mdformat-obsidian 0.0.1__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,132 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ target/
76
+
77
+ # Jupyter Notebook
78
+ .ipynb_checkpoints
79
+
80
+ # IPython
81
+ profile_default/
82
+ ipython_config.py
83
+
84
+ # pyenv
85
+ .python-version
86
+
87
+ # pipenv
88
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
90
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
91
+ # install all needed dependencies.
92
+ #Pipfile.lock
93
+
94
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95
+ __pypackages__/
96
+
97
+ # Celery stuff
98
+ celerybeat-schedule
99
+ celerybeat.pid
100
+
101
+ # SageMath parsed files
102
+ *.sage.py
103
+
104
+ # Environments
105
+ .env
106
+ .venv
107
+ env/
108
+ venv/
109
+ ENV/
110
+ env.bak/
111
+ venv.bak/
112
+
113
+ # Spyder project settings
114
+ .spyderproject
115
+ .spyproject
116
+
117
+ # Rope project settings
118
+ .ropeproject
119
+
120
+ # mkdocs documentation
121
+ /site
122
+
123
+ # mypy
124
+ .mypy_cache/
125
+ .dmypy.json
126
+ dmypy.json
127
+
128
+ # Pyre type checker
129
+ .pyre/
130
+
131
+ # VS Code
132
+ .vscode/
@@ -0,0 +1,53 @@
1
+ ---
2
+ repos:
3
+ - repo: https://github.com/pre-commit/pre-commit-hooks
4
+ rev: v4.5.0
5
+ hooks:
6
+ - id: check-added-large-files
7
+ - id: check-executables-have-shebangs
8
+ - id: check-json
9
+ - id: check-merge-conflict
10
+ - id: check-symlinks
11
+ - id: check-toml
12
+ - id: check-vcs-permalinks
13
+ - id: check-yaml
14
+ args: [--unsafe]
15
+ - id: debug-statements
16
+ - id: destroyed-symlinks
17
+ - id: detect-private-key
18
+ - id: end-of-file-fixer
19
+ - id: fix-byte-order-marker
20
+ - id: fix-encoding-pragma
21
+ args: [--remove]
22
+ - id: forbid-new-submodules
23
+ - id: mixed-line-ending
24
+ args: [--fix=auto]
25
+ - id: pretty-format-json
26
+ args: [--autofix, --indent=4]
27
+ - id: trailing-whitespace
28
+ exclude: tests/.*fixtures.*\.md
29
+ - repo: https://github.com/pre-commit/pygrep-hooks
30
+ rev: v1.10.0
31
+ hooks:
32
+ - id: python-check-blanket-noqa
33
+ - repo: https://github.com/astral-sh/ruff-pre-commit
34
+ rev: v0.3.4
35
+ hooks:
36
+ - id: ruff
37
+ args: [--fix]
38
+ - id: ruff-format
39
+ - repo: https://github.com/executablebooks/mdformat
40
+ rev: 0.7.17
41
+ hooks:
42
+ - id: mdformat
43
+ additional_dependencies:
44
+ - mdformat-mkdocs[recommended]>=2.0.6
45
+ - mdformat-gfm-alerts>=0.0.1
46
+ exclude: tests/.+\.md
47
+ args: [--wrap=no]
48
+ - repo: https://github.com/lyz-code/yamlfix/
49
+ rev: 1.16.0
50
+ hooks:
51
+ - id: yamlfix
52
+ types_or: []
53
+ types: [file, yaml]
@@ -0,0 +1,12 @@
1
+ ---
2
+ # A pre-commit hook for testing unreleased changes
3
+ # Run from tox with: tox -e py38-hook
4
+ repos:
5
+ - repo: local
6
+ hooks:
7
+ - id: mdformat
8
+ name: mdformat-from-tox
9
+ entry: mdformat
10
+ files: tests/pre-commit-test.md
11
+ types: [markdown]
12
+ language: system
@@ -0,0 +1,69 @@
1
+ # Docs: https://github.com/charliermarsh/ruff
2
+ # Tip: run python -m ruff --explain RUF100
3
+
4
+ line-length = 88
5
+ target-version = 'py38'
6
+
7
+ [lint]
8
+ ignore = [
9
+ 'ANN002', # Missing type annotation for `*args`
10
+ 'ANN003', # Missing type annotation for `**kwargs`
11
+ 'ANN101', # Missing type annotation for `self` in method
12
+ 'ANN102', # Missing type annotation for `cls` in classmethod
13
+ 'ANN401', # Dynamically typed expressions (typing.Any) are disallowed in `**kwargs`
14
+ 'BLE001', # Do not catch blind exception: `Exception`
15
+ 'CPY001', # Missing copyright notice at top of file
16
+ 'D203', # "1 blank line required before class docstring" (Conflicts with D211)
17
+ 'D213', # "Multi-line docstring summary should start at the second line" (Conflicts with D212)
18
+ 'D4', # Numpy-Style Docstrings (e.g. "Section name should end with a newline ("Returns")")
19
+ 'EM101', # Exception must not use a string literal, assign to variable first
20
+ 'FBT001', # Boolean-typed positional argument in function definition
21
+ 'FBT002', # Boolean default value in function definition
22
+ 'FIX001', # Line contains FIXME
23
+ 'FIX002', # Line contains TODO
24
+ 'FIX004', # Line contains HACK
25
+ 'N803', # Argument name `startLine` should be lowercase
26
+ 'N815', # Variable `parentType` in class scope should not be mixedCase
27
+ 'N999', # Invalid module name: '_noxfile'
28
+ 'RUF013', # PEP 484 prohibits implicit `Optional`
29
+ 'TCH001', # Move application import `{}` into a type-checking block
30
+ 'TCH002', # Move third-party import `{}` into a type-checking block
31
+ 'TCH003', # Move standard library import `pathlib.Path` into a type-checking block
32
+ 'TD001', # Invalid TODO tag: `FIXME`
33
+ 'TD002', # Missing author in TODO; try: `# TODO(<author_name>): ...`
34
+ 'TD003', # Missing issue link on the line following this TODO
35
+ 'TID252', # Relative imports from parent modules are banned
36
+ 'TRY003', # Avoid specifying long messages outside the exception class
37
+ ]
38
+ preview = true
39
+ select = ['ALL']
40
+ unfixable = [
41
+ 'ERA001', # Commented out code
42
+ ]
43
+
44
+ [lint.flake8-quotes]
45
+ inline-quotes = 'double'
46
+
47
+ [lint.isort]
48
+ known-first-party = ['mdformat_gfm_alerts']
49
+
50
+ [lint.per-file-ignores]
51
+ '__init__.py' = [
52
+ 'D104', # Missing docstring in public package
53
+ 'F401', # imported but unused; consider adding to __all__ or using a redundant alias
54
+ ]
55
+ 'tests/*.py' = [
56
+ 'ANN001', # Missing type annotation for function argument
57
+ 'ANN201', # Missing return type annotation for public function
58
+ 'ANN202', # Missing return type annotation for private function `test_make_diffable`
59
+ 'ARG001', # Unused function argument: `line`
60
+ 'D100', # Missing docstring in public module
61
+ 'D103', # Missing docstring in public function
62
+ 'EM102', # Exception must not use an f-string literal, assign to variable first
63
+ 'PT004', # flake8-pytest-style: fixture does not return
64
+ 'S101', # Use of `assert` detected
65
+ 'T201', # `print` found'
66
+ ]
67
+
68
+ [lint.pylint]
69
+ max-args = 6
@@ -0,0 +1 @@
1
+ python 3.8.12 3.12.1
@@ -0,0 +1,78 @@
1
+ # Development
2
+
3
+ This package utilizes [flit](https://flit.readthedocs.io) as the build engine, and [tox](https://tox.readthedocs.io) for test automation.
4
+
5
+ To install these development dependencies:
6
+
7
+ ```bash
8
+ pipx install tox
9
+ ```
10
+
11
+ To run the tests:
12
+
13
+ ```bash
14
+ tox
15
+ ```
16
+
17
+ and with test coverage:
18
+
19
+ ```bash
20
+ tox -e py38-cov
21
+ ```
22
+
23
+ The easiest way to write tests, is to edit `tests/fixtures.md`
24
+
25
+ To run the code formatting and style checks:
26
+
27
+ ```bash
28
+ tox -e py38-pre-commit
29
+ ```
30
+
31
+ or directly
32
+
33
+ ```bash
34
+ pip install pre-commit
35
+ pre-commit run --all
36
+ ```
37
+
38
+ To run the pre-commit hook test:
39
+
40
+ ```bash
41
+ tox -e py38-hook
42
+ ```
43
+
44
+ ## `ptw` testing
45
+
46
+ See configuration in `pyproject.toml` for `[tool.pytest-watcher]`
47
+
48
+ ```sh
49
+ pipx install pytest-watcher
50
+
51
+ ptw .
52
+ ```
53
+
54
+ ## Local pipx testing
55
+
56
+ Run the latest local code anywhere with pipx.
57
+
58
+ ```sh
59
+ pipx install . --include-deps --force --editable
60
+ ```
61
+
62
+ ## Publish to PyPi
63
+
64
+ Either use flit directly:
65
+
66
+ ```bash
67
+ pipx install flit
68
+
69
+ # envchain --set FLIT FLIT_PASSWORD
70
+ export FLIT_USERNAME=__token__
71
+ export eval $(envchain FLIT env | grep FLIT_PASSWORD=)
72
+
73
+ flit publish
74
+ ```
75
+
76
+ or trigger the GitHub Action job, by creating a release with a tag equal to the version, e.g. `v0.0.1` and updating the version in `mdformat_admon/__init__.py`.
77
+
78
+ Note, this requires generating an API key on PyPi and adding it to the repository `Settings/Secrets`, under the name `PYPI_KEY`.
@@ -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,67 @@
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) and defers the rest of the formatting to additional plugins installed automatically.
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
+ ### Pre-Commit
20
+
21
+ ```yaml
22
+ repos:
23
+ - repo: https://github.com/executablebooks/mdformat
24
+ rev: 0.7.16
25
+ hooks:
26
+ - id: mdformat
27
+ additional_dependencies:
28
+ - mdformat-obsidian
29
+ ```
30
+
31
+ ### pipx
32
+
33
+ ```sh
34
+ pipx install mdformat
35
+ pipx inject mdformat mdformat-obsidian
36
+ ```
37
+
38
+ ## HTML Rendering
39
+
40
+ 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>
41
+
42
+ ```py
43
+ from markdown_it import MarkdownIt
44
+
45
+ from mdformat_obsidian.mdit_plugins import obsidian_plugin
46
+
47
+ md = MarkdownIt()
48
+ md.use(obsidian_plugin)
49
+
50
+ text = "> [!tip] Callouts can have custom titles\n> Like this one."
51
+ md.render(text)
52
+ # <blockquote>
53
+
54
+ # </blockquote>
55
+ ```
56
+
57
+ > [!WARNING]
58
+ > 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.
59
+
60
+ ## Contributing
61
+
62
+ See [CONTRIBUTING.md](https://github.com/KyleKing/mdformat-obsidian/blob/main/CONTRIBUTING.md)
63
+
64
+ [ci-badge]: https://github.com/kyleking/mdformat-obsidian/workflows/CI/badge.svg?branch=main
65
+ [ci-link]: https://github.com/kyleking/mdformat-obsidian/actions?query=workflow%3ACI+branch%3Amain+event%3Apush
66
+ [pypi-badge]: https://img.shields.io/pypi/v/mdformat-obsidian.svg
67
+ [pypi-link]: https://pypi.org/project/mdformat-obsidian
@@ -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,53 @@
1
+ [build-system]
2
+ requires = ["flit_core >=3.2.0,<4"]
3
+ build-backend = "flit_core.buildapi"
4
+
5
+ [project]
6
+ name = "mdformat_obsidian"
7
+ authors = [
8
+ { name = "Kyle King", email = "dev.act.kyle@gmail.com" },
9
+ ]
10
+ readme = "README.md"
11
+ classifiers = [
12
+ "Intended Audience :: Developers",
13
+ "License :: OSI Approved :: MIT License",
14
+ "Programming Language :: Python :: 3",
15
+ "Topic :: Software Development :: Libraries :: Python Modules",
16
+ ]
17
+ keywords = ["mdformat", "markdown", "markdown-it"]
18
+ requires-python = ">=3.8.0"
19
+ dependencies = [
20
+ "mdformat >= 0.7.16",
21
+ "mdformat-footnote >= 0.1.1",
22
+ "mdformat-frontmatter >= 2.0.8",
23
+ "mdformat-gfm >= 0.3.6",
24
+ "mdformat-simple-breaks >= 0.0.1",
25
+ "mdformat-tables >= 0.4.1",
26
+ "mdformat-wikilink >= 0.2.0",
27
+ "mdit-py-plugins >= 0.4.0",
28
+ ]
29
+ dynamic = ["version", "description"]
30
+
31
+ [project.optional-dependencies]
32
+ test = [
33
+ "pytest >= 7.4.4",
34
+ "pytest-cov >= 4.1.0",
35
+ ]
36
+ dev = ["pre-commit"]
37
+
38
+ [project.urls]
39
+ Homepage = "https://github.com/KyleKing/mdformat-obsidian"
40
+
41
+ [project.entry-points."mdformat.parser_extension"]
42
+ obsidian = "mdformat_obsidian"
43
+
44
+ [tool.flit.sdist]
45
+ include = []
46
+ exclude = [".github/", "tests/"]
47
+
48
+ [tool.pytest-watcher]
49
+ now = true
50
+ runner = "tox"
51
+ runner_args = ["-e", "py38"]
52
+ patterns = ["*.py", "*.md"]
53
+ ignore_patterns = []
@@ -0,0 +1,34 @@
1
+ [tox]
2
+ envlist =
3
+ py{38}
4
+ py{312}-cov
5
+ py{312}-pre-commit
6
+ py{38}-hook
7
+ mypy
8
+ ruff
9
+ isolated_build = True
10
+ skip_missing_interpreters = False
11
+
12
+ [testenv:py{38}]
13
+ extras = test
14
+ commands = pytest {posargs} --ff --nf -vv
15
+
16
+ [testenv:py{312}-cov]
17
+ extras = test
18
+ commands = pytest --cov=mdformat_obsidian {posargs}
19
+
20
+ [testenv:py{312}-pre-commit]
21
+ extras = dev
22
+ commands = pre-commit run {posargs:--all-files}
23
+
24
+ [testenv:py{38}-hook]
25
+ extras = dev
26
+ commands = pre-commit run --config .pre-commit-test.yaml {posargs:--all-files --verbose --show-diff-on-failure}
27
+
28
+ [testenv:mypy]
29
+ deps = mypy
30
+ commands = mypy ./mdformat_obsidian
31
+
32
+ [testenv:ruff]
33
+ deps = ruff
34
+ commands = ruff format .