selfdoc v0.15.1 /selfdoc.html
On this page

HTML rendering module that tokenizes Markdown, dispatches blocks to specialized renderers, applies post-processors, and assembles full page shells.

#selfdoc.html

#selfdoc.html

Convert Markdown files to static HTML with a built-in minimal converter.

No external dependencies -- handles headings, code blocks, inline code, paragraphs, lists, links, bold/italic, tables, blockquotes, and admonitions. Syntax highlighting uses Pygments when available (optional dependency).

#_minify_js

python
def _minify_js(js_text)

Minify JavaScript by removing comments and collapsing whitespace.

Conservative approach: avoids breaking URLs containing // and preserves single spaces between identifiers.

#_generate_search_js

python
def _generate_search_js(engine='builtin')

Return the search JS as a standalone IIFE string.

Composes the search engine implementation (builtin, fuse, or minisearch) with the shared dialog UI code. The engine must implement two functions: initSearchEngine(entries) and searchEntries(query) returning [{title, path, snippet, score, highlights}].

Args:

  • engine: One of "builtin", "fuse", or "minisearch".

#_slugify

python
def _slugify(text)

Convert heading text to a URL-friendly slug for deep linking.

Strips HTML tags first, then: NFKD-normalize to decompose accented characters, strip combining marks, lowercase, spaces to hyphens, remove non-word characters except hyphens (preserves CJK/Cyrillic).

#get_css

python
def get_css(theme_name='minimal')

Return the CSS content for the named theme.

Args:

  • theme_name: Name of the theme to load (default "minimal").

Returns:

  • The CSS content as a string.

#_flatten_dark_css

python
def _flatten_dark_css(dark_rules)

Convert dark mode CSS rules to flat selectors.

Pygments get_style_defs returns rules like .code-block code .hll { ... }. We need to wrap each rule individually for both @media and [data-theme] contexts instead of nesting them (which is invalid CSS without native nesting).

#generate_pygments_css

python
def generate_pygments_css(light_style='default', dark_style='monokai')

Generate Pygments CSS rules for light and dark mode.

Args:

  • light_style: Pygments style name for light mode.
  • dark_style: Pygments style name for dark mode.

Scoped to .code-block code to match the HTML structure produced by _render_code_block().

Returns the CSS string, or an empty string if Pygments is not installed.

#_generate_hero_html

python
def _generate_hero_html(branding, project_name, config_description, nav_items)

Generate the hero section HTML for the landing page.

Args:

  • branding: Branding config dict (must not be None).
  • project_name: Project name for the hero title.
  • config_description: Project-level description from config.
  • nav_items: Navigation items list, used to derive default CTA link.

Returns:

  • HTML string for the hero section.

#_generate_features_html

python
def _generate_features_html(branding, nav_items)

Generate the feature grid HTML for the landing page.

When branding.features is set, uses those explicitly. Otherwise auto-generates one feature card per nav group (subdirectory).

Args:

  • branding: Branding config dict (must not be None).
  • nav_items: Navigation items list from _build_nav.

Returns:

  • HTML string for the feature grid, or empty string if no features.

#generate_html

python
def generate_html(markdown_files, project_name=None, version=None, has_custom_css=False, repo=None, docs_dir_name='docs/', base_url=None, frontmatter=None, lang='en', page_dates=None, author=None, feed_url=None, critical_css=None, twitter_site=None, search=None, feedback=None, branch='main', search_engine=None, branding=None, config_description=None, auto_detect=None, theme_meta=None, deploy_target=None, run_button=False, line_numbers=False, page_nav=True, page_progress=True, code_icons='colorful', glossary=True, url_prefix='', available_versions=None, available_locales=None, current_version='', current_locale='', is_latest=True)

Convert Markdown files to static HTML.

Args:

  • markdown_files: Dict mapping relative paths to MD content.
  • project_name: Project name for titles and sidebar.
  • version: Version string for display (optional).
  • has_custom_css: Whether a custom.css file exists for the project.
  • repo: GitHub repo URL for "Edit this page" links (optional).
  • docs_dir_name: Docs directory name for constructing source paths.
  • base_url: Base URL for canonical links and sitemap (optional).
  • frontmatter: Dict mapping relative paths to metadata dicts (Feature 34).
  • page_dates: Dict mapping relative paths to (published, modified) tuples (optional).
  • author: Author dict from config (optional, keys: name, type, url).
  • feed_url: Relative URL to the Atom feed (optional, e.g. "feed.xml").
  • url_prefix: Path prefix for versioned/localized URLs (e.g. "en/0.7.0").
  • available_versions: List of version dicts for version picker (optional).
  • available_locales: List of locale dicts for locale picker (optional).
  • current_version: Current version being built (e.g. "0.7.0").
  • current_locale: Current locale being built (e.g. "en").
  • is_latest: Whether this is the latest version (default True).

Returns:

  • Dict mapping file paths (.html) to HTML content.

#generate_404_page

python
def generate_404_page(project_name=None, version=None, has_custom_css=False, nav_items=None, repo=None, base_url=None, lang='en', feed_url=None, critical_css=None, theme_meta=None)

Generate a custom 404 page using the standard page template (Feature 39).

Returns the full HTML string for 404.html.

#_render_heading

python
def _render_heading(token, seen_slugs, first_h1_consumed_ref)

Render a Heading token to HTML.

Returns the HTML string, or empty string if this is the first H1 (which is consumed as the page title by _wrap_page).

#_render_table

python
def _render_table(token, tokens, idx)

Render a Table token to HTML, wrapped in .table-wrap with caption.

#_render_definition_list

python
def _render_definition_list(token)

Render a DefinitionList token to HTML.

#_render_block

python
def _render_block(token, tokens, idx, seen_slugs, first_h1_consumed_ref, run_button=False, line_numbers=False, code_icons='colorful')

Dispatch a single block token to its HTML renderer.

Returns the HTML string, or None if the token produces no output (e.g. BlankLine, or the first H1).

#md_to_html

python
def md_to_html(text, metadata=None, config=None)

Convert Markdown text to HTML.

Handles: headings, code blocks (with tabs and annotations), inline code, paragraphs, unordered lists, ordered lists, links, bold, italic, tables.

Args:

  • text: Markdown source text.
  • metadata: Per-page frontmatter dict (optional). Keys auto_steps

and auto_api (bool) override the corresponding global settings from config.

  • config: Project config dict (optional). The auto_detect key

(an object with optional bool keys steps and api_entries) controls whether heuristics run globally. Per-page metadata takes precedence over global config.

#_render_code_block

python
def _render_code_block(lang, code_lines, annotations=None, run=False, line_numbers=False, line_start=1, code_icons='colorful')

Render a single fenced code block to HTML.

Handles diff highlighting (Feature 27), inline code annotations (Feature 32), build-time syntax highlighting via Pygments (Wave 3 Phase 0), optional line numbers, and language icons.

#_group_code_tabs

python
def _group_code_tabs(html)

Group consecutive code blocks into a tabbed interface (Feature 31).

Detects runs of consecutive

elements (with different language labels) and wraps them in a tab container. Only groups blocks that have language labels.

#_apply_step_guides

python
def _apply_step_guides(html)

Add class="steps" to

    elements that follow step/guide/tutorial headings (Feature 33).

    Uses a two-pass approach: finds each

      without a class, then searches backward (up to 200 characters) for an h2/h3 whose plain text starts with "step", "guide", or "tutorial" (case-insensitive). If found with no intervening h2/h3 between the match and the
        , adds class="steps".

        #_wrap_api_entries

        python
        def _wrap_api_entries(html)

        Wrap h3/h4 + code block + description paragraph in API entry cards (Feature 48).

        When an h3 or h4 heading is followed by a code-block div (a function/type signature) and a

        (description), with optional whitespace/newlines between them, wrap them together in a

        .

        Guards:

        • Only wraps when the heading text looks like an identifier (snake_case,

        camelCase, PascalCase, dotted.method), not natural-language headings.

        • Only wraps when the code block is short (at most 2 newlines / 3 lines),

        indicating a signature rather than example code.

        #_apply_definitions

        python
        def _apply_definitions(html)

        Wrap definitional subjects in tags when they follow headings.

        Detects patterns like "X is a ...", "X refers to ...", "X means ...", "X represents ...", or the inverted "A/An X is ..." in the first

        after an

        or

        heading, and wraps X in .

        #_split_table_cells

        python
        def _split_table_cells(line)

        Split a markdown table line by unescaped pipes, unescaping \| in cells.

        #_parse_table

        python
        def _parse_table(table_lines)

        Parse markdown table lines into an HTML

        .

        Expects lines like:

        _parse_table
        Header1Header2
        Cell1Cell2

        The separator line (containing only |, -, :, and spaces) is detected and used to separate header from body rows. Alignment markers (:) in the separator produce text-align styles on cells. Escaped pipes (\|) in cell content are treated as literal pipe characters.

        #_parse_blockquote

        python
        def _parse_blockquote(bq_lines)

        Parse blockquote lines, detecting admonitions.

        If the first line matches [!TYPE] where TYPE is a recognized admonition, render as a styled admonition div. Otherwise render as a plain blockquote.

        #_render_diff_lines

        python
        def _render_diff_lines(code_lines)

        Render code lines with diff-style highlighting.

        Lines starting with '+' get class "line-add", lines starting with '-' get class "line-remove". Other lines get a plain "line" span.

        #_inline_format

        python
        def _inline_format(text)

        Apply inline formatting: links, bold, italic, inline code.

        #_apply_cross_page_terms

        python
        def _apply_cross_page_terms(body_html, site_terms, current_page, prefix)

        Link the first occurrence of each cross-page term in body HTML.

        For every term defined on a DIFFERENT page, finds the first occurrence in body_html that is NOT inside , ,

        , , 
        , or

        -

        tags, and wraps it in an pointing to the definition page.

        Only the first match per term is linked to avoid link spam.

        #_escape_html

        python
        def _escape_html(text)

        Escape HTML special characters.

        #_md_to_html_path

        python
        def _md_to_html_path(md_path)

        Convert a .md path to a directory-index HTML path.

        guide.md becomes guide/index.html (served as /guide/). index.md stays index.html (root page, not index/index.html). Subdirectory pages follow the same rule: api/endpoints.md becomes api/endpoints/index.html.

        #_html_path_to_url

        python
        def _html_path_to_url(html_path)

        Convert an HTML file path to its clean URL form.

        guide/index.html becomes guide/. index.html stays index.html (root page). Used for link hrefs, canonical URLs, and sitemap entries.

        #_html_to_md_path

        python
        def _html_to_md_path(html_path)

        Reverse of _md_to_html_path: convert HTML path back to .md path.

        guide/index.html becomes guide.md. index.html becomes index.md. api/endpoints/index.html becomes api/endpoints.md.

        #_build_nav

        python
        def _build_nav(markdown_files, frontmatter=None)

        Build navigation items from the markdown file list.

        Sorts by frontmatter 'order' (lower = first), then alphabetically (Feature 35). Index.md is always first regardless of order.

        Pages in subdirectories are grouped under collapsible nav groups. Group title defaults to the titlecased directory name but can be overridden via nav_group frontmatter. nav_order frontmatter controls sort order within a group (default 0, ties broken alphabetically).

        Returns list of dicts. Ungrouped items: {"label": str, "path": str, "md_path": str} Group items: {"group": str, "slug": str, "items": [ungrouped-style dicts]}

        #_flatten_nav

        python
        def _flatten_nav(nav_items)

        Flatten grouped nav items into a simple page list.

        Groups are expanded in order so that prev/next links work across group boundaries. Returns a list of dicts with label, path, and md_path keys (no group wrappers).

        #_render_nav

        python
        def _render_nav(nav_items, prefix, current_path='')

        Render the sidebar navigation HTML.

        Ungrouped items render as flat

      1. elements. Grouped items render inside
        / wrappers with a nav-group class. The group containing the active page gets the open attribute so it auto-expands.

        Link hrefs use clean directory URLs (e.g. guide/ instead of guide/index.html).

        #_extract_title

        python
        def _extract_title(md_content, fallback)

        Extract the first H1 heading from markdown content as the page title.

        #_truncate_description

        python
        def _truncate_description(description)

        Truncate a description string for use in meta tags.

        If the description exceeds 155 characters, truncates at the last word boundary before 155 chars and appends "...". Returns the original string unchanged if it fits within 155 characters.

        #_extract_first_paragraph

        python
        def _extract_first_paragraph(body_html)

        Extract the text of the first

        element from rendered HTML.

        Returns the plain text (tags stripped) or an empty string if no paragraph is found.

        #_build_toc

        python
        def _build_toc(body_html)

        Extract h2/h3 headings from body HTML and build a TOC nested list.

        Returns HTML string for the TOC, or empty string if fewer than 2 headings.

        #_build_breadcrumbs

        python
        def _build_breadcrumbs(html_path, page_title, prefix, existing_pages=None)

        Build breadcrumb HTML for a non-index page.

        For flat pages like guide.html, produces Home / Guide. For subdirectory pages like api/endpoints.html, produces Home / Api / Endpoints with intermediate directory links. If an intermediate directory index page does not exist in existing_pages, the segment is rendered as a instead of a link.

        Args:

        • html_path: The current page's html path (e.g. "guide.html"

        or "api/endpoints.html").

        • page_title: The page title extracted from the first heading.
        • prefix: Relative prefix back to root.
        • existing_pages: Optional set of HTML paths that actually exist.

        Returns:

        • Breadcrumb HTML string.

        #_render_seo_tags

        python
        def _render_seo_tags(title, base_url, page_path, description, body_html, author, project_name, repo, date_published, date_modified, lang, breadcrumbs, schema, twitter_site, deploy_target, available_locales=None, current_locale='', url_prefix='')

        Build SEO tags: JSON-LD structured data, OG meta, canonical, hreflang, security.

        python
        def _render_page_footer(edit_link_html, date_display_html, feedback_html, page_nav_html)

        Assemble the page footer from edit link, dates, feedback, and nav.

        #_render_topbar

        python
        def _render_topbar(project_name, version_badge, topbar_page_title_html, search_trigger_html, prefix, url_prefix='', available_versions=None, available_locales=None, current_version='', current_locale='', is_latest=True)

        Build the topbar header with hamburger, project name, theme toggle, search.

        #_render_search_dialog

        python
        def _render_search_dialog(prefix, current_version='')

        Build the search dialog HTML.

        Args:

        • prefix: Relative path prefix back to root.
        • current_version: Current version string for the default-version

        filter attribute (e.g. "1.0.0").

        #_build_page_meta

        python
        def _build_page_meta(body_html, nav_html, title, prefix, repo, source_path, branch, breadcrumbs, prev_page, next_page, page_nav, page_progress, page_number, total_pages, feedback, toc_html, summary, date_modified, feed_url, page_path, site_terms, has_custom_css_href, version, project_name, description, has_hero, custom_css_href, theme_meta, url_prefix='', available_versions=None, available_locales=None, current_version='', current_locale='', is_latest=True)

        Compute all page metadata variables needed by the template.

        Returns a dict with: body_html (possibly modified by cross-page terms), version_badge, custom_css_tag, feed_tag, description_tag, breadcrumbs_html, edit_link_html, content_date_html, page_nav_html, feedback_html, date_display_html, footer_html, toc_aside, mobile_toc_html, summary_html, topbar_page_title_html, font_tags, auto_h1_html, search_trigger_html, meta_description, feed_footer_html.

        #_wrap_page

        python
        def _wrap_page(body_html, nav_html, title, project_name, version, css_href='style.css', custom_css_href=None, toc_html='', breadcrumbs=None, prev_page=None, next_page=None, prefix='', repo=None, source_path=None, base_url=None, page_path=None, description='', lang='en', date_published=None, date_modified=None, author=None, feed_url=None, summary=None, critical_css=None, schema=None, twitter_site=None, search=None, feedback=None, branch='main', search_engine=None, site_terms=None, page_number=None, total_pages=None, theme_meta=None, has_hero=False, deploy_target=None, page_nav=True, page_progress=True, url_prefix='', available_versions=None, available_locales=None, current_version='', current_locale='', is_latest=True)

        Wrap converted HTML body in the full page template.