mkdown 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mkdown/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ __version__ = "0.0.2"
2
+
3
+
4
+ from mkdown.processors.extracttitlepreprocessor import ExtractTitleTreeprocessor
5
+
6
+
7
+ __all__ = ["ExtractTitleTreeprocessor"]
File without changes
@@ -0,0 +1,442 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from enum import Enum
5
+ from html import escape
6
+
7
+
8
+ class AdmonitionType(Enum):
9
+ NOTE = "note"
10
+ WARNING = "warning"
11
+ DANGER = "danger"
12
+ TIP = "tip"
13
+ INFO = "info"
14
+ CAUTION = "caution"
15
+ IMPORTANT = "important"
16
+ SUCCESS = "success"
17
+
18
+ @property
19
+ def default_icon(self) -> str:
20
+ ICON_MAP = {
21
+ "note": "📝",
22
+ "warning": "âš ī¸",
23
+ "danger": "🚨",
24
+ "tip": "💡",
25
+ "info": "â„šī¸",
26
+ "caution": "âš ī¸",
27
+ "important": "❗",
28
+ "success": "✅",
29
+ }
30
+ return ICON_MAP.get(self.value, "â„šī¸")
31
+
32
+ @property
33
+ def default_aria_role(self) -> str:
34
+ ROLE_MAP = {
35
+ "note": "note",
36
+ "warning": "alert",
37
+ "danger": "alert",
38
+ "tip": "note",
39
+ "info": "note",
40
+ "caution": "alert",
41
+ "important": "alert",
42
+ "success": "status",
43
+ }
44
+ return ROLE_MAP.get(self.value, "note")
45
+
46
+
47
+ class CustomAdmonitionType:
48
+ def __init__(
49
+ self,
50
+ name: str,
51
+ icon: str | None = None,
52
+ aria_role: str = "note",
53
+ css_class: str | None = None,
54
+ color: str | None = None,
55
+ ):
56
+ self.name = name
57
+ self.value = name.lower()
58
+ self.icon = icon
59
+ self.aria_role = aria_role
60
+ self.css_class = css_class or self.value
61
+ self.color = color
62
+
63
+ def __eq__(self, other):
64
+ if isinstance(other, CustomAdmonitionType):
65
+ return self.value == other.value
66
+ return False
67
+
68
+
69
+ class MarkdownFlavor(Enum):
70
+ SPHINX = "sphinx"
71
+ MKDOCS = "mkdocs"
72
+ DOCUSAURUS = "docusaurus"
73
+ GITHUB = "github"
74
+ GITLAB = "gitlab"
75
+ COMMONMARK = "commonmark"
76
+ HTML = "html"
77
+
78
+
79
+ @dataclass
80
+ class ThemeSupport:
81
+ name: str
82
+ css_framework: str
83
+ css_classes: dict[str, str]
84
+ custom_icons: dict[str, str]
85
+ custom_colors: dict[str, str]
86
+ supports_dark_mode: bool = False
87
+ rtl_support: bool = False
88
+
89
+
90
+ @dataclass
91
+ class AdmonitionMetadata:
92
+ """Metadata for admonition support in different flavors"""
93
+
94
+ required_extensions: set[str]
95
+ supported_types: set[AdmonitionType]
96
+ allows_custom_types: bool
97
+ allows_custom_titles: bool
98
+ allows_collapsible: bool
99
+ allows_nesting: bool
100
+ syntax_type: str # "directive", "block", "html"
101
+ css_classes: list[str] = field(default_factory=list)
102
+ icon_support: bool = False
103
+ default_css_framework: str | None = None
104
+ supported_themes: dict[str, ThemeSupport] = field(default_factory=dict)
105
+ accessibility_features: set[str] = field(default_factory=set)
106
+ custom_types: dict[str, CustomAdmonitionType] = field(default_factory=dict)
107
+ max_nesting_level: int = 1
108
+
109
+
110
+ class AdmonitionFormatter:
111
+ """Base class for formatting admonitions"""
112
+
113
+ def format(
114
+ self,
115
+ admonition: Admonition,
116
+ strict: bool = False,
117
+ theme: str | None = None,
118
+ **kwargs,
119
+ ) -> str:
120
+ raise NotImplementedError
121
+
122
+ def _get_effective_title(
123
+ self, admonition: Admonition, metadata: AdmonitionMetadata
124
+ ) -> str:
125
+ if metadata.allows_custom_titles:
126
+ return admonition.title
127
+ return admonition.admonition_type.value.title()
128
+
129
+ def _process_nested_content(
130
+ self, content: str, level: int, metadata: AdmonitionMetadata
131
+ ) -> str:
132
+ if level > metadata.max_nesting_level:
133
+ return content
134
+ # Process nested admonitions in content
135
+ # This would need to parse the content and handle nested admonitions
136
+ return content
137
+
138
+
139
+ class HTMLFormatter(AdmonitionFormatter):
140
+ def format(
141
+ self,
142
+ admonition: Admonition,
143
+ strict: bool = False,
144
+ theme: str | None = None,
145
+ **kwargs,
146
+ ) -> str:
147
+ metadata = AdmonitionSupport.METADATA[MarkdownFlavor.HTML]
148
+ theme_support = metadata.supported_themes.get(theme) if theme else None
149
+
150
+ css_class = f"admonition {admonition.admonition_type.value}"
151
+ if admonition.custom_class:
152
+ css_class += f" {admonition.custom_class}"
153
+ if theme_support:
154
+ css_class += (
155
+ f" {theme_support.css_classes.get(admonition.admonition_type.value, '')}"
156
+ )
157
+
158
+ icon_html = ""
159
+ if admonition.icon and metadata.icon_support:
160
+ theme_icon = (
161
+ theme_support.custom_icons.get(admonition.admonition_type.value)
162
+ if theme_support
163
+ else None
164
+ )
165
+ icon = theme_icon or admonition.icon
166
+ icon_html = (
167
+ f'<span class="admonition-icon" aria-hidden="true">{escape(icon)}</span>'
168
+ )
169
+
170
+ collapse_attrs = ' class="collapse"' if admonition.collapse else ""
171
+
172
+ # Add accessibility attributes
173
+ aria_role = (
174
+ admonition.admonition_type.default_aria_role
175
+ if isinstance(admonition.admonition_type, AdmonitionType)
176
+ else "note"
177
+ )
178
+
179
+ return f"""
180
+ <div class="{css_class}" role="{aria_role}">
181
+ <div class="admonition-title"{collapse_attrs}>
182
+ {icon_html}
183
+ <span class="admonition-title-text">{escape(admonition.title)}</span>
184
+ </div>
185
+ <div class="admonition-content">
186
+ {admonition._process_nested_content(escape(admonition.content))}
187
+ </div>
188
+ </div>
189
+ """.strip()
190
+
191
+
192
+ class AdmonitionSupport:
193
+ """Registry of markdown flavor support for admonitions"""
194
+
195
+ # Define common themes and their support
196
+ MATERIAL_THEME = ThemeSupport(
197
+ name="material",
198
+ css_framework="material",
199
+ css_classes={
200
+ "note": "md-note",
201
+ "warning": "md-warning",
202
+ # ... other type classes
203
+ },
204
+ custom_icons={
205
+ "note": "<svg>...</svg>", # Material Design icons
206
+ "warning": "<svg>...</svg>",
207
+ # ... other icons
208
+ },
209
+ custom_colors={
210
+ "note": "#448aff",
211
+ "warning": "#ff9100",
212
+ # ... other colors
213
+ },
214
+ supports_dark_mode=True,
215
+ rtl_support=True,
216
+ )
217
+
218
+ SPHINX_THEME = ThemeSupport(
219
+ name="sphinx_rtd",
220
+ css_framework="sphinx",
221
+ css_classes={
222
+ "note": "sphinx-note",
223
+ "warning": "sphinx-warning",
224
+ # ... other classes
225
+ },
226
+ custom_icons={}, # Sphinx doesn't use icons by default
227
+ custom_colors={},
228
+ supports_dark_mode=False,
229
+ rtl_support=True,
230
+ )
231
+
232
+ METADATA = {
233
+ MarkdownFlavor.SPHINX: AdmonitionMetadata(
234
+ required_extensions=set(),
235
+ supported_types=set(AdmonitionType),
236
+ allows_custom_types=True,
237
+ allows_custom_titles=True,
238
+ allows_collapsible=False,
239
+ allows_nesting=True,
240
+ syntax_type="directive",
241
+ accessibility_features={"aria-roles", "semantic-markup"},
242
+ supported_themes={
243
+ "sphinx_rtd": SPHINX_THEME,
244
+ # ... other Sphinx themes
245
+ },
246
+ max_nesting_level=2,
247
+ ),
248
+ MarkdownFlavor.MKDOCS: AdmonitionMetadata(
249
+ required_extensions={"admonition", "pymdownx.details"},
250
+ supported_types=set(AdmonitionType),
251
+ allows_custom_types=True,
252
+ allows_custom_titles=True,
253
+ allows_collapsible=True,
254
+ allows_nesting=True,
255
+ syntax_type="block",
256
+ icon_support=True,
257
+ accessibility_features={"aria-roles", "semantic-markup", "color-contrast"},
258
+ supported_themes={
259
+ "material": MATERIAL_THEME,
260
+ # ... other MkDocs themes
261
+ },
262
+ max_nesting_level=3,
263
+ ),
264
+ # ... other flavors
265
+ }
266
+
267
+ @classmethod
268
+ def register_custom_type(
269
+ cls, custom_type: CustomAdmonitionType, flavor: MarkdownFlavor
270
+ ) -> None:
271
+ """Register a custom admonition type for a specific flavor"""
272
+ metadata = cls.METADATA.get(flavor)
273
+ if metadata and metadata.allows_custom_types:
274
+ metadata.custom_types[custom_type.value] = custom_type
275
+
276
+ @classmethod
277
+ def get_css(
278
+ cls, framework: str = "custom", theme: str | None = None, dark_mode: bool = False
279
+ ) -> str:
280
+ """Return CSS for styling admonitions"""
281
+ if framework == "custom":
282
+ dark_mode_css = (
283
+ """
284
+ @media (prefers-color-scheme: dark) {
285
+ .admonition { background: #1a1a1a; }
286
+ .admonition.note { border-color: #448aff; background: #1a1f2f; }
287
+ /* ... other dark mode styles ... */
288
+ }
289
+ """
290
+ if dark_mode
291
+ else ""
292
+ )
293
+
294
+ return f"""
295
+ .admonition {{
296
+ margin: 1em 0;
297
+ padding: 0.1em 1em;
298
+ border-left: 4px solid;
299
+ border-radius: 4px;
300
+ transition: all 0.3s ease;
301
+ }}
302
+ .admonition-title {{
303
+ font-weight: bold;
304
+ margin: 0.5em 0;
305
+ display: flex;
306
+ align-items: center;
307
+ gap: 0.5em;
308
+ }}
309
+ .admonition-icon {{
310
+ display: inline-flex;
311
+ align-items: center;
312
+ }}
313
+ .admonition.note {{ border-color: #448aff; background: #f1f8ff; }}
314
+ .admonition.warning {{ border-color: #ff9100; background: #fff8f0; }}
315
+ .admonition.danger {{ border-color: #ff1744; background: #fff1f0; }}
316
+ /* Nested admonition styles */
317
+ .admonition .admonition {{
318
+ margin-left: 1em;
319
+ margin-right: 1em;
320
+ }}
321
+ /* Collapse styles */
322
+ .admonition-title.collapse + .admonition-content {{
323
+ display: none;
324
+ }}
325
+ .admonition-title.collapse.active + .admonition-content {{
326
+ display: block;
327
+ }}
328
+ {dark_mode_css}
329
+ """.strip()
330
+ return "" # Add other framework CSS as needed
331
+
332
+
333
+ class Admonition:
334
+ def __init__(
335
+ self,
336
+ content: str,
337
+ admonition_type: AdmonitionType | CustomAdmonitionType,
338
+ title: str | None = None,
339
+ collapse: bool = False,
340
+ icon: str | None = None,
341
+ custom_class: str | None = None,
342
+ nesting_level: int = 0,
343
+ ):
344
+ self.content = content
345
+ self.admonition_type = admonition_type
346
+ self.title = title or (
347
+ admonition_type.value.title()
348
+ if isinstance(admonition_type, AdmonitionType)
349
+ else admonition_type.name
350
+ )
351
+ self.collapse = collapse
352
+ self.icon = icon or (
353
+ admonition_type.default_icon
354
+ if isinstance(admonition_type, AdmonitionType)
355
+ else admonition_type.icon
356
+ )
357
+ self.custom_class = custom_class
358
+ self.nesting_level = nesting_level
359
+
360
+ def to_markdown(
361
+ self,
362
+ flavor: MarkdownFlavor,
363
+ strict: bool = False,
364
+ theme: str | None = None,
365
+ **kwargs,
366
+ ) -> str:
367
+ metadata = AdmonitionSupport.METADATA.get(flavor)
368
+ if not metadata:
369
+ if strict:
370
+ raise ValueError(f"Unsupported markdown flavor: {flavor}")
371
+ return self.to_markdown(MarkdownFlavor.COMMONMARK)
372
+
373
+ # Validation in strict mode
374
+ if strict:
375
+ if (
376
+ isinstance(self.admonition_type, AdmonitionType)
377
+ and self.admonition_type not in metadata.supported_types
378
+ ):
379
+ raise ValueError(
380
+ f"Admonition type {self.admonition_type} not supported in {flavor}"
381
+ )
382
+ if self.collapse and not metadata.allows_collapsible:
383
+ raise ValueError(f"Collapsible admonitions not supported in {flavor}")
384
+ if self.icon and not metadata.icon_support:
385
+ raise ValueError(f"Icons not supported in {flavor}")
386
+ if self.nesting_level > metadata.max_nesting_level:
387
+ raise ValueError(
388
+ f"Nesting level {self.nesting_level} exceeds maximum of {metadata.max_nesting_level}"
389
+ )
390
+
391
+ formatter = AdmonitionSupport.FORMATTERS.get(flavor)
392
+ if not formatter:
393
+ if strict:
394
+ raise ValueError(f"No formatter available for {flavor}")
395
+ return self.to_markdown(MarkdownFlavor.COMMONMARK)
396
+
397
+ return formatter.format(self, strict=strict, theme=theme, **kwargs)
398
+
399
+ def to_html(
400
+ self, theme: str | None = None, css_framework: str | None = None, **kwargs
401
+ ) -> str:
402
+ """Convert admonition to HTML with optional theme and CSS framework"""
403
+ return self.to_markdown(
404
+ MarkdownFlavor.HTML, theme=theme, css_framework=css_framework, **kwargs
405
+ )
406
+
407
+ def _indent_content(self, content: str, spaces: int = 4) -> str:
408
+ return "\n".join(f"{' ' * spaces}{line}" for line in content.split("\n"))
409
+
410
+ def _process_nested_content(self, content: str) -> str:
411
+ """Process content for nested admonitions"""
412
+ if self.nesting_level > 0:
413
+ # Process nested admonition content
414
+ pass
415
+ return content
416
+
417
+
418
+ if __name__ == "__main__":
419
+ # Create a custom admonition type
420
+ custom_type = CustomAdmonitionType(
421
+ name="Example",
422
+ icon="🔍",
423
+ aria_role="note",
424
+ css_class="custom-example",
425
+ color="#7c4dff",
426
+ )
427
+
428
+ # Register the custom type
429
+ AdmonitionSupport.register_custom_type(custom_type, MarkdownFlavor.MKDOCS)
430
+
431
+ # Create an admonition with the custom type
432
+ admonition = Admonition(
433
+ content="This is a custom admonition", admonition_type=custom_type, collapse=True
434
+ )
435
+
436
+ # Convert to HTML with theme support
437
+ html = admonition.to_html(theme="material", dark_mode=True, strict=False)
438
+
439
+ # Get theme-specific CSS
440
+ css = AdmonitionSupport.get_css(
441
+ framework="material", theme="material", dark_mode=True
442
+ )
mkdown/fences.py ADDED
@@ -0,0 +1,76 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+
5
+ from mknodes.utils import log
6
+
7
+
8
+ if TYPE_CHECKING:
9
+ import markdown
10
+
11
+
12
+ logger = log.get_logger(__name__)
13
+
14
+
15
+ class CustomFence:
16
+ """Formatter wrapper."""
17
+
18
+ def __init__(self, extensions: list[str]):
19
+ self.extensions = extensions
20
+
21
+ def custom_formatter(
22
+ self,
23
+ source: str,
24
+ language: str,
25
+ css_class: str,
26
+ options: dict[str, str],
27
+ md: markdown.Markdown,
28
+ classes: list[str] | None = None,
29
+ id_value: str = "",
30
+ attrs: dict[str, str] | None = None,
31
+ **kwargs: Any,
32
+ ):
33
+ # import mknodes as mk
34
+
35
+ # node_kls = getattr(mk, language)
36
+ print(f"{language=} {css_class=} {options=} {classes=} {id_value=} {attrs=}")
37
+ try:
38
+ return md.convert(source, **kwargs)
39
+ except Exception:
40
+ logger.exception("Error for custom fence %s", language)
41
+ raise
42
+
43
+
44
+ def generate_fences() -> list[dict[str, Any]]:
45
+ import mknodes as mk
46
+
47
+ dcts: list[dict[str, Any]] = []
48
+ for node_name in mk.__all__:
49
+ dct: dict[str, Any] = {
50
+ "name": node_name,
51
+ "class": node_name,
52
+ "format": fence.custom_formatter,
53
+ }
54
+ dcts.append(dct)
55
+ return dcts
56
+
57
+
58
+ if __name__ == "__main__":
59
+ from mknodes.mdlib import mdconverter
60
+
61
+ fence = CustomFence(extensions=[])
62
+ fences = generate_fences()
63
+ md = mdconverter.MdConverter(
64
+ extensions=[
65
+ "attr_list",
66
+ "admonition",
67
+ "pymdownx.superfences",
68
+ "pymdownx.snippets",
69
+ "pymdownx.inlinehilite",
70
+ "pymdownx.highlight",
71
+ ],
72
+ custom_fences=fences,
73
+ )
74
+ text = "```\n{.MkAdmonition title='test'}\n\ntest\n\n```"
75
+ result = md.convert(text)
76
+ print(result)
mkdown/mdparser.py ADDED
@@ -0,0 +1,238 @@
1
+ import functools
2
+ import json
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ import bleach
7
+ from bs4 import BeautifulSoup
8
+ import commonmark
9
+ import markdown
10
+ import markdown2
11
+
12
+
13
+ class MarkdownConverter:
14
+ """An extended wrapper class for markdown to HTML conversion libraries.
15
+ Supports multiple markdown flavors, caching, sanitization, and custom extensions.
16
+ """
17
+
18
+ SUPPORTED_ENGINES = [
19
+ "python-markdown",
20
+ "mistune",
21
+ "markdown2",
22
+ "commonmark",
23
+ "markdownify",
24
+ "mdx_math",
25
+ ]
26
+
27
+ # Cache for converter instances
28
+ _converter_cache = {}
29
+
30
+ def __init__(
31
+ self,
32
+ engine: str = "python-markdown",
33
+ cache_enabled: bool = True,
34
+ sanitize: bool = True,
35
+ pretty_output: bool = False,
36
+ ):
37
+ """Initialize the markdown converter.
38
+
39
+ Args:
40
+ engine (str): The markdown engine to use
41
+ cache_enabled (bool): Whether to cache converter instances
42
+ sanitize (bool): Whether to sanitize HTML output
43
+ pretty_output (bool): Whether to format HTML output
44
+ """
45
+ if engine not in self.SUPPORTED_ENGINES:
46
+ raise ValueError(f"Unsupported engine. Choose from: {self.SUPPORTED_ENGINES}")
47
+
48
+ self.engine = engine
49
+ self.cache_enabled = cache_enabled
50
+ self.sanitize = sanitize
51
+ self.pretty_output = pretty_output
52
+ self._setup_engine()
53
+
54
+ def _get_cache_key(self, extensions: list[str] | None, **kwargs) -> str:
55
+ """Generate a cache key based on configuration."""
56
+ cache_data = {
57
+ "engine": self.engine,
58
+ "extensions": sorted(extensions) if extensions else None,
59
+ **kwargs,
60
+ }
61
+ return json.dumps(cache_data, sort_keys=True)
62
+
63
+ @functools.lru_cache(maxsize=128)
64
+ def _get_cached_converter(self, cache_key: str):
65
+ """Get or create a cached converter instance."""
66
+ return self._converter_cache.get(cache_key)
67
+
68
+ def _setup_engine(self):
69
+ """Set up the chosen markdown engine with default configurations."""
70
+ if self.engine == "python-markdown":
71
+ import markdown
72
+
73
+ self.converter = markdown.Markdown(extensions=["extra"])
74
+ elif self.engine == "mistune":
75
+ import mistune
76
+
77
+ self.converter = mistune.create_markdown()
78
+ elif self.engine == "markdown2":
79
+ import markdown2
80
+
81
+ self.converter = markdown2.Markdown()
82
+ elif self.engine == "commonmark":
83
+ import commonmark
84
+
85
+ self.converter = commonmark.Parser()
86
+ elif self.engine == "mdx_math":
87
+ self.converter = markdown.Markdown(extensions=["mdx_math"])
88
+
89
+ def load_custom_extension(self, extension_path: str | Path) -> Any:
90
+ """Load a custom markdown extension from a Python file.
91
+
92
+ Args:
93
+ extension_path: Path to the extension file
94
+ Returns:
95
+ The loaded extension class/object
96
+ """
97
+ extension_path = Path(extension_path)
98
+ if not extension_path.exists():
99
+ raise FileNotFoundError(f"Extension file not found: {extension_path}")
100
+
101
+ import importlib.util
102
+
103
+ spec = importlib.util.spec_from_file_location(extension_path.stem, extension_path)
104
+ module = importlib.util.module_from_spec(spec)
105
+ spec.loader.exec_module(module)
106
+ return module.Extension
107
+
108
+ def sanitize_html(self, html_content: str, **kwargs) -> str:
109
+ """Sanitize HTML content using bleach.
110
+
111
+ Args:
112
+ html_content: HTML content to sanitize
113
+ **kwargs: Additional bleach options
114
+ Returns:
115
+ Sanitized HTML content
116
+ """
117
+ allowed_tags = kwargs.get("allowed_tags", bleach.ALLOWED_TAGS)
118
+ allowed_attributes = kwargs.get("allowed_attributes", bleach.ALLOWED_ATTRIBUTES)
119
+ allowed_protocols = kwargs.get("allowed_protocols", bleach.ALLOWED_PROTOCOLS)
120
+
121
+ return bleach.clean(
122
+ html_content,
123
+ tags=allowed_tags,
124
+ attributes=allowed_attributes,
125
+ protocols=allowed_protocols,
126
+ strip=kwargs.get("strip", True),
127
+ strip_comments=kwargs.get("strip_comments", True),
128
+ )
129
+
130
+ def format_html(self, html_content: str) -> str:
131
+ """Format HTML content for better readability."""
132
+ soup = BeautifulSoup(html_content, "html.parser")
133
+ return soup.prettify()
134
+
135
+ def convert(
136
+ self,
137
+ text: str,
138
+ extensions: list[str] | None = None,
139
+ admonitions: bool = False,
140
+ custom_extensions: list[str | Path] | None = None,
141
+ sanitize_options: dict | None = None,
142
+ **kwargs,
143
+ ) -> str:
144
+ """Convert markdown text to HTML with extended options.
145
+
146
+ Args:
147
+ text: The markdown text to convert
148
+ extensions: List of extensions to use
149
+ admonitions: Whether to enable admonitions
150
+ custom_extensions: List of paths to custom extensions
151
+ sanitize_options: Options for HTML sanitization
152
+ **kwargs: Additional engine-specific options
153
+
154
+ Returns:
155
+ The converted HTML text
156
+ """
157
+ # Load custom extensions if provided
158
+ if custom_extensions:
159
+ loaded_extensions = [
160
+ self.load_custom_extension(ext) for ext in custom_extensions
161
+ ]
162
+ if extensions:
163
+ extensions.extend(loaded_extensions)
164
+ else:
165
+ extensions = loaded_extensions
166
+
167
+ # Get cached converter or create new one
168
+ if self.cache_enabled:
169
+ cache_key = self._get_cache_key(extensions, **kwargs)
170
+ converter = self._get_cached_converter(cache_key)
171
+ if converter:
172
+ html_content = converter.convert(text)
173
+ else:
174
+ html_content = self._convert_with_engine(
175
+ text, extensions, admonitions, **kwargs
176
+ )
177
+ self._converter_cache[cache_key] = self.converter
178
+ else:
179
+ html_content = self._convert_with_engine(
180
+ text, extensions, admonitions, **kwargs
181
+ )
182
+
183
+ # Apply sanitization if enabled
184
+ if self.sanitize:
185
+ sanitize_options = sanitize_options or {}
186
+ html_content = self.sanitize_html(html_content, **sanitize_options)
187
+
188
+ # Format output if enabled
189
+ if self.pretty_output:
190
+ html_content = self.format_html(html_content)
191
+
192
+ return html_content
193
+
194
+ def _convert_with_engine(
195
+ self, text: str, extensions: list[str] | None, admonitions: bool, **kwargs
196
+ ) -> str:
197
+ """Handle conversion with specific engine."""
198
+ if self.engine == "python-markdown":
199
+ return self._convert_python_markdown(text, extensions, admonitions, **kwargs)
200
+ if self.engine == "mistune":
201
+ return self._convert_mistune(text, **kwargs)
202
+ if self.engine == "markdown2":
203
+ return self._convert_markdown2(text, extensions, admonitions, **kwargs)
204
+ if self.engine == "commonmark":
205
+ return self._convert_commonmark(text, **kwargs)
206
+ if self.engine == "mdx_math":
207
+ return self._convert_mdx_math(text, extensions, **kwargs)
208
+ raise ValueError(f"Unsupported engine: {self.engine}")
209
+
210
+ def _convert_commonmark(self, text: str, **kwargs) -> str:
211
+ """Handle commonmark specific conversion."""
212
+ parser = commonmark.Parser()
213
+ renderer = commonmark.HtmlRenderer(**kwargs)
214
+ ast = parser.parse(text)
215
+ return renderer.render(ast)
216
+
217
+ def _convert_mdx_math(self, text: str, extensions: list[str] | None, **kwargs) -> str:
218
+ """Handle mdx_math specific conversion."""
219
+ ext_list = extensions or ["mdx_math"]
220
+ if "mdx_math" not in ext_list:
221
+ ext_list.append("mdx_math")
222
+
223
+ md = markdown.Markdown(extensions=ext_list)
224
+ return md.convert(text)
225
+
226
+ # ... (previous conversion methods remain the same)
227
+
228
+ @staticmethod
229
+ def get_supported_extensions(engine: str) -> list[str]:
230
+ """Get list of supported extensions for the specified engine."""
231
+ extension_map = {
232
+ "python-markdown": markdown.util.get_installed_extensions(),
233
+ "markdown2": markdown2.DEFAULT_EXTRAS,
234
+ "mistune": ["tables", "footnotes", "strikethrough", "task_lists"],
235
+ "commonmark": ["smartpunct", "table", "strikethrough"],
236
+ "mdx_math": ["mdx_math", "extra", "codehilite"],
237
+ }
238
+ return extension_map.get(engine, [])
File without changes
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import logging
5
+ from typing import TYPE_CHECKING
6
+
7
+ import markdown
8
+ import markdown.postprocessors
9
+ import markdown.treeprocessors
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Sequence
14
+ from xml.etree import ElementTree as ET
15
+
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class ExtractTitleTreeprocessor(markdown.treeprocessors.Treeprocessor):
21
+ """Extract title from markdown content."""
22
+
23
+ def __init__(self, md: markdown.Markdown | None = None) -> None:
24
+ super().__init__(md)
25
+ self.title: str | None = None
26
+ self.postprocessors: Sequence[markdown.postprocessors.Postprocessor] = ()
27
+
28
+ def run(self, root: ET.Element) -> ET.Element:
29
+ """Extract title from the first h1 element."""
30
+ try:
31
+ el = next(el for el in root if el.tag == "h1")
32
+ # Fix for deprecation warning: use explicit length check
33
+ if len(el) > 0 and el[-1].tag == "a" and not (el[-1].tail or "").strip():
34
+ el = copy.copy(el)
35
+ del el[-1]
36
+ # Join all text content, including nested elements
37
+ title = "".join(el.itertext())
38
+ # Apply postprocessors
39
+ for pp in self.postprocessors:
40
+ title = pp.run(title)
41
+ self.title = title.strip()
42
+
43
+ except StopIteration:
44
+ pass
45
+
46
+ return root
47
+
48
+ def _register(self, md: markdown.Markdown) -> None:
49
+ self.postprocessors = list(md.postprocessors)
50
+ md.treeprocessors.register(
51
+ self,
52
+ "mkdown_extract_title",
53
+ priority=-1, # After the end.
54
+ )
mkdown/py.typed ADDED
File without changes
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.3
2
+ Name: mkdown
3
+ Version: 0.0.2
4
+ Summary: Tools for (Python-)Markdown
5
+ Project-URL: Documentation, https://phil65.github.io/mkdown/
6
+ Project-URL: Source, https://github.com/phil65/mkdown
7
+ Author-email: Philipp Temminghoff <philipptemminghoff@googlemail.com>
8
+ License: MIT License
9
+
10
+ Copyright (c) 2024, Philipp Temminghoff
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+
30
+ Classifier: Development Status :: 4 - Beta
31
+ Classifier: Intended Audience :: Developers
32
+ Classifier: Operating System :: OS Independent
33
+ Classifier: Programming Language :: Python :: 3
34
+ Classifier: Programming Language :: Python :: 3 :: Only
35
+ Classifier: Programming Language :: Python :: 3.12
36
+ Classifier: Programming Language :: Python :: 3.13
37
+ Classifier: Programming Language :: Python :: 3.14
38
+ Classifier: Topic :: Documentation
39
+ Classifier: Topic :: Software Development
40
+ Classifier: Topic :: Utilities
41
+ Classifier: Typing :: Typed
42
+ Requires-Python: >=3.12
43
+ Requires-Dist: markdown>=3.7
44
+ Requires-Dist: pymdown-extensions>=10.12
45
+ Description-Content-Type: text/markdown
46
+
47
+ # mkdown
48
+
49
+ [![PyPI License](https://img.shields.io/pypi/l/mkdown.svg)](https://pypi.org/project/mkdown/)
50
+ [![Package status](https://img.shields.io/pypi/status/mkdown.svg)](https://pypi.org/project/mkdown/)
51
+ [![Daily downloads](https://img.shields.io/pypi/dd/mkdown.svg)](https://pypi.org/project/mkdown/)
52
+ [![Weekly downloads](https://img.shields.io/pypi/dw/mkdown.svg)](https://pypi.org/project/mkdown/)
53
+ [![Monthly downloads](https://img.shields.io/pypi/dm/mkdown.svg)](https://pypi.org/project/mkdown/)
54
+ [![Distribution format](https://img.shields.io/pypi/format/mkdown.svg)](https://pypi.org/project/mkdown/)
55
+ [![Wheel availability](https://img.shields.io/pypi/wheel/mkdown.svg)](https://pypi.org/project/mkdown/)
56
+ [![Python version](https://img.shields.io/pypi/pyversions/mkdown.svg)](https://pypi.org/project/mkdown/)
57
+ [![Implementation](https://img.shields.io/pypi/implementation/mkdown.svg)](https://pypi.org/project/mkdown/)
58
+ [![Releases](https://img.shields.io/github/downloads/phil65/mkdown/total.svg)](https://github.com/phil65/mkdown/releases)
59
+ [![Github Contributors](https://img.shields.io/github/contributors/phil65/mkdown)](https://github.com/phil65/mkdown/graphs/contributors)
60
+ [![Github Discussions](https://img.shields.io/github/discussions/phil65/mkdown)](https://github.com/phil65/mkdown/discussions)
61
+ [![Github Forks](https://img.shields.io/github/forks/phil65/mkdown)](https://github.com/phil65/mkdown/forks)
62
+ [![Github Issues](https://img.shields.io/github/issues/phil65/mkdown)](https://github.com/phil65/mkdown/issues)
63
+ [![Github Issues](https://img.shields.io/github/issues-pr/phil65/mkdown)](https://github.com/phil65/mkdown/pulls)
64
+ [![Github Watchers](https://img.shields.io/github/watchers/phil65/mkdown)](https://github.com/phil65/mkdown/watchers)
65
+ [![Github Stars](https://img.shields.io/github/stars/phil65/mkdown)](https://github.com/phil65/mkdown/stars)
66
+ [![Github Repository size](https://img.shields.io/github/repo-size/phil65/mkdown)](https://github.com/phil65/mkdown)
67
+ [![Github last commit](https://img.shields.io/github/last-commit/phil65/mkdown)](https://github.com/phil65/mkdown/commits)
68
+ [![Github release date](https://img.shields.io/github/release-date/phil65/mkdown)](https://github.com/phil65/mkdown/releases)
69
+ [![Github language count](https://img.shields.io/github/languages/count/phil65/mkdown)](https://github.com/phil65/mkdown)
70
+ [![Github commits this week](https://img.shields.io/github/commit-activity/w/phil65/mkdown)](https://github.com/phil65/mkdown)
71
+ [![Github commits this month](https://img.shields.io/github/commit-activity/m/phil65/mkdown)](https://github.com/phil65/mkdown)
72
+ [![Github commits this year](https://img.shields.io/github/commit-activity/y/phil65/mkdown)](https://github.com/phil65/mkdown)
73
+ [![Package status](https://codecov.io/gh/phil65/mkdown/branch/main/graph/badge.svg)](https://codecov.io/gh/phil65/mkdown/)
74
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
75
+ [![PyUp](https://pyup.io/repos/github/phil65/mkdown/shield.svg)](https://pyup.io/repos/github/phil65/mkdown/)
76
+
77
+ [Read the documentation!](https://phil65.github.io/mkdown/)
78
+
@@ -0,0 +1,12 @@
1
+ mkdown/__init__.py,sha256=9oSzGp6TzIWryW5nYp_o6AsKDwgIx9fdh4ALxBXt-Yc,154
2
+ mkdown/fences.py,sha256=lYhcMKLrnr1MavXpOv-VDgkvPCcYkDhjoAlDo4dkgqo,1925
3
+ mkdown/mdparser.py,sha256=EB8FAqmeMHvoSxxRCrV9WnDHydvsSK5V3l37L6yZ2Xg,8820
4
+ mkdown/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ mkdown/elements/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ mkdown/elements/admonition.py,sha256=uzEdsuNtJbSXOv21mzQw0LAzuGmC8cg8_Fdiqjs044k,14571
7
+ mkdown/processors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ mkdown/processors/extracttitlepreprocessor.py,sha256=YBNu_dmvOokOsX9AL0ITAZLR2mqT3xnWxsGhANgtA-E,1693
9
+ mkdown-0.0.2.dist-info/METADATA,sha256=SKiVhBxYlF1_L9cv4G_sQZkQAEBmrBOigZAEfgvqwOk,5341
10
+ mkdown-0.0.2.dist-info/WHEEL,sha256=3U_NnUcV_1B1kPkYaPzN-irRckL5VW_lytn0ytO_kRY,87
11
+ mkdown-0.0.2.dist-info/licenses/LICENSE,sha256=AteGCH9r177TxxrOFEiOARrastASsf7yW6MQxlAHdwA,1078
12
+ mkdown-0.0.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.26.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024, Philipp Temminghoff
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+