mdformat-obsidian 0.2.0__tar.gz

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Kyle King
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.
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: mdformat_obsidian
3
+ Version: 0.2.0
4
+ Keywords: markdown,markdown-it,mdformat,mdformat_plugin_template
5
+ Author: kyleking
6
+ Author-email: kyleking <dev.act.kyle@gmail.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
+ Requires-Dist: mdformat>=0.7.19
14
+ Requires-Dist: mdformat-gfm>=1.0.0
15
+ Requires-Dist: mdit-py-plugins>=0.4.1
16
+ Requires-Dist: mdformat-beautysh>=0.1.1 ; extra == 'recommended'
17
+ Requires-Dist: mdformat-config>=0.2.1 ; extra == 'recommended'
18
+ Requires-Dist: mdformat-frontmatter>=2.0.8 ; extra == 'recommended'
19
+ Requires-Dist: mdformat-ruff>=0.1.3 ; extra == 'recommended'
20
+ Requires-Dist: mdformat-simple-breaks>=0.0.1 ; extra == 'recommended'
21
+ Requires-Dist: mdformat-web>=0.1.0 ; extra == 'recommended'
22
+ Requires-Dist: mdformat-wikilink>=0.2.0 ; extra == 'recommended'
23
+ Requires-Dist: setuptools ; extra == 'recommended'
24
+ Requires-Dist: pytest>=9.0.1 ; extra == 'test'
25
+ Requires-Dist: pytest-beartype>=0.2.0 ; extra == 'test'
26
+ Requires-Dist: pytest-cov>=7.0.0 ; extra == 'test'
27
+ Requires-Python: >=3.10.0
28
+ Project-URL: Bug Tracker, https://github.com/kyleking/mdformat-obsidian/issues
29
+ Project-URL: Changelog, https://github.com/kyleking/mdformat-obsidian/releases
30
+ Project-URL: homepage, https://github.com/kyleking/mdformat-obsidian
31
+ Provides-Extra: recommended
32
+ Provides-Extra: test
33
+ Description-Content-Type: text/markdown
34
+
35
+ # mdformat-obsidian
36
+
37
+ [![Build Status][ci-badge]][ci-link] [![PyPI version][pypi-badge]][pypi-link]
38
+
39
+ <!-- [![codecov.io][cov-badge]][cov-link]
40
+ [cov-badge]: https://codecov.io/gh/executablebooks/mdformat-obsidian/branch/main/graph/badge.svg
41
+ [cov-link]: https://codecov.io/gh/executablebooks/mdformat-obsidian
42
+ -->
43
+
44
+ An [mdformat](https://github.com/executablebooks/mdformat) plugin for [Obsidian Flavored Markdown](https://help.obsidian.md/Editing+and+formatting/Obsidian+Flavored+Markdown). This plugin directly supports [Callouts](https://help.obsidian.md/Editing+and+formatting/Callouts), inline footnotes, task lists with custom markers, and dollar math. See the test directory for supported formats.
45
+
46
+ > [!NOTE]
47
+ > The format for [GitHub Alerts](https://github.com/kyleking/mdformat-gfm-alerts) differs slightly from Obsidian, so they are not fully compatible. Obsidian supports folding, custom titles, and is case insensitive. To improve interoperability, this package makes the stylistic choice of capitalizing the text within `[!...]`.
48
+
49
+ ## `mdformat` Usage
50
+
51
+ Add this package wherever you use `mdformat` and the plugin will be auto-recognized. No additional configuration necessary. See [additional information on `mdformat` plugins here](https://mdformat.readthedocs.io/en/stable/users/plugins.html)
52
+
53
+ **Tip**: this package specifies an "extra" (`'recommended'`) for plugins that work well with `GFM`:
54
+
55
+ - [mdformat-beautysh](https://pypi.org/project/mdformat-beautysh)
56
+ - [mdformat-black](https://pypi.org/project/mdformat-black)
57
+ - [mdformat-config](https://pypi.org/project/mdformat-config)
58
+ - [mdformat-frontmatter](https://pypi.org/project/mdformat-frontmatter)
59
+ - [mdformat-simple-breaks](https://pypi.org/project/mdformat-simple-breaks)
60
+ - [mdformat-web](https://pypi.org/project/mdformat-web)
61
+ - [mdformat-wikilink](https://github.com/tmr232/mdformat-wikilink)
62
+
63
+ ### Pre-Commit
64
+
65
+ ```yaml
66
+ repos:
67
+ - repo: https://github.com/executablebooks/mdformat
68
+ rev: 0.7.18
69
+ hooks:
70
+ - id: mdformat
71
+ additional_dependencies:
72
+ - mdformat-obsidian
73
+ # Or
74
+ # - "mdformat-obsidian[recommended]"
75
+ ```
76
+
77
+ ### pipx
78
+
79
+ ```sh
80
+ pipx install mdformat
81
+ pipx inject mdformat mdformat-obsidian
82
+ # Or
83
+ # pipx inject mdformat "mdformat-obsidian[recommended]"
84
+ ```
85
+
86
+ ## HTML Rendering
87
+
88
+ To generate HTML output, `obsidian_plugin` can be imported from `mdit_plugins`. For more guidance on `MarkdownIt`, see the docs: <https://markdown-it-py.readthedocs.io/en/latest/using.html#the-parser>
89
+
90
+ ```py
91
+ from markdown_it import MarkdownIt
92
+
93
+ from mdformat_obsidian.mdit_plugins import obsidian_plugin
94
+
95
+ md = MarkdownIt()
96
+ md.use(obsidian_plugin)
97
+
98
+ text = "> [!tip] Callouts can have custom titles\n> Like this one."
99
+ md.render(text)
100
+ # <blockquote>
101
+ # <div data-callout-metadata="" data-callout-fold="" data-callout="tip" class="callout">
102
+ # <div class="callout-title">
103
+ # <div class="callout-title-inner">Callouts can have custom titles</div>
104
+ # </div>
105
+ # <div class="callout-content">
106
+ # <p>Like this one.</p>
107
+ # </div>
108
+ # </div>
109
+ # </blockquote>
110
+ ```
111
+
112
+ > [!WARNING]
113
+ > The outer `<blockquote>` tag is preserved to maintain compatibility with standard Markdown parsers. For full accessibility, you may want to replace this with a `<div>` in post-processing, as the `>` blockquote syntax is being repurposed for callouts.
114
+
115
+ ## Contributing
116
+
117
+ See [CONTRIBUTING.md](https://github.com/KyleKing/mdformat-obsidian/blob/main/CONTRIBUTING.md)
118
+
119
+ [ci-badge]: https://github.com/kyleking/mdformat-obsidian/workflows/CI/badge.svg?branch=main
120
+ [ci-link]: https://github.com/kyleking/mdformat-obsidian/actions?query=workflow%3ACI+branch%3Amain+event%3Apush
121
+ [pypi-badge]: https://img.shields.io/pypi/v/mdformat-obsidian.svg
122
+ [pypi-link]: https://pypi.org/project/mdformat-obsidian
@@ -0,0 +1,88 @@
1
+ # mdformat-obsidian
2
+
3
+ [![Build Status][ci-badge]][ci-link] [![PyPI version][pypi-badge]][pypi-link]
4
+
5
+ <!-- [![codecov.io][cov-badge]][cov-link]
6
+ [cov-badge]: https://codecov.io/gh/executablebooks/mdformat-obsidian/branch/main/graph/badge.svg
7
+ [cov-link]: https://codecov.io/gh/executablebooks/mdformat-obsidian
8
+ -->
9
+
10
+ An [mdformat](https://github.com/executablebooks/mdformat) plugin for [Obsidian Flavored Markdown](https://help.obsidian.md/Editing+and+formatting/Obsidian+Flavored+Markdown). This plugin directly supports [Callouts](https://help.obsidian.md/Editing+and+formatting/Callouts), inline footnotes, task lists with custom markers, and dollar math. See the test directory for supported formats.
11
+
12
+ > [!NOTE]
13
+ > The format for [GitHub Alerts](https://github.com/kyleking/mdformat-gfm-alerts) differs slightly from Obsidian, so they are not fully compatible. Obsidian supports folding, custom titles, and is case insensitive. To improve interoperability, this package makes the stylistic choice of capitalizing the text within `[!...]`.
14
+
15
+ ## `mdformat` Usage
16
+
17
+ Add this package wherever you use `mdformat` and the plugin will be auto-recognized. No additional configuration necessary. See [additional information on `mdformat` plugins here](https://mdformat.readthedocs.io/en/stable/users/plugins.html)
18
+
19
+ **Tip**: this package specifies an "extra" (`'recommended'`) for plugins that work well with `GFM`:
20
+
21
+ - [mdformat-beautysh](https://pypi.org/project/mdformat-beautysh)
22
+ - [mdformat-black](https://pypi.org/project/mdformat-black)
23
+ - [mdformat-config](https://pypi.org/project/mdformat-config)
24
+ - [mdformat-frontmatter](https://pypi.org/project/mdformat-frontmatter)
25
+ - [mdformat-simple-breaks](https://pypi.org/project/mdformat-simple-breaks)
26
+ - [mdformat-web](https://pypi.org/project/mdformat-web)
27
+ - [mdformat-wikilink](https://github.com/tmr232/mdformat-wikilink)
28
+
29
+ ### Pre-Commit
30
+
31
+ ```yaml
32
+ repos:
33
+ - repo: https://github.com/executablebooks/mdformat
34
+ rev: 0.7.18
35
+ hooks:
36
+ - id: mdformat
37
+ additional_dependencies:
38
+ - mdformat-obsidian
39
+ # Or
40
+ # - "mdformat-obsidian[recommended]"
41
+ ```
42
+
43
+ ### pipx
44
+
45
+ ```sh
46
+ pipx install mdformat
47
+ pipx inject mdformat mdformat-obsidian
48
+ # Or
49
+ # pipx inject mdformat "mdformat-obsidian[recommended]"
50
+ ```
51
+
52
+ ## HTML Rendering
53
+
54
+ To generate HTML output, `obsidian_plugin` can be imported from `mdit_plugins`. For more guidance on `MarkdownIt`, see the docs: <https://markdown-it-py.readthedocs.io/en/latest/using.html#the-parser>
55
+
56
+ ```py
57
+ from markdown_it import MarkdownIt
58
+
59
+ from mdformat_obsidian.mdit_plugins import obsidian_plugin
60
+
61
+ md = MarkdownIt()
62
+ md.use(obsidian_plugin)
63
+
64
+ text = "> [!tip] Callouts can have custom titles\n> Like this one."
65
+ md.render(text)
66
+ # <blockquote>
67
+ # <div data-callout-metadata="" data-callout-fold="" data-callout="tip" class="callout">
68
+ # <div class="callout-title">
69
+ # <div class="callout-title-inner">Callouts can have custom titles</div>
70
+ # </div>
71
+ # <div class="callout-content">
72
+ # <p>Like this one.</p>
73
+ # </div>
74
+ # </div>
75
+ # </blockquote>
76
+ ```
77
+
78
+ > [!WARNING]
79
+ > The outer `<blockquote>` tag is preserved to maintain compatibility with standard Markdown parsers. For full accessibility, you may want to replace this with a `<div>` in post-processing, as the `>` blockquote syntax is being repurposed for callouts.
80
+
81
+ ## Contributing
82
+
83
+ See [CONTRIBUTING.md](https://github.com/KyleKing/mdformat-obsidian/blob/main/CONTRIBUTING.md)
84
+
85
+ [ci-badge]: https://github.com/kyleking/mdformat-obsidian/workflows/CI/badge.svg?branch=main
86
+ [ci-link]: https://github.com/kyleking/mdformat-obsidian/actions?query=workflow%3ACI+branch%3Amain+event%3Apush
87
+ [pypi-badge]: https://img.shields.io/pypi/v/mdformat-obsidian.svg
88
+ [pypi-link]: https://pypi.org/project/mdformat-obsidian
@@ -0,0 +1,9 @@
1
+ """An mdformat plugin for `obsidian`."""
2
+
3
+ __version__ = "0.2.0"
4
+
5
+ # FYI see source code for available interfaces:
6
+ # https://github.com/executablebooks/mdformat/blob/5d9b573ce33bae219087984dd148894c774f41d4/src/mdformat/plugins.py
7
+ from .plugin import RENDERERS, update_mdit
8
+
9
+ __all__ = ("RENDERERS", "update_mdit")
@@ -0,0 +1,13 @@
1
+ from ._obsidian_blockquote_factories import (
2
+ CalloutData,
3
+ new_token,
4
+ obsidian_callout_plugin_factory,
5
+ parse_possible_blockquote_admon_factory,
6
+ )
7
+
8
+ __all__ = (
9
+ "CalloutData",
10
+ "new_token",
11
+ "obsidian_callout_plugin_factory",
12
+ "parse_possible_blockquote_admon_factory",
13
+ )
@@ -0,0 +1,119 @@
1
+ """Logic Factories.
2
+
3
+ Adapted from the implementation for `mdformat-gfm-alerts`:
4
+ <https://github.com/KyleKing/mdformat-gfm-alerts/blob/a6e71db4da3a421320e75b8a9e3e3cb2dca429d7/mdformat_gfm_alerts/factories/_gfm_blockquote_factories.py>
5
+
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from collections.abc import Callable, Generator
12
+ from contextlib import contextmanager, suppress
13
+ from typing import TYPE_CHECKING, NamedTuple
14
+
15
+ from markdown_it import MarkdownIt
16
+ from markdown_it.rules_block import StateBlock
17
+ from markdown_it.rules_inline import StateInline
18
+ from mdit_py_plugins.utils import is_code_block
19
+
20
+ if TYPE_CHECKING:
21
+ from markdown_it.token import Token
22
+
23
+
24
+ # FYI: copied from mdformat_admon.factories
25
+ @contextmanager
26
+ def new_token(
27
+ state: StateBlock | StateInline,
28
+ name: str,
29
+ kind: str,
30
+ ) -> Generator[Token, None, None]:
31
+ """Create scoped token."""
32
+ yield state.push(f"{name}_open", kind, 1)
33
+ state.push(f"{name}_close", kind, -1)
34
+
35
+
36
+ # FYI: Adapted from mdformat_admon.factories
37
+ class CalloutState(NamedTuple):
38
+ """Frozen state."""
39
+
40
+ parentType: str
41
+ lineMax: int
42
+
43
+
44
+ class CalloutData(NamedTuple):
45
+ """CalloutData data for rendering."""
46
+
47
+ old_state: CalloutState
48
+ meta_text: str
49
+ fold: str
50
+ custom_title: str
51
+ next_line: int
52
+
53
+
54
+ def parse_possible_blockquote_admon_factory(
55
+ prefix: str,
56
+ patterns: set[str],
57
+ ) -> Callable[[StateBlock, int, int, bool], CalloutData | bool]:
58
+ """Generate the parser function.
59
+
60
+ Accepts set of strings that will be compiled into regular expressions.
61
+ They must have a capture group `title` and optional group `folded`.
62
+
63
+ """
64
+
65
+ def parse_possible_blockquote_admon(
66
+ state: StateBlock,
67
+ start_line: int,
68
+ end_line: int,
69
+ silent: bool,
70
+ ) -> CalloutData | bool:
71
+ if is_code_block(state, start_line):
72
+ return False
73
+
74
+ start = state.bMarks[start_line] + state.tShift[start_line]
75
+
76
+ # Exit if no match for any pattern
77
+ text = state.src[start:]
78
+ regexes = [
79
+ re.compile(rf"{pat}(?P<custom_title>(?: |<br>)[^\n]+)?", re.IGNORECASE)
80
+ for pat in patterns
81
+ ]
82
+ match = next((_m for rx in regexes if (_m := rx.match(text))), None)
83
+ if not match:
84
+ return False
85
+
86
+ # Since start is found, we can report success here in validation mode
87
+ if silent:
88
+ return True
89
+
90
+ old_state = CalloutState(
91
+ parentType=state.parentType,
92
+ lineMax=state.lineMax,
93
+ )
94
+ state.parentType = prefix
95
+
96
+ fold = ""
97
+ with suppress(IndexError):
98
+ fold = match["fold"]
99
+ return CalloutData(
100
+ old_state=old_state,
101
+ meta_text=match["title"],
102
+ fold=fold,
103
+ custom_title=match["custom_title"] or "",
104
+ next_line=end_line,
105
+ )
106
+
107
+ return parse_possible_blockquote_admon
108
+
109
+
110
+ def obsidian_callout_plugin_factory(
111
+ prefix: str,
112
+ logic: Callable[[StateBlock, int, int, bool], bool],
113
+ ) -> Callable[[MarkdownIt], None]:
114
+ """Generate the plugin function."""
115
+
116
+ def obsidian_callout_plugin(md: MarkdownIt) -> None:
117
+ md.block.ruler.before("blockquote", prefix, logic)
118
+
119
+ return obsidian_callout_plugin
@@ -0,0 +1,40 @@
1
+ from __future__ import annotations
2
+
3
+ from markdown_it import MarkdownIt
4
+ from mdit_py_plugins.dollarmath import dollarmath_plugin
5
+ from mdit_py_plugins.footnote import footnote_plugin
6
+
7
+ from ._obsidian_callouts import (
8
+ INLINE_SEP,
9
+ OBSIDIAN_CALLOUT_PREFIX,
10
+ format_obsidian_callout_markup,
11
+ obsidian_callout_plugin,
12
+ )
13
+ from ._obsidian_inline_footnotes import (
14
+ format_footnote,
15
+ format_footnote_block,
16
+ format_footnote_ref,
17
+ )
18
+ from ._obsidian_task_lists import tasklists_plugin
19
+
20
+
21
+ def obsidian_plugin(md: MarkdownIt) -> None:
22
+ """Plugin to parse Obsidian flavored Markdown."""
23
+ md.use(dollarmath_plugin)
24
+ md.use(footnote_plugin)
25
+ md.use(obsidian_callout_plugin)
26
+ md.use(tasklists_plugin)
27
+
28
+
29
+ __all__ = (
30
+ "INLINE_SEP",
31
+ "OBSIDIAN_CALLOUT_PREFIX",
32
+ "footnote_plugin",
33
+ "format_footnote",
34
+ "format_footnote_block",
35
+ "format_footnote_ref",
36
+ "format_obsidian_callout_markup",
37
+ "obsidian_callout_plugin",
38
+ "obsidian_plugin",
39
+ "tasklists_plugin",
40
+ )
@@ -0,0 +1,132 @@
1
+ """Obsidian Callouts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from markdown_it import MarkdownIt
6
+ from markdown_it.rules_block import StateBlock
7
+
8
+ from mdformat_obsidian.factories import (
9
+ CalloutData,
10
+ new_token,
11
+ parse_possible_blockquote_admon_factory,
12
+ )
13
+
14
+ OBSIDIAN_CALLOUT_PREFIX = "obsidian_callout"
15
+ """Prefix used to differentiate the parsed output."""
16
+
17
+ INLINE_SEP = "\n\n"
18
+ """Optional separator to differentiate the title and, if present, inline content."""
19
+
20
+ PATTERN = r"^\\?\[!(?P<title>[^\]]+)\\?\](?P<fold>[\-\+]?)"
21
+ """Regular expression to match Obsidian Alerts."""
22
+
23
+
24
+ def format_obsidian_callout_markup(
25
+ state: StateBlock,
26
+ start_line: int,
27
+ admonition: CalloutData,
28
+ ) -> None:
29
+ """Format markup."""
30
+ tag = admonition.meta_text.upper()
31
+ folded = bool(admonition.fold)
32
+ custom_title = admonition.custom_title
33
+ title_line = f"[!{tag}]{admonition.fold}{INLINE_SEP}{custom_title}"
34
+
35
+ with new_token(state, OBSIDIAN_CALLOUT_PREFIX, "div") as token:
36
+ token.attrs = {
37
+ "data-callout-metadata": "",
38
+ "data-callout-fold": "",
39
+ "data-callout": admonition.meta_text.lower(),
40
+ "class": "callout",
41
+ }
42
+ if folded:
43
+ token.attrs["data-callout-fold"] = "-"
44
+ token.attrs["class"] = "callout is-collapsible is-collapsed"
45
+ token.block = True
46
+ token.map = [start_line, admonition.next_line]
47
+ token.markup = title_line
48
+ with new_token(state, f"{OBSIDIAN_CALLOUT_PREFIX}_title", "div") as tkn_title:
49
+ tkn_title.attrs = {"class": "callout-title"}
50
+
51
+ title_inner = f"{OBSIDIAN_CALLOUT_PREFIX}_title_inner"
52
+ with new_token(state, title_inner, "div") as tkn_title_inner:
53
+ tkn_title_inner.attrs = {"class": "callout-title-inner"}
54
+
55
+ tkn_title_txt = state.push("inline", "", 0)
56
+ tkn_title_txt.content = admonition.custom_title.strip()
57
+ if folded:
58
+ collapsed = f"{OBSIDIAN_CALLOUT_PREFIX}_collapsed"
59
+ with new_token(state, collapsed, "div") as tkn_collapsed:
60
+ tkn_collapsed.attrs = {"class": "callout-fold is-collapsed"}
61
+
62
+ content = f"{OBSIDIAN_CALLOUT_PREFIX}_content"
63
+ with new_token(state, content, "div") as tkn_content:
64
+ tkn_content.attrs = {"class": "callout-content"}
65
+ if folded:
66
+ tkn_content.attrs["style"] = "display: none;"
67
+
68
+ state.md.block.tokenize(state, start_line + 1, admonition.next_line)
69
+
70
+ # NOTE: The blockquote wrapper cannot be replaced with a div at this stage.
71
+ # The blockquote tokens are created by markdown-it's blockquote rule before
72
+ # this plugin runs. To truly replace the blockquote, we would need to either:
73
+ # 1. Override the blockquote rule entirely (complex, breaks other features)
74
+ # 2. Post-process tokens to replace blockquote with div (may break nesting)
75
+ # For accessibility, consider post-processing the HTML output instead.
76
+ # See: https://github.com/orgs/community/discussions/16925#discussioncomment-8729846
77
+ state.parentType = "div" # admonition.old_state.parentType
78
+ state.lineMax = admonition.old_state.lineMax
79
+ state.line = admonition.next_line
80
+
81
+
82
+ def alert_logic(
83
+ state: StateBlock,
84
+ startLine: int,
85
+ endLine: int,
86
+ silent: bool,
87
+ ) -> bool:
88
+ """Parse Obsidian Alerts."""
89
+ parser_func = parse_possible_blockquote_admon_factory(
90
+ OBSIDIAN_CALLOUT_PREFIX,
91
+ {PATTERN},
92
+ )
93
+ result = parser_func(state, startLine, endLine, silent)
94
+ if isinstance(result, CalloutData):
95
+ format_obsidian_callout_markup(state, startLine, admonition=result)
96
+ return True
97
+ return result
98
+
99
+
100
+ def obsidian_callout_plugin(md: MarkdownIt) -> None:
101
+ """Install the obsidian callout plugin."""
102
+ md.block.ruler.before("blockquote", OBSIDIAN_CALLOUT_PREFIX, alert_logic)
103
+
104
+ # Register HTML renderer rules for proper HTML output
105
+ def render_callout_open(self, tokens, idx, options, env):
106
+ token = tokens[idx]
107
+ # Build attributes string using the renderer's renderAttrs method
108
+ attrs_str = self.renderAttrs(token)
109
+ # Check if next token is inline or a closing tag to avoid extra newlines
110
+ if idx + 1 < len(tokens):
111
+ next_token = tokens[idx + 1]
112
+ # Don't add newline if next is inline content or immediately closing
113
+ next_is_inline_or_close = (next_token.type == "inline" or next_token.nesting == -1)
114
+ newline = "" if next_is_inline_or_close else "\n"
115
+ else:
116
+ newline = "\n"
117
+ return f"<{token.tag}{attrs_str}>{newline}"
118
+
119
+ def render_callout_close(self, tokens, idx, options, env):
120
+ return f"</{tokens[idx].tag}>\n"
121
+
122
+ # Register renderers for all callout token types (only for HTML output)
123
+ md.add_render_rule(f"{OBSIDIAN_CALLOUT_PREFIX}_open", render_callout_open, fmt="html")
124
+ md.add_render_rule(f"{OBSIDIAN_CALLOUT_PREFIX}_close", render_callout_close, fmt="html")
125
+ md.add_render_rule(f"{OBSIDIAN_CALLOUT_PREFIX}_title_open", render_callout_open, fmt="html")
126
+ md.add_render_rule(f"{OBSIDIAN_CALLOUT_PREFIX}_title_close", render_callout_close, fmt="html")
127
+ md.add_render_rule(f"{OBSIDIAN_CALLOUT_PREFIX}_title_inner_open", render_callout_open, fmt="html")
128
+ md.add_render_rule(f"{OBSIDIAN_CALLOUT_PREFIX}_title_inner_close", render_callout_close, fmt="html")
129
+ md.add_render_rule(f"{OBSIDIAN_CALLOUT_PREFIX}_collapsed_open", render_callout_open, fmt="html")
130
+ md.add_render_rule(f"{OBSIDIAN_CALLOUT_PREFIX}_collapsed_close", render_callout_close, fmt="html")
131
+ md.add_render_rule(f"{OBSIDIAN_CALLOUT_PREFIX}_content_open", render_callout_open, fmt="html")
132
+ md.add_render_rule(f"{OBSIDIAN_CALLOUT_PREFIX}_content_close", render_callout_close, fmt="html")
@@ -0,0 +1,55 @@
1
+ """Obsidian Inline Footnotes.
2
+
3
+ Docs: https://help.obsidian.md/Editing+and+formatting/Basic+formatting+syntax#Footnotes
4
+
5
+ NOTE: Rendering support for inline footnotes (^[...]) is implemented below.
6
+ This extends the standard footnote plugin from mdit-py-plugins to support
7
+ Obsidian's inline footnote syntax in addition to standard footnote references.
8
+
9
+ Code adapted under MIT license from:
10
+ https://github.com/executablebooks/mdformat-footnote/blob/80852fc20cfba7fd0330b9ac7a1a4df983542942/mdformat_footnote/plugin.py#L19C1-L51
11
+
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import textwrap
17
+ from contextlib import suppress
18
+
19
+ from mdformat.renderer import RenderContext, RenderTreeNode
20
+
21
+
22
+ def format_footnote(node: RenderTreeNode, context: RenderContext) -> str:
23
+ """Extend footnote formatting to exclude inline."""
24
+ if not node.meta["label"]:
25
+ return ""
26
+
27
+ first_line = f"[^{node.meta['label']}]:"
28
+ indent = " " * 4
29
+ elements = []
30
+ with context.indented(len(indent)):
31
+ for child in node.children:
32
+ if child.type == "footnote_anchor":
33
+ continue
34
+ elements.append(child.render(context))
35
+ body = textwrap.indent("\n\n".join(elements), indent)
36
+ # if the first body element is a paragraph, we can start on the first line,
37
+ # otherwise we start on the second line
38
+ if body and node.children and node.children[0].type != "paragraph":
39
+ body = "\n" + body
40
+ else:
41
+ body = " " + body.lstrip()
42
+ return first_line + body
43
+
44
+
45
+ def format_footnote_ref(node: RenderTreeNode, context: RenderContext) -> str:
46
+ """Extend footnote refs to support inline footnote formatting."""
47
+ with suppress(KeyError):
48
+ return f"[^{node.meta['label']}]"
49
+ # Locate footnote content by id
50
+ content = context.env["footnotes"]["list"][node.meta["id"]]["content"]
51
+ return f"^[{content}]"
52
+
53
+
54
+ def format_footnote_block(node: RenderTreeNode, context: RenderContext) -> str:
55
+ return "\n\n".join(child.render(context) for child in node.children)
@@ -0,0 +1,66 @@
1
+ """Obsidian Task Lists.
2
+
3
+ Loosely based on:
4
+ https://github.com/executablebooks/mdit-py-plugins/blob/d11bdaf0979e6fae01c35db5a4d1f6a4b4dd8843/mdit_py_plugins/tasklists/__init__.py
5
+
6
+ Extended to supports any mark character.
7
+
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+
14
+ from markdown_it import MarkdownIt
15
+ from markdown_it.rules_core import StateCore
16
+ from markdown_it.token import Token
17
+
18
+ # Regex string to match a whitespace character, as specified in
19
+ # https://github.github.com/gfm/#whitespace-character
20
+ # (spec version 0.29-gfm (2019-04-06))
21
+ _GFM_WHITESPACE_RE = r"[ \t\n\v\f\r]"
22
+
23
+ _RE_TODO = re.compile(rf"\\?\[(?P<mark>.)\\?\]{_GFM_WHITESPACE_RE}+")
24
+
25
+
26
+ def tasklists_plugin(md: MarkdownIt) -> None:
27
+ """Task List Plugin."""
28
+
29
+ def todo_mark(tokens: list[Token], index: int) -> re.Match[str] | None:
30
+ token = tokens[index]
31
+ if (
32
+ token.type == "inline"
33
+ and tokens[index - 1].type == "paragraph_open"
34
+ and tokens[index - 2].type == "list_item_open"
35
+ ):
36
+ # leading whitespace is already stripped by markdown-it
37
+ return _RE_TODO.match(token.content)
38
+ return None
39
+
40
+ def todoify(match: re.Match[str], token: Token) -> None:
41
+ checkbox = Token("html_inline", "", 0)
42
+ mark = match["mark"].strip()
43
+ checkbox.content = f"[{mark or ' '}] "
44
+
45
+ assert token.children is not None # for mypy
46
+ # Remove escaped brackets
47
+ # Addresses when children are: \[, <mark>, \], <content>, ...
48
+ three = 3
49
+ if len(token.children) > three and token.children[three - 1].content == "]":
50
+ token.children = token.children[three:]
51
+ token.children[0].content = token.children[0].content.lstrip()
52
+ token.content = token.content.lstrip()
53
+ else:
54
+ start = match.end()
55
+ token.children[0].content = token.children[0].content[start:]
56
+ token.content = token.content[start:]
57
+ token.children.insert(0, checkbox)
58
+
59
+ def fcn(state: StateCore) -> None:
60
+ tokens = state.tokens
61
+ for idx in range(2, len(tokens) - 1):
62
+ match = todo_mark(tokens, idx)
63
+ if match:
64
+ todoify(match, tokens[idx])
65
+
66
+ md.core.ruler.after("inline", "obsidian-tasklists", fcn)
@@ -0,0 +1,96 @@
1
+ """Public Extension."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+
7
+ from markdown_it import MarkdownIt
8
+ from mdformat.renderer import RenderContext, RenderTreeNode
9
+ from mdformat.renderer.typing import Render
10
+ from mdit_py_plugins.dollarmath import dollarmath_plugin
11
+
12
+ from .mdit_plugins import (
13
+ INLINE_SEP,
14
+ OBSIDIAN_CALLOUT_PREFIX,
15
+ footnote_plugin,
16
+ format_footnote,
17
+ format_footnote_block,
18
+ format_footnote_ref,
19
+ obsidian_callout_plugin,
20
+ tasklists_plugin,
21
+ )
22
+
23
+
24
+ def update_mdit(mdit: MarkdownIt) -> None:
25
+ """Update the parser to identify Alerts."""
26
+ mdit.use(dollarmath_plugin)
27
+ mdit.use(footnote_plugin)
28
+ mdit.use(obsidian_callout_plugin)
29
+ mdit.use(tasklists_plugin)
30
+
31
+
32
+ def _render_obsidian_callout(node: RenderTreeNode, context: RenderContext) -> str:
33
+ """Render a `RenderTreeNode`."""
34
+ title_line = node.markup.replace(INLINE_SEP, "")
35
+ elements = [render for child in node.children if (render := child.render(context))]
36
+ # Do not separate the title line from the first row
37
+ return "\n".join([title_line, "\n\n".join(elements)]).rstrip()
38
+
39
+
40
+ def _no_render(
41
+ node: RenderTreeNode, # noqa: ARG001
42
+ context: RenderContext, # noqa: ARG001
43
+ ) -> str:
44
+ """Skip rendering when handled separately."""
45
+ return ""
46
+
47
+
48
+ def _recursive_render(
49
+ node: RenderTreeNode,
50
+ context: RenderContext,
51
+ ) -> str:
52
+ elements = [render for child in node.children if (render := child.render(context))]
53
+ # Do not separate the title line from the first row
54
+ return "\n\n".join(elements).rstrip()
55
+
56
+
57
+ # ================================================================================
58
+ # Dollar Math. Adapted from mdformat-myst:
59
+ # https://github.com/executablebooks/mdformat-myst/blob/e12a64c7e3f695ea7c3ba9b33abd79c219a01750/mdformat_myst/plugin.py#L53C1-L133
60
+ # ================================================================================
61
+
62
+
63
+ def _math_inline_renderer(node: RenderTreeNode, context: RenderContext) -> str: # noqa: ARG001
64
+ return f"${node.content}$"
65
+
66
+
67
+ def _math_block_renderer(node: RenderTreeNode, context: RenderContext) -> str: # noqa: ARG001
68
+ return f"$${node.content}$$"
69
+
70
+
71
+ def _math_block_label_renderer(node: RenderTreeNode, context: RenderContext) -> str: # noqa: ARG001
72
+ return f"$${node.content}$$ ({node.info})"
73
+
74
+
75
+ # ================================================================================
76
+ # End Dollar Math
77
+ # ================================================================================
78
+
79
+ # A mapping from syntax tree node type to a function that renders it.
80
+ # This can be used to overwrite renderer functions of existing syntax
81
+ # or add support for new syntax.
82
+ RENDERERS: Mapping[str, Render] = {
83
+ "footnote": format_footnote,
84
+ "footnote_block": format_footnote_block,
85
+ "footnote_ref": format_footnote_ref,
86
+ "math_block": _math_block_renderer,
87
+ "math_block_label": _math_block_label_renderer,
88
+ "math_inline": _math_inline_renderer,
89
+ OBSIDIAN_CALLOUT_PREFIX: _render_obsidian_callout,
90
+ f"{OBSIDIAN_CALLOUT_PREFIX}_title": _no_render,
91
+ f"{OBSIDIAN_CALLOUT_PREFIX}_title_inner": _no_render,
92
+ f"{OBSIDIAN_CALLOUT_PREFIX}_collapsed": _no_render,
93
+ # NOTE: The content div uses recursive_render to properly handle nested content
94
+ # without introducing extra newlines that would create unwanted block elements
95
+ f"{OBSIDIAN_CALLOUT_PREFIX}_content": _recursive_render,
96
+ }
File without changes
@@ -0,0 +1,222 @@
1
+ [build-system]
2
+ build-backend = "uv_build"
3
+ requires = ["uv_build>=0.9.10"]
4
+
5
+ [project]
6
+ authors = [
7
+ {email = "dev.act.kyle@gmail.com", name = "kyleking"},
8
+ ]
9
+ classifiers = [
10
+ "Intended Audience :: Developers",
11
+ "License :: OSI Approved :: MIT License",
12
+ "Programming Language :: Python :: 3",
13
+ "Topic :: Software Development :: Libraries :: Python Modules",
14
+ ]
15
+ dependencies = [
16
+ "mdformat >= 0.7.19",
17
+ "mdformat-gfm >= 1.0.0",
18
+ "mdit-py-plugins >= 0.4.1",
19
+ ]
20
+ keywords = ["markdown", "markdown-it", "mdformat", "mdformat_plugin_template"]
21
+ license = "MIT"
22
+ license-files = ["LICENSE"]
23
+ name = "mdformat_obsidian"
24
+ readme = "README.md"
25
+ requires-python = ">=3.10.0"
26
+ version = "0.2.0"
27
+
28
+ [project.entry-points."mdformat.parser_extension"]
29
+ obsidian = "mdformat_obsidian"
30
+
31
+ [project.optional-dependencies]
32
+ recommended = [
33
+ # Keep in-sync with README
34
+ "mdformat-beautysh >= 0.1.1",
35
+ "mdformat-config >= 0.2.1",
36
+ "mdformat-frontmatter >= 2.0.8",
37
+ "mdformat-ruff >= 0.1.3",
38
+ "mdformat-simple-breaks >= 0.0.1",
39
+ "mdformat-web >= 0.1.0",
40
+ "mdformat-wikilink >= 0.2.0",
41
+ # Patches https://github.com/lovesegfault/beautysh/issues/248 for Python 3.12
42
+ "setuptools",
43
+ ]
44
+ test = [
45
+ "pytest >= 9.0.1",
46
+ "pytest-beartype >= 0.2.0",
47
+ "pytest-cov >= 7.0.0",
48
+ ]
49
+
50
+ [project.urls]
51
+ "Bug Tracker" = "https://github.com/kyleking/mdformat-obsidian/issues"
52
+ "Changelog" = "https://github.com/kyleking/mdformat-obsidian/releases"
53
+ homepage = "https://github.com/kyleking/mdformat-obsidian"
54
+
55
+ [tool.commitizen]
56
+ tag_format = "v${version}"
57
+ version = "0.2.0"
58
+ version_files = ["mdformat_obsidian/__init__.py", "pyproject.toml:^version"]
59
+
60
+ [tool.mypy]
61
+ check_untyped_defs = true
62
+ disallow_any_generics = true
63
+ enable_error_code = ["ignore-without-code", "possibly-undefined", "redundant-expr", "truthy-bool"]
64
+ extra_checks = true
65
+ files = ["mdformat_obsidian", "tests"]
66
+ no_implicit_reexport = true
67
+ python_version = "3.10"
68
+ show_column_numbers = true
69
+ show_error_codes = true
70
+ strict_equality = true
71
+ warn_no_return = true
72
+ warn_redundant_casts = true
73
+ warn_unreachable = true
74
+ warn_unused_configs = true
75
+ warn_unused_ignores = true
76
+
77
+ [tool.pyright]
78
+ include = ["mdformat_obsidian", "tests"]
79
+ pythonVersion = "3.10"
80
+
81
+ [tool.pytest-watcher]
82
+ ignore_patterns = []
83
+ now = true
84
+ patterns = ["*.ambr", "*.md", "*.py"]
85
+ runner = "tox"
86
+ # PLANNED: requires support for TYPE_CHECKING https://github.com/beartype/beartype/issues/477
87
+ # runner_args = ["-e", "test", "--", "--exitfirst", "--failed-first", "--new-first", "-vv", "--beartype-packages=mdformat_obsidian"]
88
+ runner_args = ["-e", "test", "--", "--exitfirst", "--failed-first", "--new-first", "-vv"]
89
+
90
+ [tool.ruff]
91
+ # Docs: https://github.com/charliermarsh/ruff
92
+ # Tip: poetry run python -m ruff --explain RUF100
93
+ line-length = 88
94
+ target-version = 'py310'
95
+
96
+ [tool.ruff.lint]
97
+ ignore = [
98
+ 'ANN002', # Missing type annotation for `*args`
99
+ 'ANN003', # Missing type annotation for `**kwargs`
100
+ 'BLE001', # Do not catch blind exception: `Exception`
101
+ 'COM812', # missing-trailing-comma
102
+ 'CPY001', # Missing copyright notice at top of file
103
+ 'D203', # "1 blank line required before class docstring" (Conflicts with D211)
104
+ 'D213', # "Multi-line docstring summary should start at the second line" (Conflicts with D212)
105
+ 'DOC201', # `return` is not documented in docstring
106
+ 'DOC402', # `yield` is not documented in docstring
107
+ 'E501', # Line too long (89 > 88)
108
+ 'EM101', # Exception must not use a string literal, assign to variable first
109
+ 'FBT001', # Boolean-typed positional argument in function definition
110
+ 'FIX001', # Line contains FIXME
111
+ 'FIX002', # Line contains TODO
112
+ 'FIX004', # Line contains HACK
113
+ 'N803', # Argument name `startLine` should be lowercase
114
+ 'N815', # Variable `lineMax` in class scope should not be mixedCase
115
+ 'PLR0913', # Too many arguments in function definition (6 > 5)
116
+ 'S101', # Use of `assert` detected
117
+ 'TC002', # Move third-party import `mdformat.renderer.typing.Postprocess` into a type-checking block (for beartype)
118
+ 'TC003', # Move standard library import `argparse` into a type-checking block (for beartype)
119
+ 'TD001', # Invalid TODO tag: `FIXME`
120
+ 'TD002', # Missing author in TODO; try: `# TODO(<author_name>): ...`
121
+ 'TD003', # Missing issue link on the line following this TODO
122
+ 'TRY003', # Avoid specifying long messages outside the exception class
123
+ ]
124
+ preview = true
125
+ select = ['ALL']
126
+ unfixable = [
127
+ 'ERA001', # Commented out code
128
+ ]
129
+
130
+ [tool.ruff.lint.isort]
131
+ known-first-party = ['mdformat_obsidian', 'tests']
132
+
133
+ [tool.ruff.lint.per-file-ignores]
134
+ '__init__.py' = [
135
+ 'D104', # Missing docstring in public package
136
+ ]
137
+ 'tests/*.py' = [
138
+ 'ANN001', # Missing type annotation for function argument
139
+ 'ANN201', # Missing return type annotation for public function
140
+ 'ANN202', # Missing return type annotation for private function `test_make_diffable`
141
+ 'ARG001', # Unused function argument: `line`
142
+ 'D100', # Missing docstring in public module
143
+ 'D103', # Missing docstring in public function
144
+ 'PLC2701', # Private name import `_<>` from external module
145
+ 'PT004', # flake8-pytest-style: fixture does not return
146
+ 'S101', # Use of `assert` detected
147
+ ]
148
+
149
+ [tool.ruff.lint.pydocstyle]
150
+ convention = "google"
151
+
152
+ [tool.tomlsort]
153
+ all = true
154
+ in_place = true
155
+ trailing_comma_inline_array = true
156
+
157
+ [tool.tomlsort.overrides."tool.pytest-watcher.*"]
158
+ inline_arrays = false
159
+
160
+ [tool.tomlsort.overrides."tool.tox.env.*"]
161
+ inline_arrays = false
162
+
163
+ [tool.tox]
164
+ # Docs: https://tox.wiki/en/4.23.2/config.html#core
165
+ basepython = ["py310", "py314"]
166
+ env_list = ["cz", "hook-min", "prek", "ruff", "test", "test-min", "type"]
167
+ isolated_build = true
168
+ requires = ["tox>=4.32.0"]
169
+ skip_missing_interpreters = false
170
+
171
+ [tool.tox.env.cz]
172
+ basepython = ["py314"]
173
+ commands = [["cz", "bump", {default = [], extend = true, replace = "posargs"}]]
174
+ deps = "commitizen>=4.10.0"
175
+ description = "Bump version using commitizen. Optionally specify: '-- --increment MAJOR|MINOR|PATCH' or '-- --dry-run'"
176
+ skip_install = true
177
+
178
+ [tool.tox.env."hook-min"]
179
+ basepython = ["py310"]
180
+ commands = [["prek", "run", "--config=.pre-commit-test.yaml", "--all-files", {default = ["--show-diff-on-failure", "--verbose"], extend = true, replace = "posargs"}]]
181
+ deps = "prek>=0.2.17"
182
+
183
+ [tool.tox.env.prek]
184
+ basepython = ["py314"]
185
+ commands = [["prek", "run", "--all-files", {default = [], extend = true, replace = "posargs"}]]
186
+ deps = "prek>=0.2.17"
187
+ skip_install = true
188
+
189
+ [tool.tox.env.ruff]
190
+ basepython = ["py314"]
191
+ commands = [
192
+ ["ruff", "check", ".", "--fix", {default = [], extend = true, replace = "posargs"}],
193
+ ["ruff", "format", "."],
194
+ ]
195
+ deps = "ruff>=0.14.5"
196
+ description = "Optionally, specify: '-- --unsafe-fixes'"
197
+ skip_install = true
198
+
199
+ [tool.tox.env.test]
200
+ basepython = ["py314"]
201
+ commands = [["pytest", "--cov=mdformat_obsidian", {default = [], extend = true, replace = "posargs"}]]
202
+ # PLANNED: requires support for TYPE_CHECKING https://github.com/beartype/beartype/issues/477
203
+ # description = "Optionally, specify: '-- --exitfirst --failed-first --new-first -vv --beartype-packages=mdformat_obsidian"
204
+ description = "Optionally, specify: '-- --exitfirst --failed-first --new-first -vv"
205
+ extras = ["test"]
206
+
207
+ [tool.tox.env."test-min"]
208
+ basepython = ["py310"]
209
+ commands = [["pytest", "--cov=mdformat_obsidian"]]
210
+ extras = ["test"]
211
+
212
+ [tool.tox.env.type]
213
+ basepython = ["py314"]
214
+ commands = [["mypy", "./mdformat_obsidian", {default = [], extend = true, replace = "posargs"}]]
215
+ deps = ["mypy>=1.18.2"]
216
+
217
+ [tool.tox.env_run_base]
218
+ # Validates that commands are set
219
+ commands = [["error-commands-are-not-set"]]
220
+
221
+ [tool.uv.build-backend]
222
+ module-root = ""