Skip to content

zensical

Class info

Classes

Name Children Inherits
IconResolver
mkdocs_mknodes.writers.zensical
Make icons used by pages / social links available to the theme.
    ZensicalWriter
    mkdocs_mknodes.writers.zensical
    Write a `BuildOutput` as Zensical input: docs folder + generated config.

      šŸ›ˆ DocStrings

      Writer producing a Zensical project (Markdown pages + a generated mkdocs.yml-style config).

      Zensical has no plugin API, so the generated pages are written into the docs folder and a generated config (mkdocs.generated.yml by default) INHERITs the project's mkdocs.yml and adds the nav, the required Markdown extensions, extra CSS / JS and site metadata. Build with zensical build -f mkdocs.generated.yml (or mkdocs-mknodes build).

      IconResolver

      Make icons used by pages / social links available to the theme.

      MkNodes uses Iconify keys (grommet-icons:install). Icons available in the theme's bundled icon sets get mapped to theme paths (material/wrench), all others get downloaded into the theme override folder (.icons/iconify/<set>/<name>.svg).

      Source code in mkdocs_mknodes/writers/zensical.py
      class IconResolver:
          """Make icons used by pages / social links available to the theme.
      
          MkNodes uses Iconify keys (`grommet-icons:install`). Icons available in the theme's
          bundled icon sets get mapped to theme paths (`material/wrench`), all others get
          downloaded into the theme override folder (`.icons/iconify/<set>/<name>.svg`).
          """
      
          def __init__(self, fetch: Callable[[str], str | None] = _fetch_svg) -> None:
              self.fetch = fetch
              self.bundled = _bundled_icons_dir()
              self.svgs: dict[str, str] = {}
              """Template path (`.icons/...svg`) -> SVG of icons to add to the theme."""
              self._cache: dict[str, str | None] = {}
      
          def _is_bundled(self, theme_icon: str) -> bool:
              if self.bundled is None:  # can't check, trust the mapping
                  return True
              return (self.bundled / f"{theme_icon}.svg").is_file()
      
          def resolve(self, icon: str) -> str | None:
              """Return the theme icon path for given icon (None if it is not available)."""
              if icon not in self._cache:
                  self._cache[icon] = self._resolve(icon)
              return self._cache[icon]
      
          def _resolve(self, icon: str) -> str | None:
              theme_icon = to_theme_icon(icon)
              if theme_icon and self._is_bundled(theme_icon):
                  return theme_icon
              key = to_iconify_key(icon)
              if key is None:
                  return None
              prefix, _, name = key.partition(":")
              target = theme_icon or f"iconify/{prefix}/{name}"
              if not (svg := self.fetch(key)):
                  return None
              self.svgs[f".icons/{target}.svg"] = svg
              return target
      
          def update_page(self, markdown: str) -> str:
              """Replace the `icon` of the page front matter with a theme icon path."""
              match = FRONT_MATTER_RE.match(markdown)
              if not match or "icon:" not in match.group(1):
                  return markdown
      
              def replace(m: re.Match[str]) -> str:
                  if resolved := self.resolve(m.group(2).strip()):
                      return f"icon: {resolved}\n"
                  logger.warning("Dropping unsupported page icon %s", m.group(2))
                  return ""
      
              front_matter = ICON_LINE_RE.sub(replace, match.group(1))
              return f"---\n{front_matter}---\n{markdown[match.end() :]}"
      
          def update_social(self, social: list[dict[str, str]]) -> list[dict[str, str]]:
              """Convert social links into theme `extra.social` entries."""
              result = []
              for entry in social:
                  icon = self.resolve(entry.get("icon", ""))
                  if icon is None:
                      logger.warning("Dropping social link %s: unsupported icon", entry.get("link"))
                      continue
                  result.append({**entry, "icon": icon})
              return result
      

      svgs instance-attribute

      svgs: dict[str, str] = {}
      

      Template path (.icons/...svg) -> SVG of icons to add to the theme.

      resolve

      resolve(icon: str) -> str | None
      

      Return the theme icon path for given icon (None if it is not available).

      Source code in mkdocs_mknodes/writers/zensical.py
      def resolve(self, icon: str) -> str | None:
          """Return the theme icon path for given icon (None if it is not available)."""
          if icon not in self._cache:
              self._cache[icon] = self._resolve(icon)
          return self._cache[icon]
      

      update_page

      update_page(markdown: str) -> str
      

      Replace the icon of the page front matter with a theme icon path.

      Source code in mkdocs_mknodes/writers/zensical.py
      def update_page(self, markdown: str) -> str:
          """Replace the `icon` of the page front matter with a theme icon path."""
          match = FRONT_MATTER_RE.match(markdown)
          if not match or "icon:" not in match.group(1):
              return markdown
      
          def replace(m: re.Match[str]) -> str:
              if resolved := self.resolve(m.group(2).strip()):
                  return f"icon: {resolved}\n"
              logger.warning("Dropping unsupported page icon %s", m.group(2))
              return ""
      
          front_matter = ICON_LINE_RE.sub(replace, match.group(1))
          return f"---\n{front_matter}---\n{markdown[match.end() :]}"
      

      update_social

      update_social(social: list[dict[str, str]]) -> list[dict[str, str]]
      

      Convert social links into theme extra.social entries.

      Source code in mkdocs_mknodes/writers/zensical.py
      def update_social(self, social: list[dict[str, str]]) -> list[dict[str, str]]:
          """Convert social links into theme `extra.social` entries."""
          result = []
          for entry in social:
              icon = self.resolve(entry.get("icon", ""))
              if icon is None:
                  logger.warning("Dropping social link %s: unsupported icon", entry.get("link"))
                  continue
              result.append({**entry, "icon": icon})
          return result
      

      ZensicalWriter

      Bases: Writer

      Write a BuildOutput as Zensical input: docs folder + generated config.

      Source code in mkdocs_mknodes/writers/zensical.py
      class ZensicalWriter(Writer):
          """Write a `BuildOutput` as Zensical input: docs folder + generated config."""
      
          name = "zensical"
      
          @property
          def source_config(self) -> dict[str, Any]:
              return self.settings.site_config
      
          def write(self, output: BuildOutput) -> pathlib.Path:
              docs_dir = self.settings.resolved_docs_dir
              gen_dir = self.settings.resolved_generated_dir
              mirror = gen_dir.resolve() != docs_dir.resolve()
              folder = GeneratedFolder(gen_dir, owned=mirror)
              if mirror:
                  self._mirror_docs(docs_dir, folder, output)
              icons = IconResolver()
              pages = {path: icons.update_page(md) for path, md in output.pages.items()}
              social = icons.update_social(output.metadata.social)
              for path, content in {**output.assets, **pages}.items():
                  if not (mirror and path in folder.written):
                      folder.write(path, content)
              removed = folder.finish()
              templates_dir = self._write_templates({**output.templates, **icons.svgs})
              config = self.build_config(output, templates_dir=templates_dir, social=social)
              cfg_path = self.settings.generated_config_path
              source = self.settings.config_file.name if self.settings.config_file else "defaults"
              header = CONFIG_HEADER.format(source=source, name=cfg_path.name)
              text = header + yamlconfig.dumps(config)
              if not cfg_path.is_file() or cfg_path.read_text(encoding="utf-8") != text:
                  cfg_path.write_text(text, encoding="utf-8")
              logger.info(
                  "Wrote %s files (%s changed, %s removed, %s hand-written kept) to %s",
                  len(folder.written),
                  len(folder.changed),
                  len(removed),
                  len(folder.skipped),
                  gen_dir,
              )
              self.folder = folder
              return cfg_path
      
          def _mirror_docs(
              self, docs_dir: pathlib.Path, folder: GeneratedFolder, output: BuildOutput
          ) -> None:
              """Copy hand-written docs into the generated folder (hand-written files win)."""
              if not docs_dir.is_dir():
                  return
              for root, dirs, files in os.walk(docs_dir):
                  dirs[:] = [d for d in dirs if d not in SKIP_MIRROR_DIRS]
                  for filename in files:
                      src = pathlib.Path(root) / filename
                      rel = src.relative_to(docs_dir).as_posix()
                      if rel in output.files:
                          logger.warning("Hand-written %s shadows a generated file", rel)
                      folder.write(rel, src.read_bytes())
      
          def _write_templates(self, templates: dict[str, str]) -> str | None:
              """Write theme template overrides (and icons) into the theme's custom_dir."""
              theme = self.source_config.get("theme")
              custom_dir = theme.get("custom_dir") if isinstance(theme, dict) else None
              if not templates and not custom_dir:
                  return None
              rel_dir = str(custom_dir or DEFAULT_OVERRIDES_DIR)
              folder = GeneratedFolder(self.settings.project_dir / rel_dir)
              for filename, html in templates.items():
                  folder.write(filename, html)
              folder.finish()
              return None if custom_dir else rel_dir
      
          def build_config(
              self,
              output: BuildOutput,
              *,
              templates_dir: str | None = None,
              social: list[dict[str, str]] | None = None,
          ) -> dict[str, Any]:
              """Return the generated config (to be layered over the source config)."""
              src = self.source_config
              cfg: dict[str, Any] = {}
              if self.settings.config_file:
                  rel = os.path.relpath(self.settings.config_file, self.settings.project_dir)
                  cfg["INHERIT"] = pathlib.Path(rel).as_posix()
              meta = output.metadata
              for key in ("site_name", "site_description", "site_author", "repo_url", "copyright"):
                  if not src.get(key) and (value := getattr(meta, key)):
                      cfg[key] = value
              if "site_name" not in cfg and not src.get("site_name"):
                  cfg["site_name"] = self.settings.project_dir.name
              gen_dir = self.settings.resolved_generated_dir
              if gen_dir.resolve() != self.settings.resolved_docs_dir.resolve():
                  rel_docs = os.path.relpath(gen_dir, self.settings.project_dir)
                  cfg["docs_dir"] = pathlib.Path(rel_docs).as_posix()
              if self.settings.site_dir:
                  cfg["site_dir"] = self.settings.site_dir
              if templates_dir:
                  cfg["theme"] = {"custom_dir": templates_dir}
              user_nav = src.get("nav")
              if not isinstance(user_nav, list):
                  user_nav = []
              if nav := nav_to_config(output.nav):
                  cfg["nav"] = [*user_nav, *nav]
              cfg["markdown_extensions"] = merge_markdown_extensions(
                  src.get("markdown_extensions"), output.markdown_extensions
              )
              css = list(src.get("extra_css") or [])
              css += [c for c in output.extra_css if c not in css]
              if css:
                  cfg["extra_css"] = css
              js = list(src.get("extra_javascript") or [])
              known = {_script_path(i) for i in js}
              js += [_script_to_config(s) for s in output.extra_javascript if s.path not in known]
              if js:
                  cfg["extra_javascript"] = js
              extra = dict(output.extra)
              src_extra = src.get("extra")
              if not isinstance(src_extra, dict):
                  src_extra = {}
              if meta.social and not src_extra.get("social"):
                  extra["social"] = social_to_config(meta.social) if social is None else social
              if extra:
                  cfg["extra"] = extra
              excluded = [line for line in (src.get("exclude_docs") or "").splitlines() if line]
              excluded += [p for p in EXCLUDED_DOCS if p not in excluded]
              cfg["exclude_docs"] = "\n".join(excluded) + "\n"
              return cfg
      
          def build_command(
              self, *, serve: bool = False, extra_args: list[str] | None = None
          ) -> list[str]:
              cmd = [sys.executable, "-m", "zensical", "serve" if serve else "build"]
              cmd += ["-f", str(self.settings.generated_config_path)]
              return cmd + list(extra_args or [])
      
          @staticmethod
          def is_available() -> bool:
              return shutil.which("zensical") is not None or _has_module("zensical")
      

      build_config

      build_config(
          output: BuildOutput,
          *,
          templates_dir: str | None = None,
          social: list[dict[str, str]] | None = None
      ) -> dict[str, Any]
      

      Return the generated config (to be layered over the source config).

      Source code in mkdocs_mknodes/writers/zensical.py
      def build_config(
          self,
          output: BuildOutput,
          *,
          templates_dir: str | None = None,
          social: list[dict[str, str]] | None = None,
      ) -> dict[str, Any]:
          """Return the generated config (to be layered over the source config)."""
          src = self.source_config
          cfg: dict[str, Any] = {}
          if self.settings.config_file:
              rel = os.path.relpath(self.settings.config_file, self.settings.project_dir)
              cfg["INHERIT"] = pathlib.Path(rel).as_posix()
          meta = output.metadata
          for key in ("site_name", "site_description", "site_author", "repo_url", "copyright"):
              if not src.get(key) and (value := getattr(meta, key)):
                  cfg[key] = value
          if "site_name" not in cfg and not src.get("site_name"):
              cfg["site_name"] = self.settings.project_dir.name
          gen_dir = self.settings.resolved_generated_dir
          if gen_dir.resolve() != self.settings.resolved_docs_dir.resolve():
              rel_docs = os.path.relpath(gen_dir, self.settings.project_dir)
              cfg["docs_dir"] = pathlib.Path(rel_docs).as_posix()
          if self.settings.site_dir:
              cfg["site_dir"] = self.settings.site_dir
          if templates_dir:
              cfg["theme"] = {"custom_dir": templates_dir}
          user_nav = src.get("nav")
          if not isinstance(user_nav, list):
              user_nav = []
          if nav := nav_to_config(output.nav):
              cfg["nav"] = [*user_nav, *nav]
          cfg["markdown_extensions"] = merge_markdown_extensions(
              src.get("markdown_extensions"), output.markdown_extensions
          )
          css = list(src.get("extra_css") or [])
          css += [c for c in output.extra_css if c not in css]
          if css:
              cfg["extra_css"] = css
          js = list(src.get("extra_javascript") or [])
          known = {_script_path(i) for i in js}
          js += [_script_to_config(s) for s in output.extra_javascript if s.path not in known]
          if js:
              cfg["extra_javascript"] = js
          extra = dict(output.extra)
          src_extra = src.get("extra")
          if not isinstance(src_extra, dict):
              src_extra = {}
          if meta.social and not src_extra.get("social"):
              extra["social"] = social_to_config(meta.social) if social is None else social
          if extra:
              cfg["extra"] = extra
          excluded = [line for line in (src.get("exclude_docs") or "").splitlines() if line]
          excluded += [p for p in EXCLUDED_DOCS if p not in excluded]
          cfg["exclude_docs"] = "\n".join(excluded) + "\n"
          return cfg
      

      merge_markdown_extensions

      merge_markdown_extensions(configured: Any, required: dict[str, dict[str, Any]]) -> list[Any]
      

      Merge required extensions into the configured ones and return a config list.

      Source code in mkdocs_mknodes/writers/zensical.py
      def merge_markdown_extensions(
          configured: Any,
          required: dict[str, dict[str, Any]],
      ) -> list[Any]:
          """Merge required extensions into the configured ones and return a config list."""
          if configured is None:
              configured = _zensical_default_extensions()
          exts = _normalize_extensions(configured)
          for name, cfg in required.items():
              current = exts.get(name)
              if current is None or isinstance(current, yamlconfig.Tagged):
                  exts[name] = cfg or current
              elif cfg:
                  exts[name] = merge_values(current, cfg)
          return [name if not cfg else {name: cfg} for name, cfg in exts.items()]
      

      merge_values

      merge_values(base: Any, update: Any) -> Any
      

      Deep-merge update into base: dicts recursively, lists without duplicates.

      Source code in mkdocs_mknodes/writers/zensical.py
      def merge_values(base: Any, update: Any) -> Any:
          """Deep-merge `update` into `base`: dicts recursively, lists without duplicates."""
          if isinstance(base, dict) and isinstance(update, dict):
              merged = dict(base)
              for k, v in update.items():
                  merged[k] = merge_values(merged[k], v) if k in merged else v
              return merged
          if isinstance(base, list) and isinstance(update, list):
              merged_list = list(base)
              for item in update:
                  if item not in merged_list and not _same_fence(item, merged_list):
                      merged_list.append(item)
              return merged_list
          return update
      

      nav_to_config

      nav_to_config(items: list[NavItem]) -> list[Any]
      

      Convert NavItems into the MkDocs / Zensical nav list format.

      Source code in mkdocs_mknodes/writers/zensical.py
      def nav_to_config(items: list[NavItem]) -> list[Any]:
          """Convert `NavItem`s into the MkDocs / Zensical `nav` list format."""
          result: list[Any] = []
          for item in items:
              if item.is_section:
                  result.append({item.title: nav_to_config(item.children)})
              else:
                  result.append({item.title: item.target})
          return result
      

      social_to_config

      social_to_config(social: list[dict[str, str]]) -> list[dict[str, str]]
      

      Convert social links (Iconify icons) into theme extra.social entries.

      Source code in mkdocs_mknodes/writers/zensical.py
      def social_to_config(social: list[dict[str, str]]) -> list[dict[str, str]]:
          """Convert social links (Iconify icons) into theme `extra.social` entries."""
          return IconResolver(fetch=lambda _key: None).update_social(social)
      

      to_iconify_key

      to_iconify_key(icon: str) -> str | None
      

      Convert a theme icon path (material/wrench) to an Iconify key (mdi:wrench).

      Source code in mkdocs_mknodes/writers/zensical.py
      def to_iconify_key(icon: str) -> str | None:
          """Convert a theme icon path (`material/wrench`) to an Iconify key (`mdi:wrench`)."""
          if ":" in icon:
              return icon
          for prefix, folder in ICON_SETS.items():
              if icon.startswith(f"{folder}/"):
                  return f"{prefix}:{icon.removeprefix(folder + '/')}"
          return None
      

      to_theme_icon

      to_theme_icon(icon: str) -> str | None
      

      Convert an Iconify key (fa-brands:github) to a theme icon path.

      Icons already in theme format (fontawesome/brands/github) are returned unchanged, unknown icon sets return None.

      Source code in mkdocs_mknodes/writers/zensical.py
      def to_theme_icon(icon: str) -> str | None:
          """Convert an Iconify key (`fa-brands:github`) to a theme icon path.
      
          Icons already in theme format (`fontawesome/brands/github`) are returned unchanged,
          unknown icon sets return None.
          """
          if ":" not in icon:
              return icon
          prefix, _, name = icon.partition(":")
          return f"{ICON_SETS[prefix]}/{name}" if prefix in ICON_SETS else None
      
      Page info
      Resources
      Resources(css=[],
                markdown_extensions={'tables': {}},
                plugins=[Plugin('mkdocstrings')],
                js=[],
                assets=[],
                packages=[])
      
      Metadata
      created:
        source_filename: /home/runner/work/mkdocs-mknodes/mkdocs-mknodes/.venv/lib/python3.13/site-packages/mknodes/pages/mkmodulepage/__init__.py
        source_function: MkModulePage.__init__
        source_line_no: 52
      title: zensical