From 7d1a4853d70012e8b3f6cf534fc43f66cfe64acd Mon Sep 17 00:00:00 2001 From: Angus Hollands Date: Thu, 22 Feb 2024 15:19:00 +0000 Subject: [PATCH] maint: use findall instead of traverse --- src/sphinx_book_theme/__init__.py | 3 ++- src/sphinx_book_theme/_compat.py | 9 +++++++++ src/sphinx_book_theme/_transforms.py | 5 +++-- 3 files changed, 14 insertions(+), 3 deletions(-) create mode 100644 src/sphinx_book_theme/_compat.py diff --git a/src/sphinx_book_theme/__init__.py b/src/sphinx_book_theme/__init__.py index 7910628c..379d3afa 100644 --- a/src/sphinx_book_theme/__init__.py +++ b/src/sphinx_book_theme/__init__.py @@ -20,6 +20,7 @@ ) from .header_buttons.launch import add_launch_buttons from .header_buttons.source import add_source_buttons +from ._compat import findall from ._transforms import HandleFootnoteTransform __version__ = "1.1.2" @@ -53,7 +54,7 @@ def add_metadata_to_page(app, pagename, templatename, context, doctree): # Add a shortened page text to the context using the sections text if doctree: description = "" - for section in doctree.traverse(docutil_nodes.section): + for section in findall(doctree, docutil_nodes.section): description += section.astext().replace("\n", " ") description = description[:160] context["page_description"] = description diff --git a/src/sphinx_book_theme/_compat.py b/src/sphinx_book_theme/_compat.py new file mode 100644 index 00000000..99e70b8d --- /dev/null +++ b/src/sphinx_book_theme/_compat.py @@ -0,0 +1,9 @@ +from docutils.nodes import Element +from typing import Iterator + + +def findall(node: Element, *args, **kwargs) -> Iterator[Element]: + # findall replaces traverse in docutils v0.18 + # note a difference is that findall is an iterator + impl = getattr(node, "findall", node.traverse) + return iter(impl(*args, **kwargs)) diff --git a/src/sphinx_book_theme/_transforms.py b/src/sphinx_book_theme/_transforms.py index a6349893..93843402 100644 --- a/src/sphinx_book_theme/_transforms.py +++ b/src/sphinx_book_theme/_transforms.py @@ -4,6 +4,7 @@ from sphinx import addnodes as sphinx_nodes from pydata_sphinx_theme.utils import get_theme_options_dict from .nodes import SideNoteNode +from ._compat import findall class HandleFootnoteTransform(SphinxPostTransform): @@ -19,10 +20,10 @@ def run(self, **kwargs: Any) -> None: # Cycle through footnote references, and move their content next to the # reference. This lets us display the reference in the margin, # or just below on narrow screens. - for ref_node in self.document.traverse(docutil_nodes.footnote_reference): + for ref_node in findall(self.document, docutil_nodes.footnote_reference): parent = None # Each footnote reference should have a single node it points to via `ids` - for foot_node in self.document.traverse(docutil_nodes.footnote): + for foot_node in findall(self.document, docutil_nodes.footnote): # matching the footnote reference with footnote if ( len(foot_node.attributes["backrefs"])