From 7480bdb19fe37ec91eaf5f41b8d9a0f3932fe29b Mon Sep 17 00:00:00 2001 From: Shengyu Zhang Date: Sun, 20 Oct 2024 13:14:00 +0800 Subject: [PATCH] feat: Impl code snippet --- src/sphinxnotes/snippet/ext.py | 10 +++++----- src/sphinxnotes/snippet/snippets.py | 6 ++++-- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/sphinxnotes/snippet/ext.py b/src/sphinxnotes/snippet/ext.py index 5d00694..3e73936 100644 --- a/src/sphinxnotes/snippet/ext.py +++ b/src/sphinxnotes/snippet/ext.py @@ -56,8 +56,8 @@ def extract_excerpt(s: Snippet) -> str: elif isinstance(s, Section) and s.title is not None: return '[' + s.title.text + ']' elif isinstance(s, Code): - excerpt = s.desc.astext() if s.desc else s.caption or '' # FIXME - return '`' + s.language + ':' + excerpt + '`' + excerpt = s.desc.astext() if isinstance(s.desc, nodes.paragraph) else s.desc + return '`' + s.lang + ':' + excerpt + '`' return '' @@ -66,10 +66,10 @@ def extract_keywords(s: Snippet) -> list[str]: if isinstance(s, WithTitle) and s.title is not None: keywords.extend(extractor.extract(s.title.text, strip_stopwords=False)) if isinstance(s, Code): - if s.desc: + if isinstance(s.desc, nodes.paragraph): keywords.extend(extractor.extract(s.desc.astext(), strip_stopwords=False)) - if s.caption: - keywords.extend(extractor.extract(s.caption, strip_stopwords=False)) + else: + keywords.extend(extractor.extract(s.desc, strip_stopwords=False)) return keywords diff --git a/src/sphinxnotes/snippet/snippets.py b/src/sphinxnotes/snippet/snippets.py index 4438415..623b975 100644 --- a/src/sphinxnotes/snippet/snippets.py +++ b/src/sphinxnotes/snippet/snippets.py @@ -94,7 +94,7 @@ def __init__(self, node: nodes.Node) -> None: self.text = node.astext() -class Code(Text): +class Code(Snippet): #: Language of code block lang: str #: Description of code block, usually the text of preceding paragraph @@ -102,7 +102,6 @@ class Code(Text): def __init__(self, node: nodes.literal_block) -> None: assert isinstance(node, nodes.literal_block) - super().__init__(node) self.lang = node['language'] @@ -121,11 +120,14 @@ def __init__(self, node: nodes.literal_block) -> None: # of the code block. This convention also applies to the code, # code-block, sourcecode directive. self.desc = para + print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>') + super().__init__(para, node) elif caption := node.get('caption'): # Use caption as descritpion. # In sphinx, code-block, sourcecode and code may have caption option. # https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-code-block self.desc = caption + super().__init__(node) else: raise ValueError('Lack of description: preceding paragraph or caption')