单页构建

单页构建#

Added in version 0.14.0.

Sphinx 以及 MyST-NB 建立在 Docutils 包之上。MyST-NB 提供了渲染器、解析器和 CLI 接口,用于直接与 Docutils 一起工作,独立于 Sphinx,如下所述。

备注

由于这些工具独立于 Sphinx,这意味着它们无法解析任何 Sphinx 或 Sphinx 扩展特定的角色或指令。

安装 MyST-NB 后,可以使用以下 CLI 命令:

  • mystnb-docutils-html:将笔记本转换为 HTML

  • mystnb-docutils-html5:将笔记本转换为 HTML5

  • mystnb-docutils-latex: 将笔记本转换为 LaTeX

  • mystnb-docutils-xml: 将笔记本转换为 docutils-native XML

  • mystnb-docutils-pseudoxml: 将笔记本转换为伪 XML(用于可视化 AST 结构)

每个命令都可以通过管道传递 stdin 或将文件路径作为参数:

$ mystnb-docutils-html --help
$ mystnb-docutils-html --nb-execution-mode="off" hello-world.ipynb
$ mystnb-docutils-html --nb-read-as-md="yes" hello-world.md

这些命令基于 Docutils 前端工具,因此遵循相同的参数和选项结构,包括 配置 部分中详细说明的许多 MyST NB 特定选项。

共享的 Docutils 命令行界面选项
Usage
=====
  mystnb-docutils-<writer> [options] [<source> [<destination>]]

Options
=======
General Docutils Options
------------------------
--output=<destination>  Output destination name. Obsoletes the <destination>
                        positional argument. Default: None (stdout).
--title=<title>         Specify the document title as metadata.
--generator, -g         Include a "Generated by Docutils" credit and link.
--no-generator          Do not include a generator credit.
--date, -d              Include the date at the end of the document (UTC).
--time, -t              Include the time & date (UTC).
--no-datestamp          Do not include a datestamp of any kind.
--root-prefix=<path>    Base directory for absolute paths when reading from
                        the local filesystem. Default "/".
--source-link, -s       Include a "View document source" link.
--source-url=<URL>      Use <URL> for a source link; implies --source-link.
--no-source-link        Do not include a "View document source" link.
--toc-entry-backlinks   Link from section headers to TOC entries.  (default)
--toc-top-backlinks     Link from section headers to the top of the TOC.
--no-toc-backlinks      Disable backlinks to the table of contents.
--footnote-backlinks    Link from footnotes/citations to references. (default)
--no-footnote-backlinks
                        Disable backlinks from footnotes and citations.
--section-numbering     Enable section numbering by Docutils.  (default)
--no-section-numbering  Disable section numbering by Docutils.
--strip-comments        Remove comment elements from the document tree.
--leave-comments        Leave comment elements in the document tree. (default)
--strip-elements-with-class=<class>
                        Remove all elements with classes="<class>" from the
                        document tree. Warning: potentially dangerous; use
                        with caution. (Multiple-use option.)
--strip-class=<class>   Remove all classes="<class>" attributes from elements
                        in the document tree. Warning: potentially dangerous;
                        use with caution. (Multiple-use option.)
--report=<level>, -r <level>
                        Report system messages at or higher than <level>:
                        "info" or "1", "warning"/"2" (default), "error"/"3",
                        "severe"/"4", "none"/"5"
--verbose, -v           Report all system messages.  (Same as "--report=1".)
--quiet, -q             Report no system messages.  (Same as "--report=5".)
--halt=<level>          Halt execution at system messages at or above <level>.
                        Levels as in --report.  Default: 4 (severe).
--strict                Halt at the slightest problem.  Same as "--halt=info".
--exit-status=<level>   Enable a non-zero exit status for non-halting system
                        messages at or above <level>.  Default: 5 (disabled).
--debug                 Enable debug-level system messages and diagnostics.
--no-debug              Disable debug output.  (default)
--warnings=<file>       Send the output of system messages to <file>.
--traceback             Enable Python tracebacks when Docutils is halted.
--no-traceback          Disable Python tracebacks.  (default)
--input-encoding=<name[:handler]>, -i <name[:handler]>
                        Specify the encoding and optionally the error handler
                        of input text.  Default: <auto-detect>:strict.
--input-encoding-error-handler=INPUT_ENCODING_ERROR_HANDLER
                        Specify the error handler for undecodable characters.
                        Choices: "strict" (default), "ignore", and "replace".
--output-encoding=<name[:handler]>, -o <name[:handler]>
                        Specify the text encoding and optionally the error
                        handler for output.  Default: utf-8:strict.
--output-encoding-error-handler=OUTPUT_ENCODING_ERROR_HANDLER
                        Specify error handler for unencodable output
                        characters; "strict" (default), "ignore", "replace",
                        "xmlcharrefreplace", "backslashreplace".
--error-encoding=<name[:handler]>, -e <name[:handler]>
                        Specify text encoding and optionally error handler for
                        error output.  Default: utf-8:backslashreplace.
--error-encoding-error-handler=ERROR_ENCODING_ERROR_HANDLER
                        Specify the error handler for unencodable characters
                        in error output.  Default: backslashreplace.
--language=<name>, -l <name>
                        Specify the language (as BCP 47 language tag).
                        Default: en.
--record-dependencies=<file>
                        Write output file dependencies to <file>.
--config=<file>         Read configuration settings from <file>, if it exists.
--version, -V           Show this program's version number and exit.
--help, -h              Show this help message and exit.

MyST-NB options
---------------
--nb-read-as-md=<boolean>
                        Read as the MyST Markdown format (default: False)
--nb-metadata-key=<str>
                        Notebook level metadata key for config overrides
                        (default: (default: 'mystnb'))
--nb-cell-metadata-key=<str>
                        Cell level metadata key for config overrides (default:
                        (default: 'mystnb'))
--nb-eval-name-regex=<str>
                        Regex that matches permitted values of eval
                        expressions (default: (default: '^[a-zA-
                        Z_][a-zA-Z0-9_]*$'))
--nb-execution-mode=<'off'|'force'|'auto'|'cache'|'inline'>
                        Execution mode for notebooks (default: 'auto')
--nb-execution-cache-path=<str>
                        Path to folder for caching notebooks (default:
                        <outdir>) (default: (default: ''))
--nb-execution-timeout=<int>
                        Execution timeout (seconds) (default: 30)
--nb-execution-in-temp=<boolean>
                        Use temporary folder for the execution current working
                        directory (default: False)
--nb-execution-allow-errors=<boolean>
                        Allow errors during execution (default: False)
--nb-execution-raise-on-error=<boolean>
                        Raise an exception on failed execution, rather than
                        emitting a warning (default: False)
--nb-execution-show-tb=<boolean>
                        Print traceback to stderr on execution error (default:
                        False)
--nb-merge-streams=<boolean>
                        Merge stdout/stderr execution output streams (default:
                        False)
--nb-render-plugin=<str>
                        The entry point for the execution output render class
                        (in group `myst_nb.output_renderer`) (default:
                        (default: 'default'))
--nb-remove-code-source=<boolean>
                        Remove code cell source (default: False)
--nb-remove-code-outputs=<boolean>
                        Remove code cell outputs (default: False)
--nb-code-prompt-show=<str>
                        Prompt to expand hidden code cell
                        {content|source|outputs} (default: (default: 'Show
                        code cell {type}'))
--nb-code-prompt-hide=<str>
                        Prompt to collapse hidden code cell
                        {content|source|outputs} (default: (default: 'Hide
                        code cell {type}'))
--nb-number-source-lines=<boolean>
                        Number code cell source lines (default: False)
--nb-builder-name=<str>
                        Builder name, to select render priority for mime types
                        (default: (default: 'html'))
--nb-output-stderr=<'show'|'remove'|'remove-warn'|'warn'|'error'|'severe'>
                        Behaviour for stderr output (default: 'show')
--nb-render-text-lexer=<str>
                        Pygments lexer applied to stdout/stderr and text/plain
                        outputs (default: (default: 'myst-ansi'))
--nb-render-error-lexer=<str>
                        Pygments lexer applied to error/traceback outputs
                        (default: (default: 'ipythontb'))
--nb-render-markdown-format=<'commonmark'|'gfm'|'myst'>
                        The format to use for text/markdown rendering
                        (default: 'commonmark')
--nb-output-folder=<str>
                        Folder for external outputs (like images), skipped if
                        empty (default: (default: 'build'))
--nb-append-css=<boolean>
                        Add default MyST-NB CSS to HTML outputs (default:
                        True)
--nb-metadata-to-fm=<boolean>
                        Convert unhandled metadata to frontmatter (default:
                        False)

MyST options
------------
--myst-commonmark-only=<boolean>
                        Use strict CommonMark parser (default: False)
--myst-gfm-only=<boolean>
                        Use strict Github Flavoured Markdown parser (default:
                        False)
--myst-enable-extensions=<comma-delimited>
                        Enable syntax extensions
--myst-disable-syntax=<comma-delimited>
                        Disable Commonmark syntax elements
--myst-all-links-external=<boolean>
                        Parse all links as simple hyperlinks (default: False)
--myst-links-external-new-tab=<boolean>
                        Open all external links in a new tab (default: False)
--myst-url-schemes=<comma-delimited>|<yaml-dict>
                        URI schemes that are converted to external links
                        (default: http,https,mailto,ftp)
--myst-fence-as-directive=<comma-delimited>
                        Interpret a code fence as a directive, for certain
                        language names. This can be useful for fences like dot
                        and mermaid, and interoperability with other Markdown
                        renderers.
--myst-number-code-blocks=<comma-delimited>
                        Add line numbers to code blocks with these languages
--myst-title-to-header=<boolean>
                        Convert a `title` field in the front-matter to a H1
                        header (default: False)
--myst-heading-anchors=<int>
                        Heading level depth to assign HTML anchors (default:
                        0)
--myst-heading-slug-func=<str>
                        Function for creating heading anchors, or a python
                        import path e.g. `my_package.my_module.my_function`
                        (default: (default: 'None'))
--myst-html-meta=<yaml-dict>
                        HTML meta tags
--myst-footnote-sort=<boolean>
                        Move all footnotes to the end of the document, and
                        sort by reference order (default: True)
--myst-footnote-transition=<boolean>
                        Place a transition before sorted footnotes (default:
                        True)
--myst-words-per-minute=<int>
                        For reading speed calculations (default: 200)
--myst-substitutions=<yaml-dict>
                        Substitutions mapping
--myst-linkify-fuzzy-links=<boolean>
                        Recognise URLs without schema prefixes (default: True)
--myst-dmath-allow-labels=<boolean>
                        Parse `$$...$$ (label)` (default: True)
--myst-dmath-allow-space=<boolean>
                        Allow initial/final spaces in `$ ... $` (default:
                        True)
--myst-dmath-allow-digits=<boolean>
                        Allow initial/final digits `1$ ...$2` (default: True)
--myst-dmath-double-inline=<boolean>
                        Parse inline `$$ ... $$` (default: False)
--myst-enable-checkboxes=<boolean>
                        Enable checkboxes (default: False)
--myst-suppress-warnings=<comma-delimited>
                        A list of warning types to suppress warning messages
--myst-highlight-code-blocks=<boolean>
                        Syntax highlight code blocks with pygments (default:
                        True)
--myst-inventories=<yaml-dict>
                        Mapping of key to (url, inv file), for intra-project
                        referencing

Generic Parser Options
----------------------
--no-file-insertion     Disable directives that insert the contents of an
                        external file; replaced with a "warning" system
                        message.
--file-insertion-enabled
                        Enable directives that insert the contents of an
                        external file. (default)
--no-raw                Disable the "raw" directive; replaced with a "warning"
                        system message.
--raw-enabled           Enable the "raw" directive. (default)
--line-length-limit=<length>
                        Maximal number of characters in an input line. Default
                        10 000.

reStructuredText Parser Options
-------------------------------
--pep-references        Recognize and link to standalone PEP references (like
                        "PEP 258").
--pep-base-url=<URL>    Base URL for PEP references (default
                        "https://peps.python.org/").
--pep-file-url-template=<URL>
                        Template for PEP file part of URL. (default
                        "pep-%04d")
--rfc-references        Recognize and link to standalone RFC references (like
                        "RFC 822").
--rfc-base-url=<URL>    Base URL for RFC references (default
                        "https://tools.ietf.org/html/").
--tab-width=<width>     Set number of spaces for tab expansion (default 8).
--trim-footnote-reference-space
                        Remove spaces before footnote references.
--leave-footnote-reference-space
                        Leave spaces before footnote references.
--syntax-highlight=<format>
                        Token name set for parsing code with Pygments: one of
                        "long", "short", or "none" (no parsing). Default is
                        "long".
--smart-quotes=<yes/no/alt>
                        Change straight quotation marks to typographic form:
                        one of "yes", "no", "alt[ernative]" (default "no").
--smartquotes-locales=<language:quotes[,language:quotes,...]>
                        Characters to use as "smart quotes" for <language>.
--word-level-inline-markup
                        Inline markup recognized at word boundaries only
                        (adjacent to punctuation or whitespace). Force
                        character-level inline markup recognition with "\ "
                        (backslash + space). Default.
--character-level-inline-markup
                        Inline markup recognized anywhere, regardless of
                        surrounding characters. Backslash-escapes must be used
                        to avoid unwanted markup recognition. Useful for East
                        Asian languages. Experimental.

命令行界面(CLI)命令还可以利用 docutils.conf 配置文件 来配置 CLI 命令的行为。例如:

# These entries affect all processing:
[general]
nb_execution_mode: off

# These entries affect specific HTML output:
[html writers]
embed-stylesheet: no

[html5 writer]
stylesheet-dirs: path/to/html5_polyglot/
stylesheet-path: minimal.css, responsive.css

你也可以通过编程方式使用 myst_nb.docutils_.Parser 类,结合 Docutils 发布者 API 来实现:

from docutils.core import publish_string
from nbformat import writes
from nbformat.v4 import new_notebook
from myst_nb.docutils_ import Parser

source = writes(new_notebook())
output = publish_string(
    source=source,
    writer_name="html5",
    settings_overrides={
        "nb_execution_mode": "off",
        "embed_stylesheet": False,
    },
    parser=Parser(),
)

最后,你可以使用 include 指令,在 reStructuredText 文件中包含 MyST Markdown 文件:

.. include:: include.ipynb
   :parser: myst_nb.docutils_

重要

parser 选项需要 docutils>=0.17 版本。