Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/markdown_it/ruler.py: 74%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2class Ruler
4Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and
5[[MarkdownIt#inline]] to manage sequences of functions (rules):
7- keep rules in defined order
8- assign the name to each rule
9- enable/disable rules
10- add/replace rules
11- allow assign rules to additional named chains (in the same)
12- caching lists of active rules
14You will not need use this class directly until write plugins. For simple
15rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and
16[[MarkdownIt.use]].
17"""
19from __future__ import annotations
21from collections.abc import Iterable
22from dataclasses import dataclass, field
23from typing import TYPE_CHECKING, Generic, TypedDict, TypeVar
24import warnings
26from .utils import EnvType
28if TYPE_CHECKING:
29 from markdown_it import MarkdownIt
32class StateBase:
33 # `src` is a plain attribute, not a property: rules read it on almost
34 # every step, and a property call there costs ~5% of total parse time.
35 src: str
37 # Cache for the deprecated `srcCharCode`, as `(src, char_codes)`.
38 # This is a class-level default, since subclasses do not call `__init__`.
39 _src_char_code: tuple[str, tuple[int, ...]] | None = None
41 def __init__(self, src: str, md: MarkdownIt, env: EnvType):
42 self.src = src
43 self.env = env
44 self.md = md
46 @property
47 def srcCharCode(self) -> tuple[int, ...]:
48 warnings.warn(
49 "StateBase.srcCharCode is deprecated. Use StateBase.src instead.",
50 DeprecationWarning,
51 stacklevel=2,
52 )
53 # rebuild the cache if `src` has been reassigned since it was built
54 if self._src_char_code is None or self._src_char_code[0] is not self.src:
55 self._src_char_code = (self.src, tuple(ord(c) for c in self.src))
56 return self._src_char_code[1]
59class RuleOptionsType(TypedDict, total=False):
60 alt: list[str]
63RuleFuncTv = TypeVar("RuleFuncTv")
64"""A rule function, whose signature is dependent on the state type."""
67@dataclass(slots=True)
68class Rule(Generic[RuleFuncTv]):
69 name: str
70 enabled: bool
71 fn: RuleFuncTv = field(repr=False)
72 alt: list[str]
75class Ruler(Generic[RuleFuncTv]):
76 def __init__(self) -> None:
77 # List of added rules.
78 self.__rules__: list[Rule[RuleFuncTv]] = []
79 # Cached rule chains.
80 # First level - chain name, '' for default.
81 # Second level - diginal anchor for fast filtering by charcodes.
82 self.__cache__: dict[str, list[RuleFuncTv]] | None = None
84 def __find__(self, name: str) -> int:
85 """Find rule index by name"""
86 for i, rule in enumerate(self.__rules__):
87 if rule.name == name:
88 return i
89 return -1
91 def __compile__(self) -> None:
92 """Build rules lookup cache"""
93 chains = {""}
94 # collect unique names
95 for rule in self.__rules__:
96 if not rule.enabled:
97 continue
98 for name in rule.alt:
99 chains.add(name)
100 self.__cache__ = {}
101 for chain in chains:
102 self.__cache__[chain] = []
103 for rule in self.__rules__:
104 if not rule.enabled:
105 continue
106 if chain and (chain not in rule.alt):
107 continue
108 self.__cache__[chain].append(rule.fn)
110 def at(
111 self, ruleName: str, fn: RuleFuncTv, options: RuleOptionsType | None = None
112 ) -> None:
113 """Replace rule by name with new function & options.
115 :param ruleName: rule name to replace.
116 :param fn: new rule function.
117 :param options: new rule options (not mandatory).
118 :raises: KeyError if name not found
119 """
120 index = self.__find__(ruleName)
121 options = options or {}
122 if index == -1:
123 raise KeyError(f"Parser rule not found: {ruleName}")
124 self.__rules__[index].fn = fn
125 self.__rules__[index].alt = options.get("alt", [])
126 self.__cache__ = None
128 def before(
129 self,
130 beforeName: str,
131 ruleName: str,
132 fn: RuleFuncTv,
133 options: RuleOptionsType | None = None,
134 ) -> None:
135 """Add new rule to chain before one with given name.
137 :param beforeName: new rule will be added before this one.
138 :param ruleName: new rule will be added before this one.
139 :param fn: new rule function.
140 :param options: new rule options (not mandatory).
141 :raises: KeyError if name not found
142 """
143 index = self.__find__(beforeName)
144 options = options or {}
145 if index == -1:
146 raise KeyError(f"Parser rule not found: {beforeName}")
147 self.__rules__.insert(
148 index, Rule[RuleFuncTv](ruleName, True, fn, options.get("alt", []))
149 )
150 self.__cache__ = None
152 def after(
153 self,
154 afterName: str,
155 ruleName: str,
156 fn: RuleFuncTv,
157 options: RuleOptionsType | None = None,
158 ) -> None:
159 """Add new rule to chain after one with given name.
161 :param afterName: new rule will be added after this one.
162 :param ruleName: new rule will be added after this one.
163 :param fn: new rule function.
164 :param options: new rule options (not mandatory).
165 :raises: KeyError if name not found
166 """
167 index = self.__find__(afterName)
168 options = options or {}
169 if index == -1:
170 raise KeyError(f"Parser rule not found: {afterName}")
171 self.__rules__.insert(
172 index + 1, Rule[RuleFuncTv](ruleName, True, fn, options.get("alt", []))
173 )
174 self.__cache__ = None
176 def push(
177 self, ruleName: str, fn: RuleFuncTv, options: RuleOptionsType | None = None
178 ) -> None:
179 """Push new rule to the end of chain.
181 :param ruleName: new rule will be added to the end of chain.
182 :param fn: new rule function.
183 :param options: new rule options (not mandatory).
185 """
186 self.__rules__.append(
187 Rule[RuleFuncTv](ruleName, True, fn, (options or {}).get("alt", []))
188 )
189 self.__cache__ = None
191 def enable(
192 self, names: str | Iterable[str], ignoreInvalid: bool = False
193 ) -> list[str]:
194 """Enable rules with given names.
196 :param names: name or list of rule names to enable.
197 :param ignoreInvalid: ignore errors when rule not found
198 :raises: KeyError if name not found and not ignoreInvalid
199 (the rules named before it are still enabled)
200 :return: list of found rule names
201 """
202 if isinstance(names, str):
203 names = [names]
204 result: list[str] = []
205 try:
206 for name in names:
207 idx = self.__find__(name)
208 if (idx < 0) and ignoreInvalid:
209 continue
210 if (idx < 0) and not ignoreInvalid:
211 raise KeyError(f"Rules manager: invalid rule name {name}")
212 self.__rules__[idx].enabled = True
213 result.append(name)
214 finally:
215 self.__cache__ = None
216 return result
218 def enableOnly(
219 self, names: str | Iterable[str], ignoreInvalid: bool = False
220 ) -> list[str]:
221 """Enable rules with given names, and disable everything else.
223 :param names: name or list of rule names to enable.
224 :param ignoreInvalid: ignore errors when rule not found
225 :raises: KeyError if name not found and not ignoreInvalid
226 (all rules are still disabled, and the rules named before it enabled)
227 :return: list of found rule names
228 """
229 if isinstance(names, str):
230 names = [names]
231 for rule in self.__rules__:
232 rule.enabled = False
233 return self.enable(names, ignoreInvalid)
235 def disable(
236 self, names: str | Iterable[str], ignoreInvalid: bool = False
237 ) -> list[str]:
238 """Disable rules with given names.
240 :param names: name or list of rule names to enable.
241 :param ignoreInvalid: ignore errors when rule not found
242 :raises: KeyError if name not found and not ignoreInvalid
243 (the rules named before it are still disabled)
244 :return: list of found rule names
245 """
246 if isinstance(names, str):
247 names = [names]
248 result = []
249 try:
250 for name in names:
251 idx = self.__find__(name)
252 if (idx < 0) and ignoreInvalid:
253 continue
254 if (idx < 0) and not ignoreInvalid:
255 raise KeyError(f"Rules manager: invalid rule name {name}")
256 self.__rules__[idx].enabled = False
257 result.append(name)
258 finally:
259 self.__cache__ = None
260 return result
262 def getRules(self, chainName: str = "") -> list[RuleFuncTv]:
263 """Return array of active functions (rules) for given chain name.
264 It analyzes rules configuration, compiles caches if not exists and returns result.
266 Default chain name is `''` (empty string). It can't be skipped.
267 That's done intentionally, to keep signature monomorphic for high speed.
269 """
270 if self.__cache__ is None:
271 self.__compile__()
272 assert self.__cache__ is not None
273 # Chain can be empty, if rules disabled. But we still have to return Array.
274 return self.__cache__.get(chainName, []) or []
276 def get_all_rules(self) -> list[str]:
277 """Return all available rule names."""
278 return [r.name for r in self.__rules__]
280 def get_active_rules(self) -> list[str]:
281 """Return the active rule names."""
282 return [r.name for r in self.__rules__ if r.enabled]