Skip to content

Commit 6f1a77e

Browse files
authored
🔧 MAINTAIN: Make type checking strict (#86)
1 parent c297f7e commit 6f1a77e

File tree

20 files changed

+429
-227
lines changed

20 files changed

+429
-227
lines changed

‎.pre-commit-config.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,4 @@ repos:
3939
hooks:
4040
- id: mypy
4141
additional_dependencies: [markdown-it-py~=3.0]
42+
exclude: ^tests/

‎mdit_py_plugins/admon/index.py

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,20 @@
11
# Process admonitions and pass to cb.
2+
from __future__ import annotations
23

3-
from typing import Callable, List, Optional, Tuple
4+
from typing import TYPE_CHECKING, Callable, Sequence
45

56
from markdown_it import MarkdownIt
67
from markdown_it.rules_block import StateBlock
78

89
from mdit_py_plugins.utils import is_code_block
910

11+
if TYPE_CHECKING:
12+
from markdown_it.renderer import RendererProtocol
13+
from markdown_it.token import Token
14+
from markdown_it.utils import EnvType, OptionsDict
1015

11-
def _get_tag(params: str) -> Tuple[str, str]:
16+
17+
def _get_tag(params: str) -> tuple[str, str]:
1218
"""Separate the tag name from the admonition title."""
1319
if not params.strip():
1420
return "", ""
@@ -36,7 +42,7 @@ def _validate(params: str) -> bool:
3642
MAX_MARKER_LEN = max(len(_m) for _m in MARKERS)
3743

3844

39-
def _extra_classes(markup: str) -> List[str]:
45+
def _extra_classes(markup: str) -> list[str]:
4046
"""Return the list of additional classes based on the markup."""
4147
if markup.startswith("?"):
4248
if markup.endswith("+"):
@@ -158,7 +164,7 @@ def admonition(state: StateBlock, startLine: int, endLine: int, silent: bool) ->
158164
return True
159165

160166

161-
def admon_plugin(md: MarkdownIt, render: Optional[Callable] = None) -> None:
167+
def admon_plugin(md: MarkdownIt, render: None | Callable[..., str] = None) -> None:
162168
"""Plugin to use
163169
`python-markdown style admonitions
164170
<https://python-markdown.github.io/extensions/admonition>`_.
@@ -181,8 +187,14 @@ def admon_plugin(md: MarkdownIt, render: Optional[Callable] = None) -> None:
181187
<https://github.com/commenthol/markdown-it-admon>`_.
182188
"""
183189

184-
def renderDefault(self, tokens, idx, _options, env):
185-
return self.renderToken(tokens, idx, _options, env)
190+
def renderDefault(
191+
self: RendererProtocol,
192+
tokens: Sequence[Token],
193+
idx: int,
194+
_options: OptionsDict,
195+
env: EnvType,
196+
) -> str:
197+
return self.renderToken(tokens, idx, _options, env) # type: ignore
186198

187199
render = render or renderDefault
188200

‎mdit_py_plugins/amsmath/__init__.py

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
11
"""An extension to capture amsmath latex environments."""
2+
from __future__ import annotations
3+
24
import re
3-
from typing import Callable, Optional
5+
from typing import TYPE_CHECKING, Callable, Optional, Sequence
46

57
from markdown_it import MarkdownIt
68
from markdown_it.common.utils import escapeHtml
79
from markdown_it.rules_block import StateBlock
810

911
from mdit_py_plugins.utils import is_code_block
1012

13+
if TYPE_CHECKING:
14+
from markdown_it.renderer import RendererProtocol
15+
from markdown_it.token import Token
16+
from markdown_it.utils import EnvType, OptionsDict
17+
1118
# Taken from amsmath version 2.1
1219
# http://anorien.csc.warwick.ac.uk/mirrors/CTAN/macros/latex/required/amsmath/amsldoc.pdf
1320
ENVIRONMENTS = [
@@ -49,7 +56,9 @@
4956
RE_OPEN = re.compile(r"\\begin\{(" + "|".join(ENVIRONMENTS) + r")([\*]?)\}")
5057

5158

52-
def amsmath_plugin(md: MarkdownIt, *, renderer: Optional[Callable[[str], str]] = None):
59+
def amsmath_plugin(
60+
md: MarkdownIt, *, renderer: Optional[Callable[[str], str]] = None
61+
) -> None:
5362
"""Parses TeX math equations, without any surrounding delimiters,
5463
only for top-level `amsmath <https://ctan.org/pkg/amsmath>`__ environments:
5564
@@ -72,14 +81,20 @@ def amsmath_plugin(md: MarkdownIt, *, renderer: Optional[Callable[[str], str]] =
7281

7382
_renderer = (lambda content: escapeHtml(content)) if renderer is None else renderer
7483

75-
def render_amsmath_block(self, tokens, idx, options, env):
84+
def render_amsmath_block(
85+
self: RendererProtocol,
86+
tokens: Sequence[Token],
87+
idx: int,
88+
options: OptionsDict,
89+
env: EnvType,
90+
) -> str:
7691
content = _renderer(str(tokens[idx].content))
7792
return f'<div class="math amsmath">\n{content}\n</div>\n'
7893

7994
md.add_render_rule("amsmath", render_amsmath_block)
8095

8196

82-
def match_environment(string):
97+
def match_environment(string: str) -> None | tuple[str, str, int]:
8398
match_open = RE_OPEN.match(string)
8499
if not match_open:
85100
return None
@@ -93,7 +108,9 @@ def match_environment(string):
93108
return (environment, numbered, match_close.end())
94109

95110

96-
def amsmath_block(state: StateBlock, startLine: int, endLine: int, silent: bool):
111+
def amsmath_block(
112+
state: StateBlock, startLine: int, endLine: int, silent: bool
113+
) -> bool:
97114
if is_code_block(state, startLine):
98115
return False
99116

‎mdit_py_plugins/anchors/index.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def anchors_plugin(
1515
permalinkSymbol: str = "¶",
1616
permalinkBefore: bool = False,
1717
permalinkSpace: bool = True,
18-
):
18+
) -> None:
1919
"""Plugin for adding header anchors, based on
2020
`markdown-it-anchor <https://github.com/valeriangalliat/markdown-it-anchor>`__
2121
@@ -64,8 +64,8 @@ def _make_anchors_func(
6464
permalinkSymbol: str,
6565
permalinkBefore: bool,
6666
permalinkSpace: bool,
67-
):
68-
def _anchor_func(state: StateCore):
67+
) -> Callable[[StateCore], None]:
68+
def _anchor_func(state: StateCore) -> None:
6969
slugs: Set[str] = set()
7070
for idx, token in enumerate(state.tokens):
7171
if token.type != "heading_open":
@@ -115,11 +115,11 @@ def _anchor_func(state: StateCore):
115115
return _anchor_func
116116

117117

118-
def slugify(title: str):
118+
def slugify(title: str) -> str:
119119
return re.sub(r"[^\w\u4e00-\u9fff\- ]", "", title.strip().lower().replace(" ", "-"))
120120

121121

122-
def unique_slug(slug: str, slugs: set):
122+
def unique_slug(slug: str, slugs: Set[str]) -> str:
123123
uniq = slug
124124
i = 1
125125
while uniq in slugs:

‎mdit_py_plugins/attrs/index.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import List, Optional
1+
from typing import List, Optional, Sequence
22

33
from markdown_it import MarkdownIt
44
from markdown_it.rules_block import StateBlock
@@ -14,10 +14,10 @@
1414
def attrs_plugin(
1515
md: MarkdownIt,
1616
*,
17-
after=("image", "code_inline", "link_close", "span_close"),
18-
spans=False,
19-
span_after="link",
20-
):
17+
after: Sequence[str] = ("image", "code_inline", "link_close", "span_close"),
18+
spans: bool = False,
19+
span_after: str = "link",
20+
) -> None:
2121
"""Parse inline attributes that immediately follow certain inline elements::
2222
2323
![alt](https://image.com){#id .a b=c}
@@ -50,7 +50,7 @@ def attrs_plugin(
5050
:param span_after: The name of an inline rule after which spans may be specified.
5151
"""
5252

53-
def _attr_inline_rule(state: StateInline, silent: bool):
53+
def _attr_inline_rule(state: StateInline, silent: bool) -> bool:
5454
if state.pending or not state.tokens:
5555
return False
5656
token = state.tokens[-1]
@@ -77,7 +77,7 @@ def _attr_inline_rule(state: StateInline, silent: bool):
7777
md.inline.ruler.push("attr", _attr_inline_rule)
7878

7979

80-
def attrs_block_plugin(md: MarkdownIt):
80+
def attrs_block_plugin(md: MarkdownIt) -> None:
8181
"""Parse block attributes.
8282
8383
Block attributes are attributes on a single line, with no other content.
@@ -111,7 +111,7 @@ def _find_opening(tokens: List[Token], index: int) -> Optional[int]:
111111
return None
112112

113113

114-
def _span_rule(state: StateInline, silent: bool):
114+
def _span_rule(state: StateInline, silent: bool) -> bool:
115115
if state.src[state.pos] != "[":
116116
return False
117117

@@ -197,7 +197,7 @@ def _attr_block_rule(
197197
return True
198198

199199

200-
def _attr_resolve_block_rule(state: StateCore):
200+
def _attr_resolve_block_rule(state: StateCore) -> None:
201201
"""Find attribute block then move its attributes to the next block."""
202202
i = 0
203203
len_tokens = len(state.tokens)

‎mdit_py_plugins/attrs/parse.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,14 @@ class State(Enum):
4646

4747

4848
class TokenState:
49-
def __init__(self):
50-
self._tokens = []
49+
def __init__(self) -> None:
50+
self._tokens: list[tuple[int, int, str]] = []
5151
self.start: int = 0
5252

5353
def set_start(self, start: int) -> None:
5454
self.start = start
5555

56-
def append(self, start: int, end: int, ttype: str):
56+
def append(self, start: int, end: int, ttype: str) -> None:
5757
self._tokens.append((start, end, ttype))
5858

5959
def compile(self, string: str) -> dict[str, str]:

‎mdit_py_plugins/colon_fence.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,20 @@
1+
from __future__ import annotations
2+
3+
from typing import TYPE_CHECKING, Sequence
4+
15
from markdown_it import MarkdownIt
26
from markdown_it.common.utils import escapeHtml, unescapeAll
37
from markdown_it.rules_block import StateBlock
48

59
from mdit_py_plugins.utils import is_code_block
610

11+
if TYPE_CHECKING:
12+
from markdown_it.renderer import RendererProtocol
13+
from markdown_it.token import Token
14+
from markdown_it.utils import EnvType, OptionsDict
15+
716

8-
def colon_fence_plugin(md: MarkdownIt):
17+
def colon_fence_plugin(md: MarkdownIt) -> None:
918
"""This plugin directly mimics regular fences, but with `:` colons.
1019
1120
Example::
@@ -25,7 +34,7 @@ def colon_fence_plugin(md: MarkdownIt):
2534
md.add_render_rule("colon_fence", _render)
2635

2736

28-
def _rule(state: StateBlock, startLine: int, endLine: int, silent: bool):
37+
def _rule(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
2938
if is_code_block(state, startLine):
3039
return False
3140

@@ -126,7 +135,13 @@ def _skipCharsStr(state: StateBlock, pos: int, ch: str) -> int:
126135
return pos
127136

128137

129-
def _render(self, tokens, idx, options, env):
138+
def _render(
139+
self: RendererProtocol,
140+
tokens: Sequence[Token],
141+
idx: int,
142+
options: OptionsDict,
143+
env: EnvType,
144+
) -> str:
130145
token = tokens[idx]
131146
info = unescapeAll(token.info).strip() if token.info else ""
132147
content = escapeHtml(token.content)

‎mdit_py_plugins/container/index.py

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,27 @@
11
"""Process block-level custom containers."""
2+
from __future__ import annotations
3+
24
from math import floor
3-
from typing import Callable, Optional
5+
from typing import TYPE_CHECKING, Any, Callable, Sequence
46

57
from markdown_it import MarkdownIt
68
from markdown_it.rules_block import StateBlock
79

810
from mdit_py_plugins.utils import is_code_block
911

12+
if TYPE_CHECKING:
13+
from markdown_it.renderer import RendererProtocol
14+
from markdown_it.token import Token
15+
from markdown_it.utils import EnvType, OptionsDict
16+
1017

1118
def container_plugin(
1219
md: MarkdownIt,
1320
name: str,
1421
marker: str = ":",
15-
validate: Optional[Callable[[str, str], bool]] = None,
16-
render=None,
17-
):
22+
validate: None | Callable[[str, str], bool] = None,
23+
render: None | Callable[..., str] = None,
24+
) -> None:
1825
"""Plugin ported from
1926
`markdown-it-container <https://github.com/markdown-it/markdown-it-container>`__.
2027
@@ -35,15 +42,21 @@ def container_plugin(
3542
3643
"""
3744

38-
def validateDefault(params: str, *args):
45+
def validateDefault(params: str, *args: Any) -> bool:
3946
return params.strip().split(" ", 2)[0] == name
4047

41-
def renderDefault(self, tokens, idx, _options, env):
48+
def renderDefault(
49+
self: RendererProtocol,
50+
tokens: Sequence[Token],
51+
idx: int,
52+
_options: OptionsDict,
53+
env: EnvType,
54+
) -> str:
4255
# add a class to the opening tag
4356
if tokens[idx].nesting == 1:
4457
tokens[idx].attrJoin("class", name)
4558

46-
return self.renderToken(tokens, idx, _options, env)
59+
return self.renderToken(tokens, idx, _options, env) # type: ignore
4760

4861
min_markers = 3
4962
marker_str = marker
@@ -52,7 +65,9 @@ def renderDefault(self, tokens, idx, _options, env):
5265
validate = validate or validateDefault
5366
render = render or renderDefault
5467

55-
def container_func(state: StateBlock, startLine: int, endLine: int, silent: bool):
68+
def container_func(
69+
state: StateBlock, startLine: int, endLine: int, silent: bool
70+
) -> bool:
5671
if is_code_block(state, startLine):
5772
return False
5873

‎mdit_py_plugins/deflist/index.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from mdit_py_plugins.utils import is_code_block
66

77

8-
def deflist_plugin(md: MarkdownIt):
8+
def deflist_plugin(md: MarkdownIt) -> None:
99
"""Plugin ported from
1010
`markdown-it-deflist <https://github.com/markdown-it/markdown-it-deflist>`__.
1111
@@ -25,7 +25,7 @@ def deflist_plugin(md: MarkdownIt):
2525
2626
"""
2727

28-
def skipMarker(state: StateBlock, line: int):
28+
def skipMarker(state: StateBlock, line: int) -> int:
2929
"""Search `[:~][\n ]`, returns next pos after marker on success or -1 on fail."""
3030
start = state.bMarks[line] + state.tShift[line]
3131
maximum = state.eMarks[line]
@@ -51,7 +51,7 @@ def skipMarker(state: StateBlock, line: int):
5151

5252
return start
5353

54-
def markTightParagraphs(state: StateBlock, idx: int):
54+
def markTightParagraphs(state: StateBlock, idx: int) -> None:
5555
level = state.level + 2
5656

5757
i = idx + 2
@@ -66,7 +66,7 @@ def markTightParagraphs(state: StateBlock, idx: int):
6666
i += 2
6767
i += 1
6868

69-
def deflist(state: StateBlock, startLine: int, endLine: int, silent: bool):
69+
def deflist(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
7070
if is_code_block(state, startLine):
7171
return False
7272

0 commit comments

Comments
 (0)