mdformat-obsidian 0.0.1__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,5 @@
1
+ """An mdformat plugin for `obsidian`."""
2
+
3
+ __version__ = "0.0.1"
4
+
5
+ from .plugin import RENDERERS, update_mdit
@@ -0,0 +1,6 @@
1
+ from ._obsidian_blockquote_factories import (
2
+ CalloutData,
3
+ new_token,
4
+ obsidian_callout_plugin_factory,
5
+ parse_possible_blockquote_admon_factory,
6
+ )
@@ -0,0 +1,111 @@
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 Generator
12
+ from contextlib import contextmanager
13
+ from typing import TYPE_CHECKING, Callable, NamedTuple
14
+
15
+ from markdown_it import MarkdownIt
16
+ from markdown_it.rules_block import StateBlock
17
+ from mdit_py_plugins.utils import is_code_block
18
+
19
+ if TYPE_CHECKING:
20
+ from markdown_it.token import Token
21
+
22
+
23
+ # FYI: copied from mdformat_admon.factories
24
+ @contextmanager
25
+ def new_token(state: StateBlock, name: str, kind: str) -> Generator[Token, None, None]:
26
+ """Creates scoped token."""
27
+ yield state.push(f"{name}_open", kind, 1)
28
+ state.push(f"{name}_close", kind, -1)
29
+
30
+
31
+ # FYI: Adapted from mdformat_admon.factories
32
+ class CalloutState(NamedTuple):
33
+ """Frozen state."""
34
+
35
+ parentType: str
36
+ lineMax: int
37
+
38
+
39
+ class CalloutData(NamedTuple):
40
+ """CalloutData data for rendering."""
41
+
42
+ old_state: CalloutState
43
+ meta_text: str
44
+ folded: bool
45
+ custom_title: str
46
+ next_line: int
47
+
48
+
49
+ def parse_possible_blockquote_admon_factory(
50
+ prefix: str,
51
+ patterns: set[str],
52
+ ) -> Callable[[StateBlock, int, int, bool], CalloutData | bool]:
53
+ """Generate the parser function.
54
+
55
+ Accepts set of strings that will be compiled into regular expressions.
56
+ They must have a capture group `title` and optional group `folded`.
57
+
58
+ """
59
+
60
+ def parse_possible_blockquote_admon(
61
+ state: StateBlock,
62
+ start_line: int,
63
+ end_line: int,
64
+ silent: bool,
65
+ ) -> CalloutData | bool:
66
+ if is_code_block(state, start_line):
67
+ return False
68
+
69
+ start = state.bMarks[start_line] + state.tShift[start_line]
70
+
71
+ # Exit if no match for any pattern
72
+ text = state.src[start:]
73
+ regexes = [
74
+ re.compile(rf"{pat}(?P<custom_title>(?: |<br>)[^\n]+)?", re.IGNORECASE)
75
+ for pat in patterns
76
+ ]
77
+ match = next((_m for rx in regexes if (_m := rx.match(text))), None)
78
+ if not match:
79
+ return False
80
+
81
+ # Since start is found, we can report success here in validation mode
82
+ if silent:
83
+ return True
84
+
85
+ old_state = CalloutState(
86
+ parentType=state.parentType,
87
+ lineMax=state.lineMax,
88
+ )
89
+ state.parentType = prefix
90
+
91
+ return CalloutData(
92
+ old_state=old_state,
93
+ meta_text=match["title"],
94
+ folded=bool(match["folded"]),
95
+ custom_title=match["custom_title"] or "",
96
+ next_line=end_line,
97
+ )
98
+
99
+ return parse_possible_blockquote_admon
100
+
101
+
102
+ def obsidian_callout_plugin_factory(
103
+ prefix: str,
104
+ logic: Callable[[StateBlock, int, int, bool], bool],
105
+ ) -> Callable[[MarkdownIt], None]:
106
+ """Generate the plugin function."""
107
+
108
+ def obsidian_callout_plugin(md: MarkdownIt) -> None:
109
+ md.block.ruler.before("blockquote", prefix, logic)
110
+
111
+ return obsidian_callout_plugin
@@ -0,0 +1,6 @@
1
+ from ._obsidian_callouts import (
2
+ INLINE_SEP,
3
+ OBSIDIAN_CALLOUT_PREFIX,
4
+ format_obsidian_callout_markup,
5
+ obsidian_callout_plugin,
6
+ )
@@ -0,0 +1,105 @@
1
+ """Obsidian Callouts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from markdown_it.rules_block import StateBlock
6
+
7
+ from ..factories import (
8
+ CalloutData,
9
+ new_token,
10
+ obsidian_callout_plugin_factory,
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 ineline content (if present)."""
19
+
20
+ PATTERNS = {
21
+ # Note '> ' prefix is removed when parsing
22
+ r"^\*\*(?P<title>Note|Warning)\*\*",
23
+ # FYI: Unlike GitHub Alerts, Obsidian doesn't constrain the possible types
24
+ r"^\\?\[!(?P<title>[^\]]+)\\?\](?P<folded>-?)",
25
+ }
26
+ """Patterns specific to GitHub Alerts."""
27
+
28
+
29
+ def format_obsidian_callout_markup(
30
+ state: StateBlock,
31
+ start_line: int,
32
+ admonition: CalloutData,
33
+ ) -> None:
34
+ """Format markup."""
35
+ tag = admonition.meta_text.upper()
36
+ fold = "-" if admonition.folded else ""
37
+ custom_title = admonition.custom_title
38
+ title_line = f"[!{tag}]{fold}{INLINE_SEP}{custom_title}"
39
+
40
+ with new_token(state, OBSIDIAN_CALLOUT_PREFIX, "div") as token:
41
+ token.attrs = {
42
+ "data-callout-metadata": "",
43
+ "data-callout-fold": "",
44
+ "data-callout": admonition.meta_text.lower(),
45
+ "class": "callout",
46
+ }
47
+ if admonition.folded:
48
+ token.attrs["data-callout-fold"] = "-"
49
+ token.attrs["class"] = "callout is-collapsible is-collapsed"
50
+ token.block = True
51
+ token.map = [start_line, admonition.next_line]
52
+ token.markup = title_line
53
+ with new_token(state, f"{OBSIDIAN_CALLOUT_PREFIX}_title", "div") as tkn_title:
54
+ tkn_title.attrs = {"class": "callout-title"}
55
+
56
+ title_inner = f"{OBSIDIAN_CALLOUT_PREFIX}_title_inner"
57
+ with new_token(state, title_inner, "div") as tkn_title_inner:
58
+ tkn_title_inner.attrs = {"class": "callout-title-inner"}
59
+
60
+ tkn_title_txt = state.push("inline", "", 0)
61
+ tkn_title_txt.content = admonition.custom_title.strip()
62
+ if admonition.folded:
63
+ collapsed = f"{OBSIDIAN_CALLOUT_PREFIX}_collapsed"
64
+ with new_token(state, collapsed, "div") as tkn_collapsed:
65
+ tkn_collapsed.attrs = {"class": "callout-fold is-collapsed"}
66
+
67
+ content = f"{OBSIDIAN_CALLOUT_PREFIX}_content"
68
+ with new_token(state, content, "div") as tkn_content:
69
+ tkn_content.attrs = {"class": "callout-content"}
70
+ if admonition.folded:
71
+ tkn_content.attrs["style"] = "display: none;"
72
+
73
+ state.md.block.tokenize(state, start_line + 1, admonition.next_line)
74
+
75
+ # FIXME: this isn't actually replacing the block quote outer div?
76
+ #
77
+ # Render as a div for accessibility rather than block quote
78
+ # Which is because '>' is being misused (https://github.com/orgs/community/discussions/16925#discussioncomment-8729846)
79
+ state.parentType = "div" # admonition.old_state.parentType
80
+ state.lineMax = admonition.old_state.lineMax
81
+ state.line = admonition.next_line
82
+
83
+
84
+ def alert_logic(
85
+ state: StateBlock,
86
+ startLine: int,
87
+ endLine: int,
88
+ silent: bool,
89
+ ) -> bool:
90
+ """Parse GitHub Alerts."""
91
+ parser_func = parse_possible_blockquote_admon_factory(
92
+ OBSIDIAN_CALLOUT_PREFIX,
93
+ PATTERNS,
94
+ )
95
+ result = parser_func(state, startLine, endLine, silent)
96
+ if isinstance(result, CalloutData):
97
+ format_obsidian_callout_markup(state, startLine, admonition=result)
98
+ return True
99
+ return result
100
+
101
+
102
+ obsidian_callout_plugin = obsidian_callout_plugin_factory(
103
+ OBSIDIAN_CALLOUT_PREFIX,
104
+ alert_logic,
105
+ )
@@ -0,0 +1,54 @@
1
+ """Public Extension."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Mapping
6
+
7
+ from markdown_it import MarkdownIt
8
+ from mdformat.renderer import RenderContext, RenderTreeNode
9
+ from mdformat.renderer.typing import Render
10
+
11
+ from .mdit_plugins import INLINE_SEP, OBSIDIAN_CALLOUT_PREFIX, obsidian_callout_plugin
12
+
13
+
14
+ def update_mdit(mdit: MarkdownIt) -> None:
15
+ """Update the parser to identify Alerts."""
16
+ mdit.use(obsidian_callout_plugin)
17
+
18
+
19
+ def _render_obsidian_callout(node: RenderTreeNode, context: RenderContext) -> str:
20
+ """Render a `RenderTreeNode`."""
21
+ title_line = node.markup.replace(INLINE_SEP, "")
22
+ elements = [render for child in node.children if (render := child.render(context))]
23
+ # Do not separate the title line from the first row
24
+ return "\n".join([title_line, "\n\n".join(elements)]).rstrip()
25
+
26
+
27
+ def _no_render(
28
+ node: RenderTreeNode, # noqa: ARG001
29
+ context: RenderContext, # noqa: ARG001
30
+ ) -> str:
31
+ """Skip rendering when handled separately."""
32
+ return ""
33
+
34
+
35
+ def _recursive_render(
36
+ node: RenderTreeNode,
37
+ context: RenderContext,
38
+ ) -> str:
39
+ elements = [render for child in node.children if (render := child.render(context))]
40
+ # Do not separate the title line from the first row
41
+ return "\n\n".join(elements).rstrip()
42
+
43
+
44
+ # A mapping from syntax tree node type to a function that renders it.
45
+ # This can be used to overwrite renderer functions of existing syntax
46
+ # or add support for new syntax.
47
+ RENDERERS: Mapping[str, Render] = {
48
+ OBSIDIAN_CALLOUT_PREFIX: _render_obsidian_callout,
49
+ f"{OBSIDIAN_CALLOUT_PREFIX}_title": _no_render,
50
+ f"{OBSIDIAN_CALLOUT_PREFIX}_title_inner": _no_render,
51
+ f"{OBSIDIAN_CALLOUT_PREFIX}_collapsed": _no_render,
52
+ # FIXME: can I add divs without introducing new blocks?
53
+ f"{OBSIDIAN_CALLOUT_PREFIX}_content": _recursive_render,
54
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Executable Books
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,95 @@
1
+ Metadata-Version: 2.1
2
+ Name: mdformat_obsidian
3
+ Version: 0.0.1
4
+ Summary: An mdformat plugin for `obsidian`.
5
+ Keywords: mdformat,markdown,markdown-it
6
+ Author-email: Kyle King <dev.act.kyle@gmail.com>
7
+ Requires-Python: >=3.8.0
8
+ Description-Content-Type: text/markdown
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.16
14
+ Requires-Dist: mdformat-footnote >= 0.1.1
15
+ Requires-Dist: mdformat-frontmatter >= 2.0.8
16
+ Requires-Dist: mdformat-gfm >= 0.3.6
17
+ Requires-Dist: mdformat-simple-breaks >= 0.0.1
18
+ Requires-Dist: mdformat-tables >= 0.4.1
19
+ Requires-Dist: mdformat-wikilink >= 0.2.0
20
+ Requires-Dist: mdit-py-plugins >= 0.4.0
21
+ Requires-Dist: pre-commit ; extra == "dev"
22
+ Requires-Dist: pytest >= 7.4.4 ; extra == "test"
23
+ Requires-Dist: pytest-cov >= 4.1.0 ; extra == "test"
24
+ Project-URL: Homepage, https://github.com/KyleKing/mdformat-obsidian
25
+ Provides-Extra: dev
26
+ Provides-Extra: test
27
+
28
+ # mdformat-obsidian
29
+
30
+ [![Build Status][ci-badge]][ci-link] [![PyPI version][pypi-badge]][pypi-link]
31
+
32
+ <!-- [![codecov.io][cov-badge]][cov-link]
33
+ [cov-badge]: https://codecov.io/gh/executablebooks/mdformat-obsidian/branch/main/graph/badge.svg
34
+ [cov-link]: https://codecov.io/gh/executablebooks/mdformat-obsidian
35
+ -->
36
+
37
+ 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) and defers the rest of the formatting to additional plugins installed automatically.
38
+
39
+ > [!NOTE]
40
+ > 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 `[!...]`.
41
+
42
+ ## `mdformat` Usage
43
+
44
+ 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)
45
+
46
+ ### Pre-Commit
47
+
48
+ ```yaml
49
+ repos:
50
+ - repo: https://github.com/executablebooks/mdformat
51
+ rev: 0.7.16
52
+ hooks:
53
+ - id: mdformat
54
+ additional_dependencies:
55
+ - mdformat-obsidian
56
+ ```
57
+
58
+ ### pipx
59
+
60
+ ```sh
61
+ pipx install mdformat
62
+ pipx inject mdformat mdformat-obsidian
63
+ ```
64
+
65
+ ## HTML Rendering
66
+
67
+ 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>
68
+
69
+ ```py
70
+ from markdown_it import MarkdownIt
71
+
72
+ from mdformat_obsidian.mdit_plugins import obsidian_plugin
73
+
74
+ md = MarkdownIt()
75
+ md.use(obsidian_plugin)
76
+
77
+ text = "> [!tip] Callouts can have custom titles\n> Like this one."
78
+ md.render(text)
79
+ # <blockquote>
80
+
81
+ # </blockquote>
82
+ ```
83
+
84
+ > [!WARNING]
85
+ > This package does not properly handle replacing the `blockquote` outer `div` with a `div` for accessibility. This should be possible with `markdown-it`, but I haven't yet found a way.
86
+
87
+ ## Contributing
88
+
89
+ See [CONTRIBUTING.md](https://github.com/KyleKing/mdformat-obsidian/blob/main/CONTRIBUTING.md)
90
+
91
+ [ci-badge]: https://github.com/kyleking/mdformat-obsidian/workflows/CI/badge.svg?branch=main
92
+ [ci-link]: https://github.com/kyleking/mdformat-obsidian/actions?query=workflow%3ACI+branch%3Amain+event%3Apush
93
+ [pypi-badge]: https://img.shields.io/pypi/v/mdformat-obsidian.svg
94
+ [pypi-link]: https://pypi.org/project/mdformat-obsidian
95
+
@@ -0,0 +1,11 @@
1
+ mdformat_obsidian/__init__.py,sha256=D_sukTBJtf49kA9ttezKQLjF8_vjlz8hjPh42DNVgbI,108
2
+ mdformat_obsidian/plugin.py,sha256=iOt6egNfW3IalA7Hn6PCtHJja5ln8nZ3MJNfUJD2DkE,1841
3
+ mdformat_obsidian/factories/__init__.py,sha256=1GyjI38pKSgAB4jj1okTPJyHep43Knzbh7RD4V6g5B4,162
4
+ mdformat_obsidian/factories/_obsidian_blockquote_factories.py,sha256=GJ2hcvDTf55Pl_ozXoI8VbbcQrMqLUeUT0NnEtBXuaQ,3101
5
+ mdformat_obsidian/mdit_plugins/__init__.py,sha256=UJDxcsNSNN9WKpRaUA5tr2z7hLrdYD-LfRDLw_JVdF0,146
6
+ mdformat_obsidian/mdit_plugins/_obsidian_callouts.py,sha256=e1RRYl67GMkANx-L85-0lCcpMksAYoRkmXBbEw_Y9fA,3713
7
+ mdformat_obsidian-0.0.1.dist-info/entry_points.txt,sha256=2VoUa5M29l69ugrY2KoAPpewFqAs35LeSK-p5a28VKw,56
8
+ mdformat_obsidian-0.0.1.dist-info/LICENSE,sha256=-voxTd2luDRUXIFkSXQRQGL3cHzC9AnnJkv3LJrla3o,1073
9
+ mdformat_obsidian-0.0.1.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81
10
+ mdformat_obsidian-0.0.1.dist-info/METADATA,sha256=Aj8dJmJYv3CsJf4_gIj1y1YssfimrI85v1K7W0hxDUY,3744
11
+ mdformat_obsidian-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.9.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [mdformat.parser_extension]
2
+ obsidian=mdformat_obsidian
3
+