From eeb509d6c09b4841a20127babb26bacc3af09433 Mon Sep 17 00:00:00 2001 From: Yves Chevallier <52489316+yves-chevallier@users.noreply.github.com> Date: Mon, 30 Sep 2024 19:33:45 +0200 Subject: [PATCH] Fix DRY by adding create_element method in abbr extension --- docs/changelog.md | 6 ++++++ markdown/extensions/abbr.py | 15 +++++++++------ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/docs/changelog.md b/docs/changelog.md index cb1919de..5ae25462 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -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 diff --git a/markdown/extensions/abbr.py b/markdown/extensions/abbr.py index 6b079ae2..36c1d91c 100644 --- a/markdown/extensions/abbr.py +++ b/markdown/extensions/abbr.py @@ -86,6 +86,13 @@ 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): @@ -93,9 +100,7 @@ def iter_element(self, el: etree.Element, parent: etree.Element | None = None) - 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 @@ -103,9 +108,7 @@ def iter_element(self, el: etree.Element, parent: etree.Element | None = None) - 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