MCPcopy Create free account
hub / github.com/Python-Markdown/markdown / AbbrTreeprocessor

Class AbbrTreeprocessor

markdown/extensions/abbr.py:90–137  ·  view source on GitHub ↗

Replace abbreviation text with ` ` elements.

Source from the content-addressed store, hash-verified

88
89
90class AbbrTreeprocessor(Treeprocessor):
91 """ Replace abbreviation text with `<abbr>` elements. """
92
93 def __init__(self, md: Markdown | None = None, abbrs: dict | None = None):
94 self.abbrs: dict = abbrs if abbrs is not None else {}
95 self.RE: re.RegexObject | None = None
96 super().__init__(md)
97
98 def create_element(self, title: str, text: str, tail: str) -> etree.Element:
99 ''' Create an `abbr` element. '''
100 abbr = etree.Element('abbr', {'title': title})
101 abbr.text = AtomicString(text)
102 abbr.tail = tail
103 return abbr
104
105 def iter_element(self, el: etree.Element, parent: etree.Element | None = None) -> None:
106 ''' Recursively iterate over elements, run regex on text and wrap matches in `abbr` tags. '''
107 for child in reversed(el):
108 self.iter_element(child, el)
109 if text := el.text:
110 if not isinstance(text, AtomicString):
111 for m in reversed(list(self.RE.finditer(text))):
112 if self.abbrs[m.group(0)]:
113 abbr = self.create_element(self.abbrs[m.group(0)], m.group(0), text[m.end():])
114 el.insert(0, abbr)
115 text = text[:m.start()]
116 el.text = text
117 if parent is not None and el.tail:
118 tail = el.tail
119 index = list(parent).index(el) + 1
120 if not isinstance(tail, AtomicString):
121 for m in reversed(list(self.RE.finditer(tail))):
122 abbr = self.create_element(self.abbrs[m.group(0)], m.group(0), tail[m.end():])
123 parent.insert(index, abbr)
124 tail = tail[:m.start()]
125 el.tail = tail
126
127 def run(self, root: etree.Element) -> etree.Element | None:
128 ''' Step through tree to find known abbreviations. '''
129 if not self.abbrs:
130 # No abbreviations defined. Skip running processor.
131 return
132 # Build and compile regex
133 abbr_list = list(self.abbrs.keys())
134 abbr_list.sort(key=len, reverse=True)
135 self.RE = re.compile(f"\\b(?:{ '|'.join(re.escape(key) for key in abbr_list) })\\b")
136 # Step through tree and modify on matches
137 self.iter_element(root)
138
139
140class AbbrBlockprocessor(BlockProcessor):

Callers 1

extendMarkdownMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected