Skip to content

Commit

Permalink
Fix DRY by adding create_element method in abbr extension
Browse files Browse the repository at this point in the history
  • Loading branch information
yves-chevallier authored Sep 30, 2024
1 parent d312609 commit eeb509d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
6 changes: 6 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). See the [Contributing Guide](contributing.md) for details.

## [Unreleased]

### Changed

* DRY fix in `abbr` extension by introducing method `create_element` (#1483).

## [3.7] -- 2024-08-16

### Changed
Expand Down
15 changes: 9 additions & 6 deletions markdown/extensions/abbr.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,26 +86,29 @@ def __init__(self, md: Markdown | None = None, abbrs: dict | None = None):
self.RE: re.RegexObject | None = None
super().__init__(md)

def create_element(self, title: str, text: str, tail: str) -> etree.Element:
''' Create an `abbr` element. '''
abbr = etree.Element('abbr', {'title': title})
abbr.text = AtomicString(text)
abbr.tail = tail
return abbr

def iter_element(self, el: etree.Element, parent: etree.Element | None = None) -> None:
''' Recursively iterate over elements, run regex on text and wrap matches in `abbr` tags. '''
for child in reversed(el):
self.iter_element(child, el)
if text := el.text:
for m in reversed(list(self.RE.finditer(text))):
if self.abbrs[m.group(0)]:
abbr = etree.Element('abbr', {'title': self.abbrs[m.group(0)]})
abbr.text = AtomicString(m.group(0))
abbr.tail = text[m.end():]
abbr = self.create_element(self.abbrs[m.group(0)], m.group(0), text[m.end():])
el.insert(0, abbr)
text = text[:m.start()]
el.text = text
if parent is not None and el.tail:
tail = el.tail
index = list(parent).index(el) + 1
for m in reversed(list(self.RE.finditer(tail))):
abbr = etree.Element('abbr', {'title': self.abbrs[m.group(0)]})
abbr.text = AtomicString(m.group(0))
abbr.tail = tail[m.end():]
abbr = self.create_element(self.abbrs[m.group(0)], m.group(0), tail[m.end():])
parent.insert(index, abbr)
tail = tail[:m.start()]
el.tail = tail
Expand Down

0 comments on commit eeb509d

Please sign in to comment.