MkCode

github Show source on GitHub

Class representing a Code block.

Example: Default

Jinja

{{ "a = 1 + 2" | MkCode }}

Python

MkCode(None)
a = 1 + 2
````python
a = 1 + 2
````
<pre><code class="language-python">a = 1 + 2
</code></pre>
.. sourcecode:: python
    a = 1 + 2
````python
a = 1 + 2
````
MkCode
╰── MkText('a = 1 + 2')

Example: Syntax highlighting

Jinja

{{ "var z = x + y;" | MkCode(language="js") }}

Python

MkCode(None, language='js')
var z = x + y;
````js
var z = x + y;
````
<pre><code class="language-js">var z = x + y;
</code></pre>
.. sourcecode:: js
    var z = x + y;
````js
var z = x + y;
````
MkCode
╰── MkText('var z = x + y;')

Example: Highlighting lines

Jinja

{{ "1
2
3
4" | MkCode(highlight_lines=[1, 3]) }}

Python

MkCode(None, highlight_lines=[1, 3])
1
2
3
4
````{code-block} python
:emphasize-lines: 1,3
1
2
3
4
````
<pre><code class="language-python">1
2
3
4
</code></pre>
.. sourcecode:: python
    1
    2
    3
    4
````python
1
2
3
4
````
MkCode
╰── MkText('1\n2\n3\n4')

Example: Line numbers

Jinja

{{ "1
2
3
4" | MkCode(linenums=10) }}

Python

MkCode(None, linenums=10)
101
112
123
134
````{code-block} python
:linenos:
:lineno-start: 10
1
2
3
4
````
<pre><code class="language-python">1
2
3
4
</code></pre>
.. sourcecode:: python
    1
    2
    3
    4
````python
1
2
3
4
````
MkCode
╰── MkText('1\n2\n3\n4')

class MkCode(mkcontainer.MkContainer)

Name

Children

Inherits

MkDiagram
mknodes.basenodes.mkdiagram
Class representing a mermaid diagram.

MkTreeView
mknodes.templatenodes.mktreeview
Node to display tree structures.

    Name

    Children

    Inherits

    MkContainer
    mknodes.basenodes.mkcontainer
    A node containing other MkNodes.

    graph TD
      1761293797["mkcode.MkCode"]
      835538629["mkcontainer.MkContainer"]
      1956333208["mkcontainer.MkContainerBase"]
      1359323199["mknode.MkNode"]
      2751680898["builtins.object"]
      835538629 --> 1761293797
      1956333208 --> 835538629
      1359323199 --> 1956333208
      2751680898 --> 1359323199
    
    /home/runner/work/mknodes/mknodes/src/mknodes/basenodes/mkcode/metadata.toml
    [metadata]
    icon = "mdi:code-json"
    name = "MkCode"
    
    [requirements.extension."pymdownx.superfences"]
    
    [requirements.extension."pymdownx.highlight"]
    anchor_linenums = true
    line_spans = "__span"
    pygments_lang_class = true
    
    [examples.title]
    title = "Default"
    description = "By default, python syntax highlighting is used."
    jinja = """
    {{ "a = 1 + 2" | MkCode }}
    """
    
    [examples.syntax_highlight]
    title = "Syntax highlighting"
    jinja = """
    {{ "var z = x + y;" | MkCode(language="js") }}
    """
    
    [examples.hl_lines]
    title = "Highlighting lines"
    jinja = """
    {{ "1\n2\n3\n4" | MkCode(highlight_lines=[1, 3]) }}
    """
    
    [examples.line_numbers]
    title = "Line numbers"
    jinja = """
    {{ "1\n2\n3\n4" | MkCode(linenums=10) }}
    
    """
    
    [output.markdown]
    template = """
    {{ node.fence_boundary }} {{ node.fence_title }}
    {{ node.get_text() }}
    {{ node.fence_boundary }}
    """
    
    [output.rst]
    template = """
    .. sourcecode:: {{ node.language }}
    {{ node.get_text() | indent(first=True) }}
    """
    
    mknodes.basenodes.mkcode.MkCode
     26class MkCode(mkcontainer.MkContainer):
     27    """Class representing a Code block."""
     28
     29    ICON = "material/code-json"
     30    ATTR_LIST_SEPARATOR = "\n"
     31    REQUIRED_EXTENSIONS = [
     32        resources.Extension(
     33            "pymdownx.highlight",
     34            anchor_linenums=True,
     35            line_spans="__span",
     36            pygments_lang_class=True,
     37        ),
     38        resources.Extension("pymdownx.superfences"),
     39    ]
     40
     41    def __init__(
     42        self,
     43        content: str | mk.MkNode | list[mk.MkNode] = "",
     44        *,
     45        language: str = "python",
     46        title: str = "",
     47        linenums: int | None = None,
     48        highlight_lines: list[int] | None = None,
     49        fence_level: int | None = None,
     50        **kwargs: Any,
     51    ) -> None:
     52        """Constructor.
     53
     54        Args:
     55            content: Content to show inside code box
     56            language: language for syntax highlighting
     57            title: Code block title
     58            linenums: If set, use as start linenumber
     59            highlight_lines: Optionally highlight lines
     60            fence_level: Determines amount of ticks used for fence.
     61                         If None, auto-determine based on nesting depth.
     62            kwargs: Keyword arguments passed to parent
     63        """
     64        self.language = language
     65        self.title = title
     66        self.linenums = linenums
     67        self.highlight_lines = highlight_lines
     68        self._fence_level = fence_level
     69        super().__init__(content=content, **kwargs)
     70
     71    def get_text(self) -> str:
     72        """Text content."""
     73        return "\n".join(str(i) for i in self.get_items())
     74
     75    @property
     76    def fence_boundary(self) -> str:
     77        """Return fence boundary, based on nesting level. Default is ```."""
     78        if self._fence_level:
     79            return "`" * (self._fence_level + 3)
     80        block_level = sum(isinstance(i, MkCode) for i in self.ancestors)
     81        return "`" * (block_level + 3)
     82
     83    def fence_for(self, text: str) -> str:
     84        """Return the fence for given code: longer than any fence inside the code."""
     85        inner = max((len(i) for i in INNER_FENCE_RE.findall(text)), default=0)
     86        boundary = self.fence_boundary
     87        return boundary if len(boundary) > inner else "`" * (inner + 1)
     88
     89    @property
     90    def fence_title(self) -> str:
     91        """Title in first line."""
     92        classes = " ".join(f".{i}" for i in self.mods.css_classes)
     93        attrs = {}
     94        if self.title:
     95            attrs["title"] = self.title
     96        if self.language:
     97            classes = f".{self.language} {classes}"
     98        if self.linenums is not None:
     99            attrs["linenums"] = str(self.linenums)
    100        if self.highlight_lines:
    101            sub = " ".join(str(i) for i in self.highlight_lines)
    102            attrs["hl_lines"] = sub
    103        if not classes and not attrs:
    104            return ""
    105        attr_str = " ".join(f"{k}={v!r}" for k, v in attrs.items())
    106        if attr_str:
    107            attr_str = " " + attr_str
    108        return f"{{{classes}{attr_str}}}"
    109
    110    def get_content(self) -> resources.NodeContent:
    111        """Single-pass: get code block markdown and resources."""
    112        space = " " if self.fence_title else ""
    113        text = self.get_text()
    114        fence = self.fence_for(text)
    115        md = f"{fence}{space}{self.fence_title}\n{text}\n{fence}"
    116
    117        # Get own resources (don't aggregate children since we format them as text)
    118        aggregated = self._build_node_resources()
    119
    120        return resources.NodeContent(markdown=md, resources=aggregated)
    121
    122    def to_md_unprocessed(self) -> str:
    123        content = self.get_content()
    124        return content.markdown
    125
    126    @classmethod
    127    def for_file(
    128        cls,
    129        path: JoinablePathLike,
    130        *,
    131        linenums: bool = True,
    132        highlight_caller: bool = True,
    133        title: str | None = None,
    134        language: str | None = None,
    135        **kwargs: Any,
    136    ) -> Self:
    137        """Create a MkCode node based on a code file.
    138
    139        Line numbers will be shown by default. If `highlight_caller` is `True`,
    140        it will try to detect whether the calling method is inside the code block are
    141        creating and if yes, it will highlight that line.
    142
    143        Args:
    144            path: Path to the code file (also supports fsspec-protocol URLs)
    145            linenums: Whether to show line numbers
    146            highlight_caller: Whether we want to try to highlight the line which called
    147                              this method.
    148            title: title to use for the code box. If None is set, filename will be used.
    149            language: Syntax highlighting language. If None, try to infer from extension.
    150            kwargs: Keyword arguments passed to MkCode ctor
    151        """
    152        file_path = to_upath(path)
    153        content = file_path.read_text("utf-8")
    154        hl_lines = None
    155        if highlight_caller and (frame := inspect.currentframe()) and frame.f_back:
    156            call_file = frame.f_back.f_code.co_filename
    157            if call_file == str(file_path.absolute()):
    158                line_count = content.count("\n")
    159                line = frame.f_back.f_lineno
    160                hl_lines = [line] if 0 <= line <= line_count else None
    161        start_line = 1 if linenums else None
    162        title = file_path.name if title is None else title
    163        if language is None:
    164            language = datatypes.EXT_TO_PYGMENTS_STYLE.get(file_path.suffix, "")
    165        return cls(
    166            content,
    167            linenums=start_line,
    168            title=title,
    169            highlight_lines=hl_lines,
    170            language=language,
    171            **kwargs,
    172        )
    173
    174    @classmethod
    175    def for_object(
    176        cls,
    177        obj: datatypes.HasCodeType,
    178        *,
    179        dedent: bool = True,
    180        extract_body: bool = False,
    181        title: str | None = None,
    182        linenums: bool = True,
    183        highlight_caller: bool = True,
    184        **kwargs: Any,
    185    ) -> Self:
    186        """Create a MkCode node based on a python object.
    187
    188        Fetches code by using the inspect module.
    189        Line numbers will be shown by default. If highlight_caller is True,
    190        it will try to detect whether the calling method is inside the code block are
    191        displaying and if yes, it will highlight that line.
    192
    193        Args:
    194            obj: Python object to show code from
    195            dedent: Whether to dedent the code
    196            extract_body: if True, Function / Class signatures are stripped from the code
    197            title: Title to use for code block. If None, it will use the object path.
    198            linenums: Whether to show line numbers
    199            highlight_caller: Whether we want to try to highlight the line which called
    200                              this method.
    201            kwargs: Keyword arguments passed to MkCode ctor
    202        """
    203        code = inspecthelpers.get_source(obj)
    204        if extract_body:
    205            if not callable(obj):
    206                msg = "Can only extract body from Functions, Methods and classes"
    207                raise TypeError(msg)
    208            code = textfilters.extract_body(code)
    209        code = textwrap.dedent(code) if dedent else code
    210        code_title = title if title is not None else classhelpers.get_code_name(obj)
    211        hl_lines = None
    212        lines, start_line = inspecthelpers.get_source_lines(obj)
    213        if isinstance(obj, types.ModuleType):
    214            start_line += 1
    215        if highlight_caller and (frame := inspect.currentframe()) and frame.f_back:
    216            call_file = frame.f_back.f_code.co_filename
    217            obj_file = inspecthelpers.get_file(obj)
    218            if call_file == obj_file:
    219                line_no = frame.f_back.f_lineno
    220                line = line_no - start_line + 1
    221                hl_lines = [line] if 0 <= line <= start_line + len(lines) else None
    222        return cls(
    223            code,
    224            title=code_title,
    225            linenums=start_line if linenums else None,
    226            highlight_lines=hl_lines,
    227            **kwargs,
    228        )
    
    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
    title: MkCode