mdformat-hugo 0.1.0__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.
@@ -0,0 +1,16 @@
1
+ """Mdformat plugin for Hugo-flavored Markdown."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import version
6
+
7
+ __version__ = version("mdformat-hugo")
8
+
9
+ from ._plugin import CHANGES_AST, RENDERERS, update_mdit
10
+
11
+ __all__ = [
12
+ "CHANGES_AST",
13
+ "RENDERERS",
14
+ "__version__",
15
+ "update_mdit",
16
+ ]
@@ -0,0 +1,3 @@
1
+ """Hugo markdown-it-py plugins."""
2
+
3
+ from __future__ import annotations
@@ -0,0 +1,52 @@
1
+ """Hugo shortcode preservation parser plugin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from markdown_it import MarkdownIt
9
+ from markdown_it.rules_inline import StateInline
10
+
11
+
12
+ def shortcode_plugin(md: MarkdownIt) -> None:
13
+ """Plugin to parse and format Hugo shortcodes uniformly."""
14
+ md.inline.ruler.before("text", "hugo_shortcode", _shortcode_rule_wrapper)
15
+
16
+
17
+ def _shortcode_rule_wrapper(state: StateInline, silent: bool) -> bool: # noqa: FBT001 - wrapper required by markdown-it-py API signature
18
+ """Wrap shortcode rule to convert markdown-it-py boolean to named parameter."""
19
+ return _shortcode_rule(state, should_skip_token_creation=silent)
20
+
21
+
22
+ def _shortcode_rule(state: StateInline, *, should_skip_token_creation: bool) -> bool:
23
+ """Parse Hugo shortcodes: {{< shortcode >}} and {{% shortcode %}}."""
24
+ pos = state.pos
25
+ if pos + 3 >= state.posMax or state.src[pos : pos + 3] not in {"{{<", "{{%"}:
26
+ return False
27
+
28
+ is_percent = state.src[pos : pos + 3] == "{{%"
29
+ close_marker = "%}}" if is_percent else ">}}"
30
+ content_start = pos + 3
31
+
32
+ pos = content_start
33
+ while pos < state.posMax:
34
+ if state.src[pos : pos + 3] == close_marker:
35
+ if not should_skip_token_creation: # pragma: no branch
36
+ _create_shortcode_token(state, content_start, pos, is_percent=is_percent)
37
+ state.pos = pos + 3
38
+ return True
39
+ pos += 1
40
+ return False
41
+
42
+
43
+ def _create_shortcode_token(state: StateInline, content_start: int, pos: int, *, is_percent: bool) -> None:
44
+ """Create a Hugo shortcode token."""
45
+ token = state.push("hugo_shortcode", "", 0)
46
+ token.content = state.src[content_start:pos].strip()
47
+ token.markup = "{{%" if is_percent else "{{<"
48
+
49
+
50
+ __all__ = [
51
+ "shortcode_plugin",
52
+ ]
@@ -0,0 +1,34 @@
1
+ """Mdformat plugin interface for Hugo markdown."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Final
6
+
7
+ if TYPE_CHECKING:
8
+ from collections.abc import Mapping
9
+
10
+ from markdown_it import MarkdownIt
11
+ from mdformat.renderer.typing import Render
12
+
13
+ from ._mdit_plugins.shortcodes import shortcode_plugin
14
+ from ._renderer import render_fence, render_heading, render_hugo_shortcode, render_image
15
+
16
+ CHANGES_AST: Final = True
17
+ RENDERERS: Final[Mapping[str, Render]] = {
18
+ "hugo_shortcode": render_hugo_shortcode,
19
+ "heading": render_heading,
20
+ "image": render_image,
21
+ "fence": render_fence,
22
+ }
23
+
24
+
25
+ def update_mdit(mdit: MarkdownIt) -> None:
26
+ """Add Hugo-specific markdown-it-py plugins."""
27
+ mdit.use(shortcode_plugin)
28
+
29
+
30
+ __all__ = [
31
+ "CHANGES_AST",
32
+ "RENDERERS",
33
+ "update_mdit",
34
+ ]
@@ -0,0 +1,104 @@
1
+ """Renderers for Hugo markdown elements."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import TYPE_CHECKING, Final
7
+
8
+ if TYPE_CHECKING:
9
+ from mdformat.renderer import RenderContext, RenderTreeNode
10
+
11
+ FENCE_ATTRS_PATTERN: Final = re.compile(r"^(\S+)\s+\{([^}]+)\}$")
12
+ INLINE_ATTRS_PATTERN: Final = re.compile(r"^(.*?)\s*\{([^}]+)\}\s*$")
13
+ ATTR_PATTERN: Final = re.compile(r'\.([^\s{}=]+)|#([^\s{}=]+)|([^\s{}=]+)=(?:"([^"]*)"|([^\s{}]+))')
14
+
15
+
16
+ def render_hugo_shortcode(node: RenderTreeNode, _context: RenderContext) -> str:
17
+ """Render Hugo shortcode with normalized formatting."""
18
+ content = " ".join(node.content.split())
19
+ is_percent = node.markup == "{{%"
20
+ open_delim, close_delim = ("{{%", "%}}") if is_percent else ("{{<", ">}}")
21
+ return f"{open_delim} {content} {close_delim}"
22
+
23
+
24
+ def render_image(node: RenderTreeNode, _context: RenderContext) -> str:
25
+ """Render image with optional title attribute."""
26
+ src, alt, title = node.attrs.get("src", ""), node.content, node.attrs.get("title", "")
27
+ return f'![{alt}]({src} "{title}")' if title else f"![{alt}]({src})"
28
+
29
+
30
+ def render_heading(node: RenderTreeNode, context: RenderContext) -> str:
31
+ """Render heading with optional attributes."""
32
+ markup = "#" * int(node.tag[1])
33
+ children_text = node.children[0].render(context) if node.children else ""
34
+
35
+ if match := INLINE_ATTRS_PATTERN.match(children_text):
36
+ text_part = match.group(1).strip()
37
+ attrs = _parse_attrs_from_string(match.group(2))
38
+ attrs_str = f" {_format_attrs(attrs)}"
39
+ return f"{markup} {text_part}{attrs_str}"
40
+
41
+ return f"{markup} {children_text}"
42
+
43
+
44
+ def render_fence(node: RenderTreeNode, _context: RenderContext) -> str:
45
+ """Render code fence with optional attributes from info string."""
46
+ code_block = node.content
47
+ fence_char = "`"
48
+ fence_len = max(3, _longest_consecutive_sequence(code_block, fence_char) + 1)
49
+ fence = fence_char * fence_len
50
+
51
+ info_str = node.info or ""
52
+
53
+ if match := FENCE_ATTRS_PATTERN.match(info_str):
54
+ lang = match.group(1)
55
+ attrs = _parse_attrs_from_string(match.group(2))
56
+ info_str = f"{lang} {_format_attrs(attrs)}"
57
+
58
+ return f"{fence}{info_str}\n{code_block}{fence}"
59
+
60
+
61
+ def _format_attrs(attrs: dict[str, str]) -> str:
62
+ """Format attributes dictionary with consistent ordering and sorted elements."""
63
+ parts = (
64
+ ([f"#{attrs['id']}"] if "id" in attrs else [])
65
+ + [f".{c}" for c in sorted(attrs.get("class", "").split()) if c]
66
+ + [
67
+ f'{k}="{v}"' if " " in v or "=" in v else f"{k}={v}"
68
+ for k, v in sorted(attrs.items())
69
+ if k not in {"id", "class"}
70
+ ]
71
+ )
72
+ return f"{{{' '.join(parts)}}}"
73
+
74
+
75
+ def _parse_attrs_from_string(attr_str: str) -> dict[str, str]:
76
+ """Parse attribute string into dictionary, preserving quoted values."""
77
+ attrs: dict[str, str] = {}
78
+ for match in ATTR_PATTERN.finditer(attr_str):
79
+ if class_name := match.group(1):
80
+ attrs["class"] = f"{attrs.get('class', '')} {class_name}".strip()
81
+ elif id_value := match.group(2):
82
+ attrs["id"] = id_value
83
+ else:
84
+ key = match.group(3)
85
+ value = match.group(4) if match.group(4) is not None else match.group(5)
86
+ attrs[key] = value
87
+ return attrs
88
+
89
+
90
+ def _longest_consecutive_sequence(text: str, char: str) -> int:
91
+ """Find longest consecutive sequence of char in text."""
92
+ longest = current = 0
93
+ for c in text:
94
+ current = current + 1 if c == char else 0
95
+ longest = max(longest, current)
96
+ return longest
97
+
98
+
99
+ __all__ = [
100
+ "render_fence",
101
+ "render_heading",
102
+ "render_hugo_shortcode",
103
+ "render_image",
104
+ ]
mdformat_hugo/py.typed ADDED
File without changes
@@ -0,0 +1,173 @@
1
+ Metadata-Version: 2.4
2
+ Name: mdformat-hugo
3
+ Version: 0.1.0
4
+ Summary: Mdformat plugin for Hugo-flavored Markdown
5
+ Project-URL: Documentation, https://mdformat-hugo.readthedocs.io
6
+ Project-URL: Homepage, https://github.com/gaborbernat/mdformat-hugo
7
+ Project-URL: Source, https://github.com/gaborbernat/mdformat-hugo
8
+ Project-URL: Tracker, https://github.com/gaborbernat/mdformat-hugo/issues
9
+ Maintainer-email: Bernát Gábor <gaborjbernat@gmail.com>
10
+ License: MIT License
11
+
12
+ Copyright (c) 2026 Bernát Gábor
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+ License-File: LICENSE
32
+ Keywords: formatter,hugo,markdown,mdformat
33
+ Classifier: Development Status :: 4 - Beta
34
+ Classifier: Intended Audience :: Developers
35
+ Classifier: License :: OSI Approved :: MIT License
36
+ Classifier: Operating System :: OS Independent
37
+ Classifier: Programming Language :: Python
38
+ Classifier: Programming Language :: Python :: 3 :: Only
39
+ Classifier: Programming Language :: Python :: 3.11
40
+ Classifier: Programming Language :: Python :: 3.12
41
+ Classifier: Programming Language :: Python :: 3.13
42
+ Classifier: Programming Language :: Python :: 3.14
43
+ Classifier: Programming Language :: Python :: Implementation :: CPython
44
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
45
+ Requires-Python: >=3.11
46
+ Requires-Dist: markdown-it-py>=3
47
+ Requires-Dist: mdformat-config>=0.1.3
48
+ Requires-Dist: mdformat-deflist>=0.1.2
49
+ Requires-Dist: mdformat-footnote>=0.1.1
50
+ Requires-Dist: mdformat-front-matters>=2
51
+ Requires-Dist: mdformat-gfm-alerts>=1
52
+ Requires-Dist: mdformat-gfm>=1
53
+ Requires-Dist: mdformat-pyproject>=0.0.1
54
+ Requires-Dist: mdformat-ruff>=0.1.3
55
+ Requires-Dist: mdformat-shfmt>=0.1
56
+ Requires-Dist: mdformat-web>=0.1
57
+ Requires-Dist: mdformat>=0.7.17
58
+ Requires-Dist: mdit-py-plugins>=0.4
59
+ Description-Content-Type: text/markdown
60
+
61
+ # mdformat-hugo
62
+
63
+ [![PyPI](https://img.shields.io/pypi/v/mdformat-hugo?style=flat-square)](https://pypi.org/project/mdformat-hugo/)
64
+ [![Supported Python versions](https://img.shields.io/pypi/pyversions/mdformat-hugo.svg)](https://pypi.org/project/mdformat-hugo/)
65
+ [![check](https://github.com/gaborbernat/mdformat-hugo/actions/workflows/check.yaml/badge.svg)](https://github.com/gaborbernat/mdformat-hugo/actions/workflows/check.yaml)
66
+
67
+ Mdformat plugin for Hugo-flavored Markdown. Formats Hugo content files while preserving shortcodes and markdown
68
+ attributes.
69
+
70
+ ## Features
71
+
72
+ This plugin adds support for Hugo-specific markdown syntax:
73
+
74
+ ### Shortcode Formatting
75
+
76
+ Hugo shortcodes are formatted with normalized whitespace.
77
+
78
+ **Input:**
79
+
80
+ ```markdown
81
+ {{< ref "documentation.md" >}}
82
+ {{% note %}}
83
+ ```
84
+
85
+ **Output:**
86
+
87
+ ```markdown
88
+ {{< ref "documentation.md" >}}
89
+ {{% note %}}
90
+ ```
91
+
92
+ Both `{{< >}}` (no markdown processing) and `{{% %}}` (markdown processed) shortcode styles are supported.
93
+
94
+ ### Markdown Attributes
95
+
96
+ Hugo extends standard Markdown with [markdown attributes](https://gohugo.io/content-management/markdown-attributes/) --
97
+ a syntax for attaching HTML attributes (IDs, classes, and key-value pairs) to rendered elements. Attributes are written
98
+ in curly braces after the element they modify, e.g., `{#my-id .my-class key=value}`.
99
+
100
+ This plugin normalizes attribute order and formatting:
101
+
102
+ 1. **IDs** (`#id`) come first
103
+ 1. **Classes** (`.class`) follow, sorted alphabetically
104
+ 1. **Key-value pairs** (`key=value`) come last, sorted alphabetically by key
105
+ 1. Values containing spaces or `=` are quoted: `key="hello world"`; otherwise unquoted: `key=value`
106
+
107
+ **Headings:**
108
+
109
+ ```markdown
110
+ ## Introduction {.zebra .apple #intro}
111
+ ```
112
+
113
+ Formats to:
114
+
115
+ ```markdown
116
+ ## Introduction {#intro .apple .zebra}
117
+ ```
118
+
119
+ **Images:**
120
+
121
+ ```markdown
122
+ ![Logo](logo.png){width=300 .img-fluid height=200}
123
+ ```
124
+
125
+ Formats to:
126
+
127
+ ```markdown
128
+ ![Logo](logo.png){.img-fluid height=200 width=300}
129
+ ```
130
+
131
+ **Code blocks:**
132
+
133
+ ````
134
+ ```python {linenos=table .highlight #code}
135
+ def hello():
136
+ print("world")
137
+ ```
138
+ ````
139
+
140
+ Formats to:
141
+
142
+ ````
143
+ ```python {#code .highlight linenos=table}
144
+ def hello():
145
+ print("world")
146
+ ```
147
+ ````
148
+
149
+ ### Additional Features
150
+
151
+ This plugin bundles support for Hugo markdown features and code block formatting via dependencies:
152
+
153
+ **Markdown syntax:**
154
+
155
+ - [mdformat-gfm](https://github.com/hukkin/mdformat-gfm) - GFM tables, strikethrough, task lists, autolinks
156
+ - [mdformat-front-matters](https://github.com/kyleking/mdformat-front-matters) - TOML/YAML/JSON frontmatter
157
+ - [mdformat-gfm-alerts](https://github.com/KyleKing/mdformat-gfm-alerts) - Blockquote alerts (`[!NOTE]`, `[!WARNING]`)
158
+ - [mdformat-footnote](https://github.com/executablebooks/mdformat-footnote) - Pandoc-style footnotes
159
+ - [mdformat-deflist](https://github.com/executablebooks/mdformat-deflist) - Definition lists
160
+
161
+ **Code block formatting:**
162
+
163
+ - [mdformat-ruff](https://github.com/Freed-Wu/mdformat-ruff) - Format Python code blocks with ruff
164
+ - [mdformat-shfmt](https://github.com/hukkin/mdformat-shfmt) - Format shell code blocks with shfmt
165
+ - [mdformat-config](https://github.com/hukkin/mdformat-config) - Format JSON, YAML, TOML code blocks
166
+ - [mdformat-web](https://github.com/hukkin/mdformat-web) - Format HTML, CSS, JavaScript code blocks
167
+ - [mdformat-pyproject](https://github.com/csala/mdformat-pyproject) - Format pyproject.toml in code blocks
168
+
169
+ ## Usage
170
+
171
+ ```bash
172
+ mdformat content/
173
+ ```
@@ -0,0 +1,11 @@
1
+ mdformat_hugo/__init__.py,sha256=3O9_sZqQ0vktjvdh5N65w3IlH7HdkzZgagoye0K9S2g,313
2
+ mdformat_hugo/_plugin.py,sha256=WmcepcQiboxEsfTyWg7O5YlOpRzBUL4_2LvrFjAXSO4,821
3
+ mdformat_hugo/_renderer.py,sha256=rkKnsuQXxhxFyd1g4_aEpZXOuULOIDZXRHyw_eRvhAw,3707
4
+ mdformat_hugo/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ mdformat_hugo/_mdit_plugins/__init__.py,sha256=WxPImNCoI9EnVQll8jb4hox-JcscBfJcvHYy0RcAQIQ,71
6
+ mdformat_hugo/_mdit_plugins/shortcodes.py,sha256=EirbXJdnJiaIMXBzQSdI4jqgQzcEkAHYwRBujdnRzVc,1830
7
+ mdformat_hugo-0.1.0.dist-info/METADATA,sha256=9MD0qAGi5QKC_JRqOyAMpf_1ac-3Iy7tCfBTk1xBVic,6332
8
+ mdformat_hugo-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
9
+ mdformat_hugo-0.1.0.dist-info/entry_points.txt,sha256=VfcV4gU5q6xqI4b6stW4JKllUh8Cp9imJF-tfq-iCFo,49
10
+ mdformat_hugo-0.1.0.dist-info/licenses/LICENSE,sha256=vOxHGaCaxBpCypg8AG7-s7tzNPEx-MqOSxGt6fWRjKQ,1071
11
+ mdformat_hugo-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [mdformat.parser_extension]
2
+ hugo = mdformat_hugo
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bernát Gábor
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.