MkCommentedCode¶
Node which displays a list of code / comment blocks for given code.¶
Description
Lines beginning with # are shown in dedicated blocks and can be used to inline-explain the code. Lines can be hidden by ending a line with “##”.
Example: From text
Jinja
{{
"
# Comment sections automatically get converted to non-codeblock sections.
# That way you can explain your code in-line.
# ## you can use headers.
some_code = 1 + 2
# !!! note
# Admonitions and everything else work, too.
#
" | MkCommentedCode
}}
Python
MkCommentedCode(
"\n# Comment sections automatically get converted to non-codeblock sections.\n# That way you can explain your code in-line.\n\n# ## you can use headers.\n\nsome_code = 1 + 2\n\n# !!! note\n# Admonitions and everything else work, too.\n#\n\n"
)
Comment sections automatically get converted to non-codeblock sections. That way you can explain your code in-line.
you can use headers.
some_code = 1 + 2
Note
Admonitions and everything else work, too.
<div class="speech bottom">
Comment sections automatically get converted to non-codeblock sections.
That way you can explain your code in-line.
## you can use headers.
</div>
````python
some_code = 1 + 2
````
<div class="speech bottom">
!!! note
Admonitions and everything else work, too.
</div>
<div class="speech bottom">
<p>Comment sections automatically get converted to non-codeblock sections.
That way you can explain your code in-line.</p>
<h2>you can use headers.</h2>
</div>
<pre><code class="language-python">some_code = 1 + 2
</code></pre>
<div class="speech bottom">
<p>!!! note
Admonitions and everything else work, too.</p>
</div>
MkCommentedCode
├── MkSpeechBubble()
│ ╰── MkText('Comment sections automatically get converted to non-codeblock sections.\nThat way you can explain your code in-line.\n## you can use headers.')
├── MkCode(None)
│ ╰── MkText('some_code = 1 + 2')
╰── MkSpeechBubble()
╰── MkText('!!! note\n Admonitions and everything else work, too.\n')
Example: From function
Jinja
{{ mk.MkCommentedCode.create_example_page | MkCommentedCode }}
Python
MkCommentedCode(<bound method MkCommentedCode.create_example_page of <class 'mknodes.templatenodes.mkcommentedcode.<locals>.MkCommentedCode'>>)
@classmethod
def create_example_page(cls, page) -> None:
Comment sections automatically get converted to non-codeblock sections. That way you can explain your code in-line.
you can use headers.
page += MkCommentedCode(MkCommentedCode.create_example_page)
Note
Admonitions and everything else work, too.
page += MkCommentedCode(MkCommentedCode.create_example_page, style="admonition")
````python
@classmethod
def create_example_page(cls, page) -> None:
````
<div class="speech bottom">
Comment sections automatically get converted to non-codeblock sections.
That way you can explain your code in-line.
## you can use headers.
</div>
````python
page += MkCommentedCode(MkCommentedCode.create_example_page)
````
<div class="speech bottom">
!!! note
Admonitions and everything else work, too.
</div>
````python
page += MkCommentedCode(MkCommentedCode.create_example_page, style="admonition")
````
<pre><code class="language-python"> @classmethod
def create_example_page(cls, page) -> None:
</code></pre>
<div class="speech bottom">
<p>Comment sections automatically get converted to non-codeblock sections.
That way you can explain your code in-line.</p>
<h2>you can use headers.</h2>
</div>
<pre><code class="language-python"> page += MkCommentedCode(MkCommentedCode.create_example_page)
</code></pre>
<div class="speech bottom">
<p>!!! note
Admonitions and everything else work, too.</p>
</div>
<pre><code class="language-python"> page += MkCommentedCode(MkCommentedCode.create_example_page, style="admonition")
</code></pre>
MkCommentedCode
├── MkCode(None)
│ ╰── MkText(' @classmethod\n def create_example_page(cls, page) -> None:')
├── MkSpeechBubble()
│ ╰── MkText('Comment sections automatically get converted to non-codeblock sections.\nThat way you can explain your code in-line.\n## you can use headers.')
├── MkCode(None)
│ ╰── MkText(' page += MkCommentedCode(MkCommentedCode.create_example_page)')
├── MkSpeechBubble()
│ ╰── MkText('!!! note\n Admonitions and everything else work, too.\n')
╰── MkCode(None)
╰── MkText(' page += MkCommentedCode(MkCommentedCode.create_example_page, style="admonition")')
Name |
Children |
Inherits |
|---|---|---|
MkTemplate |
graph TD
634542573["mkcommentedcode.MkCommentedCode"]
1289759389["mktemplate.MkTemplate"]
3160803176["rendercache.TemplateRenderMixin"]
2751680898["builtins.object"]
835538629["mkcontainer.MkContainer"]
1956333208["mkcontainer.MkContainerBase"]
1359323199["mknode.MkNode"]
1289759389 --> 634542573
3160803176 --> 1289759389
2751680898 --> 3160803176
835538629 --> 1289759389
1956333208 --> 835538629
1359323199 --> 1956333208
2751680898 --> 1359323199
/home/runner/work/mknodes/mknodes/src/mknodes/templatenodes/mkcommentedcode/metadata.toml¶
[metadata]
icon = "mdi:code-json"
name = "MkCommentedCode"
status = "new"
group = "documentation"
virtual_children = true
[examples.from_text]
title = "From text"
jinja = """
{{
"
# Comment sections automatically get converted to non-codeblock sections.
# That way you can explain your code in-line.
# ## you can use headers.
some_code = 1 + 2
# !!! note
# Admonitions and everything else work, too.
#
" | MkCommentedCode
}}
"""
[examples.from_function]
title = "From function"
jinja = """
{{ mk.MkCommentedCode.create_example_page | MkCommentedCode }}
"""
[output.markdown]
template = """
{% for section in node.iter_code_sections() %}
{% if section.typ == "code" %}
{{ section.code | MkCode(linenums=section.start_line) }}
{% else %}
{% set comment = section.code | MkText(render_jinja=node.render_comments) %}
{% if node.style == "text" %}
{{ comment }}
{% elif node.style == "bubble" %}
{{ comment | MkSpeechBubble }}
{% elif node.style == "admonition" %}
{{ comment | MkAdmonition }}
{% endif %}
{% endif %}
{% endfor %}
"""
mknodes.templatenodes.mkcommentedcode.MkCommentedCode¶
22class MkCommentedCode(mktemplate.MkTemplate):
23 """Node which displays a list of code / comment blocks for given code.
24
25 Lines beginning with # are shown in dedicated blocks and can be used to
26 inline-explain the code. Lines can be hidden by ending a line with "##".
27 """
28
29 ICON = "material/code-json"
30 STATUS = "new"
31 VIRTUAL_CHILDREN = True
32
33 def __init__(
34 self,
35 code: str | datatypes.HasCodeType,
36 language: str = "py",
37 *,
38 linenums: int | None = None,
39 style: Literal["text", "admonition", "bubble"] = "bubble",
40 render_comments: bool = False,
41 **kwargs: Any,
42 ) -> None:
43 """Constructor.
44
45 Args:
46 code: Code to show
47 language: language for syntax highlighting
48 linenums: If set, use as start linenumber
49 style: Comment style
50 render_comments: Render the comments with Jinja (they can contain
51 `{{ ... }}` expressions, the code stays as it is)
52 kwargs: Keyword arguments passed to parent
53 """
54 self._code = code
55 self.language = language
56 self.title = ""
57 self.linenums = linenums
58 self.style = style
59 self.render_comments = render_comments
60 super().__init__(template="output/markdown/template", **kwargs)
61
62 def iter_code_sections(self) -> Iterator[Section]:
63 lines: list[str] = []
64 mode = ""
65 line_num = self.linenums or 0
66 for i, line in enumerate(self.code.split("\n"), start=line_num):
67 if not line.strip() or line.rstrip().endswith("##"):
68 continue
69 if line.strip().startswith("#"):
70 if mode == "code":
71 code = "\n".join(lines)
72 yield Section(mode, code, start_line=line_num if self.linenums else None)
73 lines = []
74 line_num = i
75 lines.append(line.strip().removeprefix("#")[1:])
76 mode = "comment"
77 elif not line.strip().startswith("#"):
78 if mode == "comment":
79 text = "\n".join(lines)
80 yield Section("comment", text)
81 lines = []
82 line_num = i
83 lines.append(line)
84 mode = "code"
85 if mode == "code":
86 code = "\n".join(lines)
87 yield Section("code", code, start_line=line_num if self.linenums else None)
88 elif mode == "comment":
89 text = "\n".join(lines)
90 yield Section("comment", text)
91
92 @property
93 def code(self) -> str:
94 match self._code:
95 case str():
96 return self._code
97 case _:
98 return inspecthelpers.get_source(self._code)
99
100 @classmethod
101 def create_example_page(cls, page) -> None:
102 # Comment sections automatically get converted to non-codeblock sections.
103 # That way you can explain your code in-line.
104
105 # ## you can use headers.
106
107 page += MkCommentedCode(MkCommentedCode.create_example_page)
108 # !!! note
109 # Admonitions and everything else work, too.
110 #
111 page += MkCommentedCode(MkCommentedCode.create_example_page, style="admonition")
Page info
Code for this page
mknodes.manual.nodes_section.create_section_for_nodes¶
93def create_section_for_nodes(
94 nav: mk.MkNav,
95 klasses: Sequence[type[mk.MkNode]],
96) -> mk.MkTable:
97 table = mk.MkTable(columns=["Node", "Docstrings", "Markdown extensions"])
98 for kls in klasses:
99 tpl = "classpage_custom.jinja"
100 page = mk.MkClassPage(kls, icon=kls.ICON, template_path=tpl, parent=nav, hide="toc")
101 nav += page
102 if kls.STATUS:
103 page.metadata.status = kls.STATUS
104 elif kls.JS_FILES:
105 page.metadata.status = "js"
106 elif kls.CSS:
107 page.metadata.status = "css"
108 page.created_by = create_section_for_nodes
109 link = mk.MkLink(page, kls.__name__, icon=kls.ICON)
110 extensions = ", ".join(f"`{i}`" for i in kls.REQUIRED_EXTENSIONS)
111 table.add_row((link, kls.__doc__, extensions))
112 return table
Resources
Resources(css=[],
markdown_extensions={'admonition': {},
'pymdownx.details': {},
'pymdownx.highlight': {'anchor_linenums': True,
'line_spans': '__span',
'pygments_lang_class': True},
'pymdownx.superfences': {'custom_fences': [{'class': 'mermaid',
'format': <function fence_code_format at 0x7ff77e88b060>,
'name': 'mermaid'}]},
'pymdownx.tabbed': {},
'tables': {}},
plugins=[Plugin('mkdocstrings')],
js=[],
assets=[],
packages=[])
Metadata
created:
source_filename: /home/runner/work/mknodes/mknodes/src/mknodes/manual/nodes_section.py
source_function: create_section_for_nodes
source_line_no: 93
hide:
- toc
icon: material/code-json
status: new
title: MkCommentedCode