Skip to content

Commit

Permalink
feat: Impl code snippet
Browse files Browse the repository at this point in the history
  • Loading branch information
SilverRainZ committed Oct 20, 2024
1 parent 02dd9e7 commit 7480bdb
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
10 changes: 5 additions & 5 deletions src/sphinxnotes/snippet/ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ''


Expand All @@ -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


Expand Down
6 changes: 4 additions & 2 deletions src/sphinxnotes/snippet/snippets.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,15 +94,14 @@ 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
desc: nodes.paragraph | str

def __init__(self, node: nodes.literal_block) -> None:
assert isinstance(node, nodes.literal_block)
super().__init__(node)

self.lang = node['language']

Expand All @@ -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')

Expand Down

0 comments on commit 7480bdb

Please sign in to comment.