Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix DRY by adding create_element method in abbr extension #1483

Merged
merged 2 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading