%%% -------------------------------------------------------------------
%%% codemwe 宏包中英文使用说明书
%%% Author: Nan Geng <nangeng@nwafu.edu.cn>
%%% -------------------------------------------------------------------
\documentclass[full]{l3doc}
\usepackage{ctex}
\usepackage{enumitem}
\usepackage{indentfirst}
\usepackage{titling}
\usepackage{geometry}
\usepackage{fancyvrb-ex}
\usepackage{tikz}
\usepackage{codehigh}
\usepackage{codemwe}

\IndexPrologue
  {
    \section*{Index}
    \markboth{Index}{Index}
    \addcontentsline{toc}{section}{Index}
    The~italic~numbers~denote~the~pages~where~the~
    corresponding~entry~is~described,~
    numbers~underlined~point~to~the~definition,~
    all~others~indicate~the~places~where~it~is~used.
  }

\geometry{
  left   = 4.5cm,
  right  = 2.0cm,
  top    = 2.0cm,
  bottom = 2.0cm,
}

\hypersetup{
  CJKbookmarks,
  bookmarksopen,
  bookmarksopenlevel=3,
  pdfstartview=FitH,
  pdfinfo = {
    Title   = The package codemwe,
    Subject = A LaTeX3 package,
    Author  = Geng Nan
  }
}

\DoNotIndex{\begin, \end}
\setlength{\parskip}{\medskipamount}

% 中英文注意环境
\DeclareDocumentEnvironment { noteen } { +b } {
  \par\textbf{\textsf{NOTE:~}}#1\par
} {}
\DeclareDocumentEnvironment { notezh } { +b } {
  \par\textbf{\textsf{注意:~}}#1\par
} {}

\AtEndDocument{
  \newgeometry{
    left   = 2.0cm,
    right  = 2.0cm,
    top    = 2.0cm,
    bottom = 2.0cm
  }
  \PrintIndex
}

\ExplSyntaxOn
% 一个简单的代码框环境
\dim_new:N \l__my_syntax_dim
\box_new:N \g__my_syntax_box
\NewDocumentEnvironment { Syntax } { s }
  {
    \dim_set:Nn \l__my_syntax_dim { \textwidth }
    \hbox_gset:Nw \g__my_syntax_box
      \small \ttfamily
      \begin{minipage}[t]{\l__my_syntax_dim}
        \raggedright\obeyspaces\obeylines
  }
  {
      \end{minipage}
    \hbox_gset_end:
    \IfValueF { #1 } { \smallskip }
    \box_use_drop:N \g__my_syntax_box
    \smallskip
  }

% 描述列表
\DeclareDocumentEnvironment { Description } { o +b } {
  \hbox_set:Nn \l_tmpa_box { #1 }
  \dim_set:Nn \l_tmpa_dim { \box_wd:N \l_tmpa_box }
  \begin{itemize}[labelwidth=\l_tmpa_dim, align=left]
    #2
  \end{itemize}
} {  }

% 选项条目
\keys_define:nn { codemwe/doc } {
  opt  .tl_set:N = \l_opt_tl,
  desc .tl_set:N = \l_desc_tl,
  init .tl_set:N = \l_init_tl,
  init .initial:n = init-none,
}

% 行内代码：用于选项条目正文（因环境体参数中不能使用 \verb）
\NewDocumentCommand \optcode { m }
  { \texttt{\detokenize{#1}} }

% 选项条目环境：选项名/说明行 + 正文说明
\DeclareDocumentEnvironment { option } { m +b } {
  \keys_set:nn { codemwe/doc } { #1 }
  \par\medskip\noindent
  \hbox~to\linewidth\bgroup
    \small\ttfamily
    \textcolor{red}{\l_opt_tl}%
    \tl_if_empty:NF \l_desc_tl { ~\l_desc_tl }%
    \hfil
    (\tl_if_eq:NnTF \l_init_tl { init-none } { no~value }
       { init:~\texttt{\expandafter\detokenize\expandafter{\l_init_tl}} })%
  \egroup
  \par\nobreak\ignorespaces
  #2
  \medskip
} {  }

\DeclareDocumentCommand \opt { O{} m }
  { \__codedoc_cmd:no {#1} { #2 } }
\ExplSyntaxOff

% 版本信息
\def\vers{\texttt{v1.1.0}
\thanks{\url{https://gitee.com/nwafu_nan/codemwe}}
}

\changes{v1.0.0}{2026/10/10}{first version.}
\changes{v1.1.0}{2026/10/23}{add \opt{minted} and \opt{mintedstyle}
  options for syntax highlighting, and the optional \pkg{minted}
  language name of \tn{codemweNewBackend}.}

\begin{document}
\title{
  \pkg{codemwe}代码框及结果框排版\\ 与MWE文件生成宏包
  \rlap{\makebox[4.0cm][r]{
    \normalsize $\Longrightarrow$ \color{red}
    \protect\hyperlink{en}{English Version}
    \protect\hypertarget{zh}{}
  }}
}
\author{\textit{耿楠} \texttt{<nangeng@nwafu.edu.cn>}}
\date{\the\year 年\the\month 月\the\day 日\qquad \vers
}
\maketitle

{\small
\tableofcontents
}
\newpage

\begin{documentation}

\section{引言}

\pkg{codemwe}是一个基于\pkg{tcolorbox}宏包用\pkg{Expl3}开发的
示例代码排版宏包，它用于排版示例代码框及其编译结果框，并自动生成
可独立编译的MWE(Minimal Working Example) 文件。
它将示例代码置于代码框中，将其编译结果置于结果框中，
两者可按水平或垂直方式排列，适合代码与结果的对比阅读。

该宏包提供了\env{example}、\env{example*}、\env{texcode}和\env{ccode}四个环境。
其中，\env{example}环境默认采用水平模式排版，即左侧为代码框、
右侧为结果框；\env{example*}环境是垂直模式的兼容写法，即上方为
代码框、下方为结果框；\env{texcode}环境仅排版一个代码框，
不编号、不编译，适合插入无需编译的代码片段；\env{ccode}环境用于
排版C语言代码，仅显示代码框并生成\file{.c} MWE 源文件。

同时，该宏包还提供了\tn{codemweset}命令用于设置全局默认选项，
\tn{codemweNewBox}命令用于注册用户自定义的盒子，
\tn{codemweNewLang}命令用于注册用户自定义的过渡语、注释词条的语种，
以及\tn{codemweNewBackend}命令用于注册需要排版的后端代码语言。

除本节的总体介绍外，后面依次讨论用户接口（第\ref{sec:iface}节）、
排版模式（第\ref{sec:mode}节）、编号与引用、结果图片、导言区内容的
输出控制、代码后端（第\ref{sec:backend}节）、行号、宏包选项、盒子类型、
全部选项说明（第\ref{sec:opts}节）、注意事项、实现简介与常见问题。
若要快速上手，可先看第\ref{sec:iface}节与第\ref{sec:mode}节，
再按需查阅第\ref{sec:opts}节。

\begin{notezh}
  为实现中文排版，在手册的中文部分将\pkg{codemwe}宏包的\texttt{textlang}语种选项
  设置为\texttt{zh}，在中文结束后，排版英文手册之前恢复英文。
\end{notezh}

\begin{texcode}
\codemweset{ textlang = zh }
\end{texcode}

% 设置排版中文内容选项
\codemweset{ textlang = zh }

\section{用户接口}\label{sec:iface}

\subsection{\env{example}环境}

\leftskip=0pt
\begin{function}[added=2026-10-10]{\begin{example},\end{example}}
  \begin{syntax}
    \tn{begin}\marg{example}\oarg{选项}\marg{前置内容}
      \meta{示例代码}
    \tn{end}\marg{example}
  \end{syntax}
\end{function}

  用于排版示例代码及其编译结果，默认以水平模式（左代码框、右结果框）
  显示，同时自动生成可独立编译的MWE 源文件。

  该环境有一个可选参数\oarg{选项}和一个\textbf{必选}参数\marg{前置内容}。

  \oarg{选项}为逗号分隔的key-value列表。有些选项是布尔型，
  只能取 |true| 或 |false|。对于这些选项，
  \Arg{选项}| = true| 中的``|= true|''可以省略。

  \marg{前置内容}用于写入MWE 文件的前置内容（如\LaTeX{}文件的导言区），
  可包含\tn{newcommand}、\tn{tikzset}、\verb|#include <stdio.h>|等内容。
  若不需要追加前置内容，则花括号留空|{}|，但\textbf{必须}有一对空花括号。

  \env{example}环境默认会对示例代码进行编号，若有\tn{chapter}命令，
  则其编号格式为“章号.编号”，并会自动生成引用标签（如\verb|ex:1-1|）；
  若无\tn{chapter}命令，则其编号格式为“编号”，自动生成的引用标签如\verb|ex:1|。
  如：

\begin{texcode}
\begin{example}[cls={ctexart}]{}
\ExplSyntaxOn
\tl_clear_new:N \l__test_tl
\tl_set:Nn \l__test_tl { 猫儿喜欢鱼 }
\tl_use:N \l__test_tl
\ExplSyntaxOff
\end{example}
\end{texcode}

\subsection{\env{example*}环境}

\begin{function}[added=2026-10-10]{\begin{example*},\end{example*}}
  \begin{syntax}
    \tn{begin}\marg{example*}\oarg{选项}\marg{前置内容}
      \meta{示例代码}
    \tn{end}\marg{example*}
  \end{syntax}
\end{function}

  用于排版示例代码及其编译结果，默认以上代码框和下结果框的垂直模式
  显示。它等价于设置了\optcode{vmode = true}的\env{example}环境；
  如设置了\verb|[cls={ctexart}, pkg = {tikz}]|的\env{example*}环境相当于
  设置了\verb|[vmode, cls={ctexart}, pkg = {tikz}]|的\env{example}环境。如：

\begin{texcode}
\begin{example*}[cls={ctexart}, pkg={tikz}]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 0) -- (1, 1);
\end{tikzpicture}
\end{example*}
\end{texcode}

\subsection{\env{texcode}环境}

\begin{function}[added=2026-10-10]{\begin{texcode},\end{texcode}}
  \begin{syntax}
    \tn{begin}\marg{texcode}\oarg{选项}
      \meta{代码片段}
    \tn{end}\marg{texcode}
  \end{syntax}
\end{function}

  用于排版\LaTeX{}示例代码，不编号、不生成引用标签、不编译示例代码，也不生成
  MWE \file{tex}文件。它适用于在正文中插入无需编译的示例代码片段。

  \oarg{选项}与\env{example}环境一致。

  \env{texcode}环境实际上是通过为\env{example}环境预置
  |[vmode, nonum, noshow]|选项实现的，它等价于
  \tn{begin}|{example}||[vmode, nonum, noshow]|\marg{...}\ldots
  \tn{end}|{example}|。

\begin{example}[vmode, noshow, nonum]{}
\begin{texcode}
\ExplSyntaxOn
\tl_clear_new:N \l__test_tl
\tl_set:Nn \l__test_tl { 猫儿喜欢鱼 }
\tl_use:N \l__test_tl
\ExplSyntaxOff
\end{texcode}
\end{example}

\changes{v1.0.0}{2026/10/20}{ add \env{ccode} environment and \tn{codemweNewBackend}.}

\subsection{\env{ccode}环境}

\begin{function}[added=2026-10-20]{\begin{ccode},\end{ccode}}
  \begin{syntax}
    \tn{begin}\marg{ccode}\oarg{选项}
      \meta{C语言代码片段}
    \tn{end}\marg{ccode}
  \end{syntax}
\end{function}

  用于排版C语言代码，仅显示一个代码框，不编号、不显示结果框，
  同时按C语言格式生成源文件（见第\ref{sec:backend}节）。
  它适用于插入C语言代码片段或函数定义。

  \oarg{选项}与\env{example}环境一致，其中\verb|backend|
  已被预置为\optcode{c}，通常无须再次指定。

  \env{ccode}环境实际上是通过为\env{example}环境预置
  \optcode{vmode}、\optcode{nonum}、\optcode{noshow}与
  \optcode{backend = c}选项实现的，即\env{example}环境加上这四个选项。

\begin{example}[vmode, noshow, nonum]{}
\begin{ccode}[filename = { hello.c }]{}
#include <stdio.h>

int main(void)
{
    printf("Hello, World!\n");
    return 0;
}
\end{ccode}
\end{example}

\begin{notezh}
  \env{ccode}环境的主体部分按原样写入\file{c}文件，因此
  \verb|cls|、\verb|pkg|等\LaTeX{}专属选项对它没有意义。若代码中需要
  \fakeverb{#include}等前置内容，可直接写入环境体，或写在环境的必选参数
  （导言区附加内容）中，二者都会出现在生成的源文件里；区别在于后者
  不会显示在代码框中，除非同时使用\verb|withextra|选项。
\end{notezh}

\subsection{\tn{codemweset}全局选项设置}

\begin{function}[added=2026-10-10]{\codemweset}
  \begin{syntax}
    \tn{codemweset}\marg{选项}
  \end{syntax}
\end{function}

  用于在当前作用域内修改后续\env{example}、\env{example*}、\env{texcode}和
  \env{ccode}环境的默认选项，\marg{选项}为逗号分隔的key-value列表。如：

\begin{texcode}
\codemweset{ vmode, withpkg }
\end{texcode}

\subsection{\tn{codemweNewBox}注册新盒子}

\begin{function}[added=2026-10-10]{\codemweNewBox}
  \begin{syntax}
    \tn{codemweNewBox}\marg{盒子环境名}\oarg{选项}
  \end{syntax}
\end{function}

  用于向\pkg{codemwe}注册一个新的盒子环境，
  注册后即可通过\verb|boxtype|选项使用该盒子排版代码框和结果框。

  \marg{盒子环境名}必须符合``\verb|O{背景色} d() O{额外选项}|''
  形式的参数接口，建议用\pkg{tcolorbox}的\tn{DeclareTColorBox}命令
  定义。\oarg{选项}中目前只支持\verb|withtitle|，用于声明该
  盒子是否支持标题栏，其初始值与默认值均为\verb|true|。如：

\begin{texcode}
\codemweNewBox{ mybox }[ withtitle = true ]
\end{texcode}

  \begin{notezh}
    宏包内部维护了一张“盒子环境名称 $\to$ 是否支持标题栏”的属性表，
    6个内置盒子已预先注册。\tn{codemweNewBox}只登记属性，
    它无法实现环境本身的定义，因此须先用\tn{DeclareTColorBox}
    （或等价方式，如\tn{NewDocumentEnvironment}）定义\marg{盒子环境名}，
    再调用本命令实现注册。

    如果使用了与内置盒子环境名称同名的盒子，则会覆盖内置盒子的设置。
  \end{notezh}

\changes{v1.0.0}{2026/10/13}{ add \tn{codemweNewLang}.}

\subsection{\tn{codemweNewLang}注册新语种}

\begin{function}[added=2026-10-13]{\codemweNewLang}
  \begin{syntax}
    \tn{codemweNewLang}\marg{语种名称}\marg{8段内容}
  \end{syntax}
\end{function}

  用于向\pkg{codemwe}注册一种新的语种，设置该语种对应的过渡语、注释词等文本，
  注册后即可通过\verb|textlang|选项使用该新语种排版过渡语、添加的注释内容等。

  \marg{语种名称}是新语种的名称。
  \marg{8段内容}由8段逗号分隔的文本构成（前过渡语, 后过渡语,
  无编号过渡语, 文档类注释词, 导言区注释词, 正文区词,
  默认文档类名称, 标题及\tn{ref}引用结果引导词）。如：

\begin{texcode}
\codemweNewLang{ fr }
  {
    Le~résultat~de,
    est~affiché~ci-dessous.,
    Le~résultat~du~code~est~affiché~ci-dessous.,
    classe~de~document,
    préambule,
    corps,
    article,
    exemple
  }
\end{texcode}

  宏包内置了\verb|en|（英文）和\verb|zh|（中文）两个语种。
  如果\tn{codemweNewLang}定义的语种名称与内置名称重名，则会覆盖
  内置语种文本内容。

\begin{notezh}
  \marg{8段内容}各段内容中如有逗号则需要用大括号进行保护，
  空白字段需要留白，不能省略。
\end{notezh}

\subsection{\tn{codemweNewBackend}注册新代码后端}

\begin{function}[added=2026-10-20,updated=2026-10-23]{\codemweNewBackend}
  \begin{syntax}
    \tn{codemweNewBackend}\marg{后端名称}\marg{文件扩展名}\marg{注释符}\marg{能否编译}\oarg{\pkg{minted}语言名}
  \end{syntax}
\end{function}

  用于向\pkg{codemwe}注册一种新的代码后端（源语言），注册后即可通过
  \verb|backend|选项使用该后端排版代码、生成对应格式的源文件。

  \marg{后端名称}是新后端的名称，也是\verb|backend|选项的取值。
  \marg{文件扩展名}（不含点号），如\optcode{c}、\optcode{py}。
  \marg{注释符}按原样读取，用于源文件的首行注释，如百分号、
  \verb|//|或\verb|#|号，均无须转义。
  \marg{能否编译}取\optcode{true}时，源文件按\LaTeX{}文档编译并在结果框中
  显示结果；取\optcode{false}时，不对其按\LaTeX{}编译，结果框只能显示由
  \verb|result|选项指定的图片。
  \oarg{\pkg{minted}语言名}是可选参数，给出该语言在\pkg{minted}宏包中
  对应的语言名（即\pkg{pygments}的 lexer 名），用于\verb|minted|选项
  下的语法高亮，如\optcode{python}、\optcode{javascript}。省略或留空时
  默认为\marg{后端名称}本身。若不使用\verb|minted|选项，该参数不影响
  任何排版效果。

\begin{texcode}
\codemweNewBackend { python } { py } { # } { false }
\end{texcode}

  若该后端也要用于语法高亮，可使用可选项给出语言名：

\begin{texcode}
\codemweNewBackend { py } { py } { # } { false } [ python ]
\end{texcode}

  宏包内置了\optcode{tex}（默认）和\optcode{c}两种后端。
  如果\tn{codemweNewBackend}注册的后端名称与内置名称重名，则会覆盖
  内置后端的设置。

\section{排版模式}\label{sec:mode}

\subsection{水平模式}

水平模式为默认模式，左侧为代码框，右侧为结果框，适合代码与结果
对比阅读。水平模式下的宽度分配规则为：若未指定\verb|width|，
则减去左右框之间的间距\verb|sep|后，按剩余宽度的$1/2$等宽排版
左右两栏。如：
\begin{texcode}
\begin{example}{}
\ExplSyntaxOn
\tl_clear_new:N \l__fsttest_tl
\tl_set:Nn \l__fsttest_tl
  { 猫儿喜欢鱼 }
\tl_use:N \l__fsttest_tl
\ExplSyntaxOff
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}{}
\ExplSyntaxOn
\tl_clear_new:N \l__fsttest_tl
\tl_set:Nn \l__fsttest_tl
  { 猫儿喜欢鱼 }
\tl_use:N \l__fsttest_tl
\ExplSyntaxOff
\end{example}

\subsection{垂直模式}

垂直模式下，上方为代码框，下方为结果框，中间可插入过渡文字。
通过\verb|vmode|选项实现模式切换。如：

\begin{texcode}
\begin{example}[vmode]{}
\ExplSyntaxOn
\tl_clear_new:N \l__sectest_tl
\tl_set:Nn \l__sectest_tl { 猫儿喜欢鱼 }
\tl_use:N \l__sectest_tl
\ExplSyntaxOff
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[vmode]{}
\ExplSyntaxOn
\tl_clear_new:N \l__sectest_tl
\tl_set:Nn \l__sectest_tl { 猫儿喜欢鱼 }
\tl_use:N \l__sectest_tl
\ExplSyntaxOff
\end{example}

垂直模式下，代码框与结果框之间的过渡文字取自\optcode{textlang}
选项所选语种对应的\textbf{默认过渡语}（见第\ref{sec:opts}节的选项说明）。
本手册的导言区已用\tn{codemweset}把语种设为中文，因此上例中
出现的过渡文字为“以下是\ref{ex:2}编译后得到的结果。”（其中引用标签
\verb|\ref{ex:2}|由宏包自动生成）；若使用了|nonum|选项，则为无编号过渡语
“以下是该代码编译后得到的结果。”。单个示例也可用\verb|transition|
选项另行指定过渡文字。

\subsection{自定义过渡文字}

使用\verb|transition|选项可以为单个示例自定义代码框与结果框之间的
过渡文字（它会覆盖\optcode{textlang}所选语种给出的默认过渡语）。如：

\begin{texcode}
\begin{example}[
  vmode,
  pkg        = { tikz },
  title      = { 自定义过渡文字 },
  transition = { 下面是本例的排版结果，请核对代码与输出是否一致： },
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
  \draw (1, 1) -- (2, 0);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[
  vmode,
  pkg        = { tikz },
  title      = { 自定义过渡文字 },
  transition = { 下面是本例的排版结果，请核对代码与输出是否一致： },
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
  \draw (1, 1) -- (2, 0);
\end{tikzpicture}
\end{example}

\subsection{水平模式下的间距控制}

水平模式下，\verb|sep|选项控制左代码框与右结果框之间的间距，默认\optcode{18pt}，如：
下面的示例把间距设置为\fakeverb{0.2\textwidth}：

\begin{texcode}
\begin{example}[
  pkg   = { tikz },
  sep   = { 0.2\textwidth },
  title = { 水平间距加大 },
]{}
\begin{tikzpicture}
  \draw (0, 0) circle (1);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[
  pkg   = { tikz },
  sep   = { 0.2\textwidth },
  title = { 水平间距加大 },
]{}
\begin{tikzpicture}
  \draw (0, 0) circle (1);
\end{tikzpicture}
\end{example}

\subsection{代码框宽度控制}

\verb|width|选项控制代码框的宽度。未指定时，水平模式按左右均分，
垂直模式取\tn{textwidth}。下面的示例把代码框宽度设置为
\fakeverb{0.35\textwidth}：

\begin{texcode}
\begin{example}[
  pkg   = { tikz },
  width = 0.35\textwidth,
  title = { 指定代码框宽度 },
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (5, 1);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
其排版结果为：

\begin{example}[
  pkg   = { tikz },
  width = 0.35\textwidth,
  title = { 指定代码框宽度 },
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (5, 1);
\end{tikzpicture}
\end{example}

\verb|width|与\verb|sep|等长度选项应使用\LaTeX{}的长度表达方式（如
\optcode{0.35\textwidth}、\optcode{4cm}）。若写成\optcode{width = 0.35}
这样的纯小数，\TeX{}会补上默认单位\optcode{pt}，即被解释为
\optcode{0.35pt}，代码框会被压缩成一条细线。

\section{编号与引用}

默认情况下，每个\env{example}环境都会编号，如有\tn{chapter}命令(\pkg{book}，\pkg{report}等文档类)，
则编号格式为“章号.编号”， 如无\tn{chapter}命令(\pkg{article}等文档类)，则编号格式为“编号”。
并在代码框首行添加该编号的注释行：

\begin{texcode}
% 例 1.3 绘制直线
\end{texcode}

同时每个\env{example}环境都会自动生成引用标签（如\verb|\label{ex:1-3}|），
可用\verb|\ref{ex:1-3}|引用，显示为“例 1.3”。若使用\verb|label|选项自定义
引用标签，则\tn{ref}按自定义标签解析。如：

\begin{texcode}
\begin{example}[
  pkg   = { tikz },
  label = { code:drawline-zh },
  title = { 绘制直线 },
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[
  pkg   = { tikz },
  label = { code:drawline-zh },
  title = { 绘制直线 },
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
\end{tikzpicture}
\end{example}

\ref{code:drawline-zh}是用

\begin{quote}
\verb|label = { code:drawline-zh }|
\end{quote}

\noindent 选项自定义引用标签后，用\verb|\ref{code:drawline-zh}|引用的效果。

若不需编号，可使用\verb|nonum|（\verb|nonum=true|）选项进行设置：
此时不占用计数器，也不生成标签，但代码框与结果框仍正常排版。如：

\begin{texcode}
\begin{example}[
  pkg = { tikz },
  nonum,
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[
  pkg = { tikz },
  nonum,
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
\end{tikzpicture}
\end{example}

\section{仅显示代码}

若只需代码框，不要结果框，可以使用\verb|noshow|（\verb|noshow=true|）选项。

\begin{texcode}
\begin{example}[noshow]{}
  ...
\end{example}
\end{texcode}

此时代码框正常排版，结果框及其过渡文字均不输出，但不影响编号与
引用标签。如：

\begin{texcode}
\begin{example}[ noshow, vmode, pkg = { tikz } ]{}
\begin{tikzpicture}
  \draw (0, 0) cos (2, 1);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[ noshow, vmode, pkg = { tikz } ]{}
\begin{tikzpicture}
  \draw (0, 0) cos (2, 1);
\end{tikzpicture}
\end{example}

\section{结果图片}

若示例代码无法直接编译，则可用\verb|result|选项指定图片文件，
用图片代替编译结果：

\begin{notezh}
  使用结果图片时，结果框不再使用指定的背景框，而是使用简单的
  单线外框进行包围后输出插图。
\end{notezh}

\begin{texcode}
\begin{example}[ result = fig/sine.pdf, scale = 0.8 ]{}
  ...
\end{example}
\end{texcode}

\verb|scale=0.8|表示按原尺寸的80\%插入；若需按宽度或高度插入，
可改用\verb|wd|或\verb|ht|选项。如：

\begin{texcode}
\begin{example}[
  pkg    = { tikz },
  result = sine.pdf,
  scale  = 0.8,
]{}
\begin{tikzpicture}
  \draw (0, 0) sin (2, 1);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[
  pkg    = { tikz },
  result = sine.pdf,
  scale  = 0.8,
]{}
\begin{tikzpicture}
  \draw (0, 0) sin (2, 1);
\end{tikzpicture}
\end{example}

\subsection{结果图片的宽度与高度控制}

\verb|wd|用于把结果图片按指定宽度排版，例如\verb|wd=0.2\textwidth|：

\begin{texcode}
\begin{example}[
  pkg    = { tikz },
  result = sine.pdf,
  wd     = 0.2\textwidth,
]{}
\begin{tikzpicture}
  \draw (0, 0) sin (2, 1);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[
  pkg    = { tikz },
  result = sine.pdf,
  wd     = 0.2\textwidth,
]{}
\begin{tikzpicture}
  \draw (0, 0) sin (2, 1);
\end{tikzpicture}
\end{example}

\verb|ht|用于把结果图片按指定高度排版，例如\verb|ht=1cm|：

\begin{texcode}
\begin{example}[
  pkg    = { tikz },
  result = sine.pdf,
  ht     = 1cm,
]{}
\begin{tikzpicture}
  \draw (0, 0) sin (2, 1);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[
  pkg    = { tikz },
  result = sine.pdf,
  ht     = 1cm,
]{}
\begin{tikzpicture}
  \draw (0, 0) sin (2, 1);
\end{tikzpicture}
\end{example}

\begin{notezh}
  当\verb|wd|被指定后，\verb|ht|与\verb|scale|都被忽略；
  当只指定\verb|ht|时，\verb|scale|被忽略。
\end{notezh}

\section{输出前置内容}

可以通过\verb|withcls|、\verb|withpkg|、\verb|withextra|、\verb|nobody|
等逻辑选项的不同组合，实现是否在示例代码框中输出文档类及其选项、宏包及其选项、
导言区额外内容等。如果使用了\verb|noshow|或\verb|nobody|选项，
则这些内容会原样输出；否则将会给\verb|cls|和\verb|pkg|的内容添加注释符号|%|后输出。

下面的示例综合使用了\verb|withcls|、\verb|withpkg|、\verb|withextra|
和\verb|nobody|选项，可以看到代码框中原样输出了文档类、前置内容（导言区内容），
但不输出环境体（\verb|nobody|），也不输出编译结果：

\begin{texcode}
\begin{example}[
  cls       = { article = { 12pt, a4paper } },
  pkg       = { tikz, xcolor = { svgnames } },
  title     = { 绘制直线 },
  pretitle  = { 样例 },
  width     = { 0.8\textwidth },
  vmode,
  nonum,
  withcls,
  withpkg,
  withextra,
  nobody,
]{
\newcommand{\mya}{a}
\newcommand{\myb}{b}
}
\begin{tikzpicture}
  \draw (0, 0) node[below] { \mya } -- (1, 1) node[above] { \myb };
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[
  cls       = { article = { 12pt, a4paper } },
  pkg       = { tikz, xcolor = { svgnames } },
  title     = { 绘制直线 },
  pretitle  = { 样例 },
  width     = { 0.8\textwidth },
  vmode,
  nonum,
  withcls,
  withpkg,
  withextra,
  nobody,
]{
\newcommand{\mya}{a}
\newcommand{\myb}{b}
}
\begin{tikzpicture}
  \draw (0, 0) node[below] { \mya } -- (1, 1) node[above] { \myb };
\end{tikzpicture}
\end{example}

\section{代码后端}\label{sec:backend}

\pkg{codemwe}默认排版\LaTeX{}示例代码：宏包把代码框中的内容写入
临时文件\file{.aux}文件，并以\tn{input}命令将其读入结果框编译，
从而得到结果。这一机制依赖于被排版的代码本身就是\LaTeX{}代码。

为排版C语言等其他语言的代码，宏包引入了“代码后端”（backend）
的概念，用\verb|backend|选项选择。一个后端登记了以下四项信息：
源文件扩展名、首行注释所用的注释符、该语言代码能否被\LaTeX{}
编译、以及该语言在\pkg{minted}宏包中对应的语言名。宏包内置了
两个后端，如表~\ref{tab:backend}所示。

\begin{table}[htbp]
  \centering
  \caption{内置的代码后端}
  \label{tab:backend}
  \begin{tabular}{ccccc}
    \toprule
    后端 & 扩展名 & 注释符 & 能否编译 & \pkg{minted}语言名 \\
    \midrule
    \optcode{tex} & \file{tex} & \texttt{\char37} & 是 & \optcode{tex} \\
    \optcode{c}   & \file{c}   & \optcode{//} & 否 & \optcode{c} \\
    \bottomrule
  \end{tabular}
\end{table}

最后一列仅在使用\verb|minted|选项（见第~\ref{sec:minted}节）时
才会用到；不使用\pkg{minted}时该列内容不影响排版。

\verb|backend = c|时的排版行为如下：

\begin{enumerate}[itemsep=0.3ex]
  \item 生成的源文件不是\LaTeX{}文档，而是可直接交给C编译器处理的
        纯C源文件：首行为注释（如\optcode{// 例 2.2 两数之和}），
        其后为环境必选参数给出的前置内容与代码框中的代码；
  \item 代码框中的注释行使用C语言的注释符|//|，且不会添加
        “文档类”“导言区”“正文区”等\LaTeX{}专有的结构注释；
  \item \verb|cls|、\verb|pkg|及\verb|withcls|、\verb|withpkg|等
        选项对C代码没有意义，因此被忽略；
  \item 由于C代码不能被\LaTeX{}编译，宏包不在排版过程中编译它。
        若给出了\verb|result|选项，结果框显示指定的图片；
        若未给出，则结果框整体省略，并给出\optcode{backend-no-result}
        警告。
\end{enumerate}

如，可以用以下代码排版一个C函数，并以插图作为结果。

\begin{texcode}
\begin{example}[
  backend  = c,
  title    = { 两数之和 },
  result   = { csum.png },
  scale    = 0.3,
  filename = { sum.c },
]{
#include <stdio.h>

int sum(int a, int b);

int main(void)
{
  int a, b;
  a = 3;
  b = 4;

  printf("sum=%d\n", sum(a, b));

  return 0;
}
}
int sum(int a, int b)
{
    return a + b;
}
\end{example}
\end{texcode}

\noindent
其排版结果为：

\begin{example}[
  backend  = c,
  title    = { 两数之和 },
  result   = { csum.png },
  scale    = 0.3,
  filename = { sum.c },
]{
#include <stdio.h>

int sum(int a, int b);

int main(void)
{
  int a, b;
  a = 3;
  b = 4;

  printf("sum=%d\n", sum(a, b));

  return 0;
}
}
int sum(int a, int b)
{
    return a + b;
}
\end{example}

其中，\verb|filename = { sum.c }|使源文件保存为\file{sum.c}，
其内容为：

\begin{texcode}
// 例 11 两数之和
#include <stdio.h>

int sum(int a, int b);

int main(void)
{
  int a, b;
  a = 3;
  b = 4;

  printf("sum=%d\n", sum(a, b));

  return 0;
}

int sum(int a, int b)
{
    return a + b;
}
\end{texcode}

若不关心源文件的名字，也可省略\verb|filename|，此时文件名由
\verb|dir|、\verb|prelabel|与编号自动构造，扩展名取当前后端的扩展名
（C语言为\file{c}），例如\file{codes/ex11.c}。

\begin{notezh}
  由于C语言代码不在排版时编译，结果框中的插图必须事先准备好，
  并与代码保持同步更新。若未指定\verb|result|选项，可用
  \verb|noshow|选项关闭结果框，以免出现警告；\env{ccode}环境
  已自动设置了\verb|noshow|。

  需要排版C语言之外的语言（如Python）时，只需用
  \tn{codemweNewBackend}注册一个新后端，再通过\verb|backend|
  选项使用它，无需修改宏包本身。
\end{notezh}

\section{显示行号}

可以通过使用\fakeverb{[linenos]}选项为代码框添加行号，如：

\begin{texcode}
\begin{example}[
  pkg   = { tikz },
  title = { 绘制直线 },
  linenos,
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[
  pkg   = { tikz },
  title = { 绘制直线 },
  linenos,
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
\end{tikzpicture}
\end{example}

\begin{notezh}
  通过\verb|withcls|、\verb|withpkg|、\verb|withextra|添加的内容及自动添加的注释
  等内容同样会计入行号。
\end{notezh}

\section{完整示例}

下面给出一个综合运用多种选项的完整示例。它使用\verb|article|文档类、
\verb|tikz|与\verb|xcolor|宏包，在导言区追加两个自定义命令，并采用
垂直模式、指定代码框宽度与自定义标题。如：

\begin{texcode}
\begin{example}[
  cls       = { article = { 12pt, a4paper } },
  pkg       = { tikz, xcolor = { svgnames } },
  title     = { 绘制直线 },
  label     = { code:multi-opts-zh },
  pretitle  = { 示例 },
  width     = { 0.55\textwidth },
  vmode,
  withextra,
]{
\newcommand{\myA}{A}
\newcommand{\myB}{B}
}
\begin{tikzpicture}
  \draw (0, 0) node[below] { \myA } -- (1, 1)
    node[above] { \myB };
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[
  cls       = { article = { 12pt, a4paper } },
  pkg       = { tikz, xcolor = { svgnames } },
  title     = { 绘制直线 },
  label     = { code:multi-opts-zh },
  pretitle  = { 示例 },
  width     = { 0.55\textwidth },
  vmode,
  withextra,
]{
\newcommand{\myA}{A}
\newcommand{\myB}{B}
}
\begin{tikzpicture}
  \draw (0, 0) node[below] { \myA } -- (1, 1)
    node[above] { \myB };
\end{tikzpicture}
\end{example}

\ref{code:multi-opts-zh}生成\file{codes/ex11.tex}文件的MWE \file{tex}文件，
其内容为：

\begin{texcode}
% 文档类
\documentclass[12pt,a4paper]{article}

% 导言区
\usepackage{tikz}
\usepackage[svgnames]{xcolor}

\newcommand{\myA}{A}
\newcommand{\myB}{B}

% 正文区
\begin{document}

\begin{tikzpicture}
  \draw (0, 0) node[below] { \myA } -- (1, 1) node[above] { \myB };
\end{tikzpicture}

\end{document}
\end{texcode}

\begin{notezh}
  如果需要在|title|选项设置的标题内容中包含类似\tn{tikzset}这样的命令，
  则需要使用\LaTeX{}的原命令\tn{string}实现，如\tn{string}\tn{tikzset}%
  用于输出\tn{tikzset}，以避免在写入注释时被展开。
\end{notezh}

\section{将环境体保存为文件}

如果仅需要将环境体保存到指定文件中，可以同时指定
\fakeverb{[nonum, filename=test.tex]}两个选项。此时对示例代码不进行编号，
但会将环境体保存在\verb|filename|选项指定的文件中，路径前缀仍使用
\verb|dir|选项指定的路径。

\begin{notezh}
  此时保存的文件不包含文档类、导言区、表示正文区开始的命令
  \fakeverb{\begin{document}}和表示正文区结束的命令
  \fakeverb{\end{document}}等内容，该文件无法独立进行编译。
\end{notezh}

如：

\begin{texcode}
\begin{example}[
  vmode,
  noshow,
  nonum,
  title    = { 定义用户接口 },
  filename = test.tex,
]{}
\ExplSyntaxOn
\tl_clear_new:N \l__test_tl
\tl_set:Nn \l__test_tl { 猫儿喜欢鱼 }
\newcommand{\mytest}{ % 定义用户接口
  \tl_use:N \l__test_tl
}
\ExplSyntaxOff
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[
  vmode,
  noshow,
  nonum,
  title    = { 定义用户接口 },
  filename = test.tex,
]{}
\ExplSyntaxOn
\tl_clear_new:N \l__test_tl
\tl_set:Nn \l__test_tl { 猫儿喜欢鱼 }
\newcommand{\mytest}{ % 定义用户接口
  \tl_use:N \l__test_tl
}
\ExplSyntaxOff
\end{example}

\section{语法高亮}\label{sec:minted}

默认情况下，代码框中的代码按原样排版，不做语法高亮。若对代码的
可读性有更高要求，可以为宏包或环境设置\verb|minted|选项，改用\pkg{minted}
宏包完成示例代码排版，从而得到带语法高亮的示例代码：

\begin{texcode}
\usepackage[minted]{codemwe}
\end{texcode}

未指定\verb|minted|选项时，宏包使用\pkg{fancyvrb}宏包排版示例代码；
指定该选项后，代码框中的内容改由\pkg{minted}排版，并统一采用\tn{small}字号、
自动去除公共缩进（\optcode{autogobble}）。
行号由\verb|linenos|选项控制，与不使用\pkg{minted}时一致。

\begin{notezh}
  \pkg{minted}需要调用外部程序（\optcode{latexminted}或\optcode{pygmentize}）
  完成高亮，因此必须以\optcode{-shell-escape}选项编译文档。若未开启
  shell escape 或未安装\pkg{minted}，宏包不会中止编译，而会发出一条
  \optcode{minted-unavailable}警告并回退到\pkg{fancyvrb}宏包排版方案，
  此时文档仍可正常生成，只是没有语法高亮。

  此外，\pkg{minted}默认采用\optcode{fasthighlightmode}：首遍编译时只在
  代码框中插入占位符，从第二遍起才显示出真正的高亮结果。因此启用
  \verb|minted|选项后需要编译两遍以上。
\end{notezh}

高亮所需的语言名不由\verb|minted|选项给出，而是由\verb|backend|选项
决定：每个代码后端都登记了对应的\pkg{minted}语言名（见
表~\ref{tab:backend}），排版时宏包自动取当前后端的语言名交给
\pkg{minted}。例如\verb|backend = c|时用\optcode{c}语法高亮，
\verb|backend = tex|时用\optcode{tex}语法高亮。

高亮样式由\verb|mintedstyle|选项设置，取值为\pkg{minted}（\pkg{pygments}）
支持的样式名，默认为\optcode{default}。如改用\optcode{tango}样式：

\begin{texcode}
\usepackage[minted, mintedstyle = tango]{codemwe}
\end{texcode}

可供选择的常用样式有\optcode{default}、\optcode{friendly}、
\optcode{tango}、\optcode{monokai}、\optcode{bw}等，完整列表见
\pkg{pygments}的样式文档。若只设置\verb|mintedstyle|而未启用
\verb|minted|，宏包会发出\optcode{mintedstyle-unused}警告，但仍会
记录该取值，以便日后启用\verb|minted|时生效。

\verb|minted|与\verb|mintedstyle|都可以作为宏包选项，也可以在
\tn{codemweset}或具体环境中给出，用法与其他选项相同，如：

\begin{texcode}
\begin{example}[
  minted,
  backend     = c,
  mintedstyle = friendly,
  result      = chelloworld.png,
  wd          = 0.45\textwidth,
  title       = { 语法高亮示例 },
]{}
#include <stdio.h>
int main(void)
{
    printf("Hello, world!\n");
    return 0;
}
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[
  minted,
  backend     = c,
  mintedstyle = friendly,
  result      = chelloworld.png,
  wd          = 0.45\textwidth,
  title       = { 语法高亮示例 },
]{}
#include <stdio.h>
int main(void)
{
    printf("Hello, world!\n");
    return 0;
}
\end{example}

\subsection{在正文中开关语法高亮}

\verb|minted|选项可以像其他布尔选项一样在正文中开关，从而只对个别
示例启用高亮：

\begin{texcode}
\codemweset{minted}          % 打开：其后所有示例都做语法高亮
\begin{example}{}
  ...
\end{example}
\begin{example}[minted = false]{}
  ...
\end{example}
\codemweset{minted = false}  % 关闭：恢复原有排版方案
\end{texcode}

\begin{notezh}
  \pkg{minted}宏包只能在导言区加载。本宏包在被读取时
  就已检查系统是否装有\pkg{minted}、编译是否用了\verb|-shell-escape|，
  条件满足便直接加载，因此正文中的\verb|minted|、\verb|minted = false|
  随时可用。\verb|minted = false|只是把高亮关掉，并不会卸载\pkg{minted}宏包，
  因此之后再打开无需重新加载。

  若缺\pkg{minted}宏包或未用\verb|-shell-escape|编译，加载便不会发生，
  此时一旦启用\verb|minted|选项，会发出\optcode{minted-unavailable}
  警告，代码按原有方案排版，不加语法高亮。
\end{notezh}

\begin{notezh}
  结果框的用途是把示例代码真正编译运行一遍并显示其效果，因此结果框中
  的代码始终按原样读入编译，不做语法高亮；只有代码框中的代码才会被
  \pkg{minted}高亮。对\optcode{c}这类不能被\LaTeX 编译的后端，
  结果框本就只在给出\verb|result|选项时才显示，与此无关。
\end{notezh}

\section{宏包选项}

宏包支持通过\tn{usepackage}"[选项]"\marg{codemwe}传入全局默认选项，
这些选项会作为后续\env{example}、\env{example*}、\env{texcode}、
\env{ccode}环境的初值。可作为宏包选项传入的键有：
\verb|vmode|、\verb|nobody|、\verb|noshow|、\verb|nonum|、
\verb|withcls|、\verb|withpkg|、\verb|withextra|、\verb|cls|、
\verb|pkg|、\verb|width|、\verb|sep|、\verb|prelabel|、\verb|pretitle|、
\verb|dir|、\verb|counter|、\verb|boxtype|、\verb|textlang|、
\verb|backend|、\verb|linenos|、\verb|minted|和\verb|mintedstyle|。

宏包级选项设置的初值，可以在环境内部通过同名选项覆盖。如：

\begin{texcode}
\begin{example}[
  vmode = false,
  pkg   = { tikz },
  title = { 覆盖宏包级 vmode },
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1) -- (2, 0);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[
  vmode = false,
  pkg   = { tikz },
  title = { 覆盖宏包级 vmode },
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1) -- (2, 0);
\end{tikzpicture}
\end{example}

\section{未知选项与警告}

若传入未定义的键，宏包会发出一条\verb|unknown-key|警告，并忽略该选项。
例如编译下列示例时：

\begin{texcode}
\begin{example}[foo, pkg={tikz}]{}
  ...
\end{example}
\end{texcode}

\noindent
会得到：

\begin{texcode}
Package codemwe Warning:\\
Unknown key-val option 'foo' for package 'codemwe'.
\end{texcode}

\noindent
这样的警告，但并不会中止编译。

此外，与代码后端相关的两条警告为：

\begin{itemize}[itemsep=0.3ex]
  \item \optcode{unknown-backend}：\verb|backend|选项给定了未注册的后端名称，
        宏包回退到\optcode{tex}；
  \item \optcode{backend-no-result}：当前后端不可被\LaTeX 编译，
        又未给出\verb|result|选项，结果框被整体省略。补充\verb|result|
        插图或改用\verb|noshow|选项即可消除该警告。
\end{itemize}

与语法高亮相关的三条警告为：

\begin{itemize}[itemsep=0.3ex]
  \item \optcode{minted-unavailable}：启用了\optcode{minted}选项，但当前
        编译未开启 shell escape，或系统中没有\pkg{minted}宏包。此时宏包
        回退到原有排版方案，代码仍可正常排出，只是没有高亮；
  \item \optcode{mintedstyle-unused}：设置了\optcode{mintedstyle}却没有
        启用\optcode{minted}选项，该样式暂不生效；
  \item \optcode{minted-no-lexer}、\optcode{minted-unknown-lexer}：
        当前后端没有登记\pkg{minted}语言名，或者登记的语言名不被
        \pkg{pygments}识别。
\end{itemize}

\section{盒子类型}

\verb|boxtype|选项用于指定代码框和结果框所使用的盒子环境，其默认值为
\env{syntaxbox}。宏包内置了6个盒子环境，详见表~\ref{tab:codemwe-boxtype}。
其中带星号的三个盒子是各自不带星号盒子的“白底无边框”变体；
而\env{mwebox}/\env{mwebox*}与\env{mweparbox}/\env{mweparbox*}
支持标题栏，示例编号与标题会自动成为盒子标题栏的内容，
\env{syntaxbox}/\env{syntaxbox*}不支持标题栏，
此时编号与标题以首行注释的形式写在代码框内。

\begin{table}[!htbp]
  \centering
  \caption{内置盒子类型}
  \label{tab:codemwe-boxtype}
  \begin{tabular}{llccc}
    \toprule
    \textbf{类型} & \textbf{背景色} & \textbf{边框} & \textbf{标题栏} & \textbf{宏包依赖}\\
    \midrule
    \env{syntaxbox}  & \verb|gray!12| & 无       & 无 & \pkg{tcolorbox}\\
    \env{syntaxbox*} & \verb|white|   & 无       & 无 & \pkg{tcolorbox}\\
    \env{mwebox}     & \verb|cyan|    & 无       & 有 & \pkg{tcolorbox}\\
    \env{mwebox*}    & \verb|cyan|    & 有       & 有 & \pkg{tcolorbox}\\
    \env{mweparbox}  & \verb|purple|  & 左竖边框 & 有 & \pkg{tcolorbox}\\
    \env{mweparbox*} & \verb|white|   & 左竖边框 & 有 & \pkg{tcolorbox}\\
    \bottomrule
  \end{tabular}
\end{table}

如：

\begin{texcode}
\begin{example}[ boxtype = mwebox, label = { code:mwebox-zh }, pkg = { tikz } ]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
\end{tikzpicture}
\end{example}
\end{texcode}

\ref{code:mwebox-zh}是采用\env{mwebox}盒子排版的结果。

\begin{example}[ boxtype = mwebox, label = { code:mwebox-zh }, pkg = { tikz } ]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
\end{tikzpicture}
\end{example}

可以使用\tn{codemweNewBox}命令注册用户自定义的盒子。要求自定义盒子环境的
参数接口符合``\verb|O{背景色} d() O{额外选项}|''的要求，即第一个可选参数
\verb|[]|给出背景色、第二个可选参数\verb|()|给出标题、第三个可选参数
\verb|[]|给出额外的\pkg{tcolorbox}选项，就能被\verb|boxtype|使用。
例如，可以用\pkg{tcolorbox}宏包的\tn{DeclareTColorBox}命令定义这样一个盒子：

\begin{texcode}
% 定义 tcolorbox 盒子（接口与内置盒子一致）
\DeclareTColorBox{ mybox }{ O{ green!30 } d() O{  } }
  {
    colback  = #1,
    colframe = #1,
    boxrule  = 0pt,
    arc      = 4mm,
    left     = 8pt,
    right    = 8pt,
    top      = 4pt,
    bottom   = 4pt,
    nobeforeafter,
    IfValueT = { #2 } { title = #2, coltitle = green!30!black },
    #3,
  }
\end{texcode}

因为该盒子会使用\verb|()|参数生成标题栏，所以注册时应声明
\optcode{withtitle = true}（这也是其默认值）。

\begin{texcode}
% 注册排版盒子
\codemweNewBox{ mybox }[ withtitle = true ]
\end{texcode}

\begin{notezh}
  若自定义盒子支持标题栏，\tn{codemweNewBox}的\optcode{withtitle}
  必须为\optcode{true}；反之若盒子不支持标题栏，则应声明
  \optcode{withtitle = false}。若声明与实际不符，编号与标题
  有可能被丢失或重复输出。
\end{notezh}

下面用\env{mybox}排版一个示例（为便于阅读，这里直接用\tn{DeclareTColorBox}
命令定义盒子，效果与上面\tn{codemweNewBox}注册后完全一致）：

\DeclareTColorBox{ mybox }{ O{ green!30 } d() O{  } }
  {
    colback  = #1,
    colframe = #1,
    boxrule  = 0pt,
    arc      = 4mm,
    left     = 8pt,
    right    = 8pt,
    top      = 4pt,
    bottom   = 4pt,
    nobeforeafter,
    IfValueT = { #2 } { title = #2, coltitle = green!30!black },
    #3,
  }
\codemweNewBox{ mybox }[ withtitle = true ]

如：

\begin{texcode}
\begin{example}[
  pkg     = { tikz },
  title   = { 自定义盒子 },
  boxtype = mybox,
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1) -- (2, 0);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
的排版结果为：

\begin{example}[
  pkg     = { tikz },
  title   = { 自定义盒子 },
  boxtype = mybox,
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1) -- (2, 0);
\end{tikzpicture}
\end{example}

\section{选项说明}\label{sec:opts}

以下是\pkg{codemwe}宏包设置的全部key-value选项。
其中“初始值”是选项在宏包或环境未作任何设置时的取值，
“默认值”是该布尔选项写成不带值的简写形式（如\optcode{vmode}）时的取值。

\begin{option}{ opt = vmode, desc = {= \meta{true/false}}, init=false }
  排版模式。\optcode{vmode = false}为水平模式，\optcode{vmode = true}
  为垂直模式；布尔值\optcode{= true}可省略，仅写\optcode{vmode}
  即表示\optcode{vmode = true}。初始值为\optcode{false}。
\end{option}

\begin{option}{ opt = noshow, desc = {= \meta{true/false}}, init=false }
  是否显示结果框。使用\optcode{noshow}则仅显示代码框，结果框及其过渡
  文字均不输出。初始值为\optcode{false}。
\end{option}

\begin{option}{ opt = nonum, desc = {= \meta{true/false}}, init=false }
  是否编号并生成标签。使用\optcode{nonum}关闭编号，此时不占用计数器，
  也不生成标签，但代码框与结果框仍正常排版。初始值为\optcode{false}。
\end{option}

\begin{option}{ opt = nobody, desc = {= \meta{true/false}}, init=false }
  是否输出\env{example}环境体。使用\optcode{nobody}时不输出环境体，
  同时也就不输出编译结果（相当于同时使用了\optcode{noshow}选项）。
  初始值为\optcode{false}。
\end{option}

\begin{option}{ opt = withcls, desc = {= \meta{true/false}}, init=false }
  在示例代码框中是否加入\optcode{cls}列出的文档类内容。如果使用了
  \optcode{noshow}或\optcode{nobody}选项，则把\optcode{cls}的内容
  原样输出；否则在其前面加上注释符号\verb|\%|后输出。初始值为
  \optcode{false}。
\end{option}

\begin{option}{ opt = withpkg, desc = {= \meta{true/false}}, init=false }
  在示例代码框中是否加入\optcode{pkg}列出的宏包内容。如果使用了
  \optcode{noshow}或\optcode{nobody}选项，则把\optcode{pkg}的内容
  原样输出；否则为其中的每个宏包加上注释符号\verb|\%|后输出。初始值为
  \optcode{false}。
\end{option}

\begin{option}{ opt = withextra, desc = {= \meta{true/false}}, init=false }
  在示例代码框中是否加入\env{example}必选参数给出的导言区额外内容。
  初始值为\optcode{false}。
\end{option}

\begin{option}{ opt = cls, desc = {= \meta{文档类}}, init=ctexart }
  MWE \file{tex}文件所需的文档类。既支持不带选项的
  \optcode{cls = { article }}形式，也支持通过\optcode{=}指定文档类
  选项的\optcode{cls = { article = { 12pt, a4paper } }}形式，后者会在
  MWE \file{tex}文件开头生成\tn{documentclass}|[12pt,a4paper]\{article\}|。
  初始值为\optcode{ctexart}。
\end{option}

\begin{option}{ opt = pkg, desc = {= \meta{宏包列表}}, init=none }
  MWE \file{tex}文件所需的宏包列表。与\optcode{cls}类似，用逗号列表
  的方式给出需要添加的宏包，如
  \optcode{pkg = { tikz, tabularray, listings = { numbers = left } }}。
  初始值为空，即不添加任何宏包。
\end{option}

\begin{option}{ opt = width, desc = {= \meta{dim}}, init=0pt }
  代码框宽度。初始值为\optcode{0pt}，表示“未指定”：此时水平模式在
  扣除间距\optcode{sep}后按左右均分，垂直模式取\tn{textwidth}。
  在水平模式下，若该值过大导致右结果框宽度为负，会给出
  \optcode{width-too-large}警告。该值应写成\LaTeX{}长度，如
  \optcode{width = 0.35\textwidth}。
\end{option}

\begin{option}{ opt = sep, desc = {= \meta{dim}}, init=18pt }
  水平模式下，左代码框与右结果框的间距，初始值为\optcode{18pt}。
  该值应写成\LaTeX{}长度，如\optcode{sep = 0.1\textwidth}。
\end{option}

\begin{option}{ opt = prelabel, desc = {= \meta{前缀}}, init=ex }
  MWE 文件名与自动引用标签的前缀，初始值为\optcode{ex}。
  例如第\optcode{ex:1}个示例的\verb|label|默认为\optcode{ex:1}，
  对应的MWE文件名为\file{ex1.tex}。
\end{option}

\begin{option}{ opt = pretitle, desc = {= \meta{编号前缀}}, init=example }
  示例编号的引导词，用于代码框首行注释与\tn{ref}的显示内容，
  初始值为\optcode{example}。例如\verb|pretitle = { Example }|时，
  首行注释为“Example~1.1”，\tn{ref}也显示为“Example~1.1”。
  该值可含换行，换行会被转换为空格。中文排版时可设置为“例”、
  “示例”等内容。
\end{option}

\begin{option}{ opt = dir, desc = {= \meta{目录}}, init=codes }
  MWE 文件的保存目录，默认为当前目录下的\file{codes}文件夹。
  \textbf{指定的路径必须已存在}。
\end{option}

\begin{option}{ opt = counter, desc = {= \meta{计数器名}}, init=example }
  计数器名称，初始值为\optcode{example}。若指定的计数器名已被占用，
  会给出\optcode{counter-exists}警告并忽略该选项。由于在
  \tn{AtBeginDocument}时按该名称创建计数器，因此通常不需修改此项。
\end{option}

\begin{option}{ opt = boxtype, desc = {= \meta{盒子环境名}}, init=syntaxbox }
  指定代码框和结果框所使用的盒子环境，初始值为\env{syntaxbox}。
  内置盒子见表~\ref{tab:codemwe-boxtype}。
  若指定的盒子未被注册，会给出\optcode{unknown-boxtype}
  警告并回退到\env{syntaxbox}。
\end{option}

\begin{option}{ opt = textlang, desc = {= \meta{语种名称}}, init=en }
  选择语种。\pkg{codemwe}宏包按语种给出默认过渡语、MWE 文件中
  “文档类/导言区/正文区”三个结构注释词，以及\optcode{cls}与
  \optcode{pretitle}的默认取值，\optcode{textlang}选项用于选择使用
  哪一套。其取值为语种名称，初始值为\optcode{en}（英文）。

  宏包内置了\optcode{en}（英文）和\optcode{zh}（中文）两个语种。
  若指定的语种未注册，会给出\optcode{unknown-textlang}
  警告并回退到\optcode{en}。切换语种通常在导言区或文档开头用
  \tn{codemweset} 完成，如\fakeverb{\codemweset\{ textlang = zh \}}。
  单次示例仍可用\optcode{transition}选项单独覆盖过渡语。

  注册新语种用\tn{codemweNewLang}命令，见第\ref{sec:iface}节。
\end{option}

\begin{option}{ opt = backend, desc = {= \meta{后端名称}}, init=tex }
  选择代码后端，即被排版代码所属的语言。后端决定生成源文件的
  扩展名、首行注释所用的注释符，以及该语言代码能否被\LaTeX 编译。
  其取值为后端名称，初始值为\optcode{tex}（\LaTeX 示例代码）。

  宏包内置了\optcode{tex}和\optcode{c}（C语言）两种后端。
  选\optcode{c}时，宏包生成\file{c}源文件，代码框首行注释改用|//|，
  且不编译代码：若给出了\optcode{result}选项则显示该图片，否则
  省略结果框并给出\optcode{backend-no-result}警告。若指定的后端未注册，
  会给出\optcode{unknown-backend}警告并回退到\optcode{tex}。

  注册新后端用\tn{codemweNewBackend}命令，见第\ref{sec:iface}节；
  后端机制的详细说明见第\ref{sec:backend}节。
\end{option}

\begin{option}{ opt = minted, desc = {= \meta{true/false}}, init=false }
  是否改用\pkg{minted}宏包排版代码框，从而获得语法高亮。使用
  \optcode{minted}时，代码框中的代码由\pkg{minted}按当前后端登记的
  语言名高亮，并统一采用\tn{small}字号、自动去除公共缩进
  （\optcode{autogobble}）；行号仍由\optcode{linenos}选项控制。
  初始值为\optcode{false}，即沿用原有的\pkg{fancyvrb}排版方案，
  不做语法高亮。

  作为宏包选项给出时，全文所有示例都做语法高亮；作为环境选项给出时，
  只对当前示例启用，环境结束即恢复；用\tn{codemweset}给出时，对其后
  的所有示例生效，直到再次用\tn{codemweset}改回。因此
  \optcode{minted = false}既可关闭宏包级的高亮，也可在正文中随时关掉
  某一处的高亮。

  该选项需要\pkg{minted}宏包并以\optcode{-shell-escape}编译文档。
  本宏包在加载时即检查这两个条件，满足便直接加载\pkg{minted}，
  所以选项在任何位置（导言区、正文、环境）都能立即生效，无需先在
  导言区预置一次。若条件不满足，宏包会给出\optcode{minted-unavailable}
  警告并自动回退到原有方案，不会中止编译。此外，\pkg{minted}默认首遍
  只插入占位符，故启用本选项后需编译两遍以上才能看到高亮结果。

  详细说明见第~\ref{sec:minted}节。
\end{option}

\begin{option}{ opt = mintedstyle, desc = {= \meta{样式名}}, init=default }
  \pkg{minted}的语法高亮样式名，即\pkg{pygments}的 style 名，
  初始值为\optcode{default}。常用取值有\optcode{tango}、
  \optcode{friendly}、\optcode{monokai}、\optcode{bw}等。

  该选项只在启用\optcode{minted}时起作用。若设置了本选项而未启用
  \optcode{minted}，宏包会给出\optcode{mintedstyle-unused}警告，
  但仍记录该取值，以备日后启用\optcode{minted}时生效。
\end{option}

\begin{option}{ opt = title, desc = {= \meta{标题}}, init=none }
  示例的功能标题，如“绘制直线”，初始值为空。该标题在代码框支持
  标题栏时成为盒子的标题栏，否则成为代码框首行注释的一部分。
  若需要在\optcode{title}中包含类似\tn{tikzset}这样的命令，则需要
  使用\tn{string}原语，即\tn{string}\tn{tikzset}。
\end{option}

\begin{option}{ opt = label, desc = {= \meta{标签名}}, init=none }
  该示例的交叉引用标签。未指定时自动生成\meta{prelabel}|:|\meta{章号-编号}
  （支持\tn{chapter}的文档类，如\optcode{ex:8-1}）或
  \meta{prelabel}|:|\meta{编号}（不支持\tn{chapter}的文档类，
  如\optcode{ex:1}）。
\end{option}

\begin{option}{ opt = filename, desc = {= \meta{文件名}}, init=none }
  MWE 文件名。未指定时自动生成
  \meta{prelabel}\meta{章号-编号}|.tex|（支持\tn{chapter}的文档类，
  如\file{ex8-1.tex}）或\meta{prelabel}\meta{编号}|.tex|
  （不支持\tn{chapter}的文档类，如\file{ex1.tex}）。
  若同时使用\optcode{nonum}选项，则只把环境体保存到该文件中。
\end{option}

\begin{option}{ opt = result, desc = {= \meta{图片文件名}}, init=none }
  结果图片文件名。指定后，用该图片代替示例代码的编译结果，不再编译
  示例代码。文件名中可以包含路径（路径分隔符用\optcode{/}）。
  若文件不存在，会给出\optcode{result-file-missing}警告，但不会
  中止编译。
\end{option}

\begin{option}{ opt = wd, desc = {= \meta{dim}}, init=0pt }
  结果图片宽度。初始值为\optcode{0pt}，表示“未指定”。始终优先于
  \optcode{ht}与\optcode{scale}：只要指定了\optcode{wd}，这两个选项
  都被忽略。
\end{option}

\begin{option}{ opt = ht, desc = {= \meta{dim}}, init=0pt }
  结果图片高度。初始值为\optcode{0pt}，表示“未指定”。优先于
  \optcode{scale}：在未指定\optcode{wd}而指定了\optcode{ht}时，
  \optcode{scale}被忽略。
\end{option}

\begin{option}{ opt = scale, desc = {= \meta{比例}}, init=1 }
  结果图片的缩放比例，初始值为\optcode{1}。只有在\optcode{wd}和
  \optcode{ht}均未指定时有效。
\end{option}

\begin{option}{ opt = transition, desc = {= \meta{过渡文字}}, init=none }
  为当前这一个示例单独指定垂直模式下代码框与结果框之间的
  过渡文字，初始值为空。留空时改用\optcode{textlang}所选语种给出的全局
  默认过渡语。它可以含\tn{ref}等命令，例如
  \fakeverb{transition = \{ 下面是 \tn{ref}\{ ex:1 \} 的结果： \}}。
\end{option}

\begin{option}{ opt = linenos, desc = {= \meta{true/false}}, init=false }
  是否在代码框左侧显示行号。使用\optcode{linenos}时，代码框的每一行
  前会加上行号，行号与代码之间留有\optcode{6pt}的间距；不加该选项时
  不显示行号。初始值为\optcode{false}。

  行号由\pkg{fancyvrb}宏包的\tn{VerbatimInput}命令的
  \optcode{numbers=left}选项实现，编号从代码框的第一行起算，
  与示例自身的编号无关；使用\optcode{withcls}或\optcode{withpkg}
  时，被加入的文档类与宏包内容同样计入行号。
\end{option}

\begin{notezh}
  \optcode{textlang}决定整篇文档使用的\textbf{默认过渡语}及各语种相关
  文本（可用\tn{codemweset}或宏包选项设置，适合切换文档语种），
  \optcode{transition}为单个示例的局部覆盖。可根据需要进行设置。
\end{notezh}

\section{注意事项}

\begin{enumerate}[itemsep=0.3ex]
  \item 只有在未使用\verb|noshow|和\verb|nobody|选项时，代码框中的
        \verb|cls|与\verb|pkg|内容才会被自动添加注释符号|%|。
  \item 水平模式下，若\verb|width|过大，使右结果框宽度为负，
        会给出\verb|width-too-large|警告，此时应减小\verb|width|
        或\verb|sep|。
  \item \verb|boxtype|指定的盒子必须已注册（内置或通过
        \tn{codemweNewBox}注册），否则会给出\verb|unknown-boxtype|
        警告并回退到\env{syntaxbox}。
  \item \verb|counter|选项指定的计数器若已存在，会给出
        \verb|counter-exists|警告并忽略该选项。
  \item 若\pkg{expl3}、\pkg{tcolorbox}等宏包版本过旧，会给出
        \verb|package-old|警告，建议把\TeX{}发行版更新到最新版。
  \item \verb|title|、\verb|label|、\verb|transition|、\verb|boxtype|
        与\verb|pretitle|的值中若含换行，宏包会把换行转换为空格，
        并去掉首尾空白。
  \item 结果框在插入\verb|result|图片时使用\tn{includegraphics}，
        因此图片需由\pkg{graphicx}支持的格式提供（如\file{pdf}、
        \file{png}、\file{jpg}）；用\XeTeX{}编译时\file{eps}
        不被支持。
\end{enumerate}

\section{实现简介}

\pkg{codemwe}的核心思路是将\env{example}环境体写入临时文件
（\file{jobname-example.aux}），再通过\tn{verbatiminput}%
读入该文件，从而排版出代码框；结果框则把该临时文件通过\tn{input}%
置于盒中现场排版，或插入\verb|result|选项指定的图片。MWE %
文件按指定后端语言结构拼装后写入\verb|dir|指定的
目录，其文件名由\verb|prelabel|、\verb|counter|（或\verb|filename|选项）决定。

宏包内部用\pkg{Expl3}的\pkg{l3keys}机制管理选项：宏包加载时通过
\tn{ProcessKeyOptions}把\verb|codemwe / pkgopts|一组键转发到
\verb|codemwe|键组，\env{example}、\env{example*}与\env{texcode}
环境则在各自的组内用\tn{keys_set:nn}设置选项，并由环境前预置的键
（如\env{example*}的\verb|vmode = true|）提供默认值。由于环境体
在\tn{group_begin:}与\tn{group_end:}之间处理，各示例的选项互不
影响。语种相关的文本（默认过渡语、结构注释词等）集中存放在一张
“语种 $\to$ 文本”的属性表中，由\verb|textlang|选项选用，
\tn{codemweNewLang}用于向该表登记新语种。更底层的实现细节可直接
查阅\file{codemwe.sty}源码。

\section{常见问题}

\subsection*{为什么结果框是空的？}

若未使用\verb|result|选项，结果框会通过\tn{input}编译代码临时文件
得到；请确认示例代码本身可编译。若使用了\verb|result|选项，请确认
图片文件存在且路径正确。

\subsection*{为什么代码框中的宏包名被加了注释符？}

这是\verb|withpkg|（以及\verb|withcls|）的默认行为：当输出编译结果时，
文档类与宏包内容会被加上注释符号|%|，仅作为说明之用。若希望原样输出，
可配合\verb|noshow|或\verb|nobody|选项。

\subsection*{如何把示例代码单独保存成一个文件？}

同时使用\verb|nonum|和\verb|filename|选项，即可只把环境体保存到
指定文件中（路径前缀仍取\verb|dir|选项）。注意该文件不含文档类与
导言区，也不含\fakeverb{\begin{document}}与\fakeverb{\end{document}}，
不能独立编译。

\subsection*{为什么MWE文件名与我在选项中写的\texttt{label}不一致？}

MWE 文件名只由\verb|prelabel|、\verb|counter|与
\verb|filename|决定，与\verb|label|选项无关。\verb|label|只改变
交叉引用标签，不改变文件名。

\subsection*{设置了标题，却看不到标题栏？}

标题栏是否出现取决于当前盒子类型。\env{syntaxbox}与\env{syntaxbox*}
不支持标题栏，此时编号与标题会作为首行注释写在代码框内容里；
若要看到独立的标题栏，请改用\env{mwebox}、\env{mwebox*}、
\env{mweparbox}或\env{mweparbox*}。

\subsection*{为什么结果框里没有C语言的运行结果？}

C语言代码不能在\LaTeX 中编译，宏包不会运行它，结果框只显示
\verb|result|选项指定的图片。若希望结果框中出现真实输出，需要
先用C编译器运行生成的\file{c}文件，再把输出（或截图）保存为图片，
通过\verb|result|选项插入。参见第\ref{sec:backend}节。

%%% ===================================================================
%%% English part
%%% ===================================================================
% 设置排版英文内容选项
\codemweset{ textlang = en }

\title{
  The \pkg{codemwe} Package: Typesetting Code with a Result Box
  and Generating MWE Files
  \rlap{\makebox[2.5cm][r]{
    \normalsize $\Longrightarrow$ \color{red}
    \protect\hyperlink{zh}{中文版本}
    \protect\hypertarget{en}{}
  }}
}
\author{Nan~Geng \texttt{<nangeng@nwafu.edu.cn>}}
\date{\today\qquad}
\maketitle

\section{Introduction}

\pkg{codemwe} is a code-typesetting package built on the
\pkg{tcolorbox} package and developed with \pkg{Expl3}. It typesets an
example code box together with its compiled result box, and
automatically generates an independently compilable MWE (Minimal
Working Example) file. The example code is placed in a code
box and its compiled result in a result box; the two boxes can be
arranged horizontally or vertically, which is convenient for comparing
the code with its output.

The package provides four environments: \env{example}, \env{example*},
\env{texcode} and \env{ccode}. The \env{example} environment uses the
horizontal mode by default, i.e. the code box on the left and the
result box on the right; the \env{example*} environment is a
compatibility spelling of the vertical mode, i.e. the code box on the
top and the result box at the bottom; the \env{texcode} environment
typesets a code box only, without numbering or compilation, and is
suitable for code fragments that need not be compiled; the
\env{ccode} environment typesets C code, showing a code box only and
generating a \file{c} source file.

In addition, the package provides the \tn{codemweset} macro for
setting global default options, the \tn{codemweNewBox} macro for
registering user-defined boxes, the \tn{codemweNewLang} macro
for registering user-defined language varieties for transition phrases and comment terms,
and the \tn{codemweNewBackend} macro for registering code backends
other than C.

Besides this overview, the following sections discuss the user
interfaces (Section~\ref{sec:iface-en}), the typesetting modes
(Section~\ref{sec:mode-en}), numbering and references, result figures,
the output of the preliminary content, code backends
(Section~\ref{sec:backend-en}), line numbers, package-level options,
unknown options and warnings, box types, the complete option list
(Section~\ref{sec:opts-en}), notes, an implementation overview and
frequently asked questions. For a quick start, read
Sections~\ref{sec:iface-en} and~\ref{sec:mode-en} first, and consult
Section~\ref{sec:opts-en} when needed.

\begin{noteen}
  The default language variety of the package is English
  (\optcode{textlang = en}). For documents written in another language
  it can be switched with the \optcode{textlang} option (see
  Section~\ref{sec:opts-en}), as is done in the Chinese part of this
  manual. The \optcode{textlang} option also selects the wording of the
  structural comments ``document class / preamble / body'' written into
  the MWE \file{tex} file.
\end{noteen}

\section{User Interfaces}\label{sec:iface-en}

\subsection{The \env{example} Environment}

\begin{function}[added=2026-10-10]{\begin{example},\end{example}}
  \begin{syntax}
    \tn{begin}\marg{example}\oarg{options}\marg{preliminary content}
      \meta{example code}
    \tn{end}\marg{example}
  \end{syntax}
\end{function}

  Typesets the example code and its compiled result, in the horizontal
  mode by default (code box on the left, result box on the right), and
  generates an independently compilable MWE file.

  The environment takes one optional argument \oarg{options} and one
  \textbf{mandatory} argument \marg{preliminary content}.

  The \oarg{options} is a comma-separated key-value list. Some options
  are boolean and accept only |true| or |false|; for these options the
  ``|= true|'' part of \Arg{option}| = true| may be omitted.

  \marg{preliminary content} is written into the preliminary part of
  the MWE file (e.g. the preamble of a \LaTeX{} file) and may contain
  \tn{newcommand}, \tn{tikzset}, \verb|#include <stdio.h>| and similar
  material. If no preliminary content is needed, an empty pair of
  braces |{}| must still be given; the empty pair of braces is
  \textbf{mandatory}.

  Each \env{example} environment is numbered by default. In document
  classes with a \tn{chapter} command (\pkg{book}, \pkg{report},
  etc.) the number looks like ``chapter.number'' and a reference label
  such as \verb|ex:1-1| is generated automatically; in classes without
  a \tn{chapter} command (e.g. \pkg{article}) the number is a plain
  number and the label looks like \verb|ex:1|. For instance:

\begin{texcode}
\begin{example}{}
\ExplSyntaxOn
\tl_clear_new:N \l__test_tl
\tl_set:Nn \l__test_tl { cat~likes~fish }
\tl_use:N \l__test_tl
\ExplSyntaxOff
\end{example}
\end{texcode}

\subsection{The \env{example*} Environment}

\begin{function}[added=2026-10-10]{\begin{example*},\end{example*}}
  \begin{syntax}
    \tn{begin}\marg{example*}\oarg{options}\marg{preliminary content}
      \meta{example code}
    \tn{end}\marg{example*}
  \end{syntax}
\end{function}

  Typesets the example code and its compiled result in the vertical
  mode (code box on the top, result box at the bottom). It is
  equivalent to giving the \env{example} environment the
  \optcode{vmode = true} option; for instance, the
  \verb|[pkg = {tikz}]| option of \env{example*} corresponds to
  \verb|[vmode, pkg = {tikz}]| of \env{example}. For instance:

\begin{texcode}
\begin{example*}[pkg={tikz}]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 0) -- (1, 1);
\end{tikzpicture}
\end{example*}
\end{texcode}

\subsection{The \env{texcode} Environment}

\begin{function}[added=2026-10-10]{\begin{texcode},\end{texcode}}
  \begin{syntax}
    \tn{begin}\marg{texcode}\oarg{options}
      \meta{code fragment}
    \tn{end}\marg{texcode}
  \end{syntax}
\end{function}

  Typesets a code box only. The content is not numbered, no reference
  label is generated, the example code is not compiled and no MWE
  \file{tex} file is generated. It is suitable for inserting code
  fragments that need not be compiled.

  The \oarg{options} are the same as those of the \env{example}
  environment.

  The \env{texcode} environment is in fact implemented by presetting
  the |[vmode, nonum,| |noshow]| options of \env{example}. It is
  equivalent to

\begin{quote}
  \tn{begin}|{example}[vmode, nonum, noshow]|\marg{\ldots}\\
  \tn{end}|{example}|
\end{quote}

\begin{example}[vmode, noshow, nonum]{}
\begin{texcode}
\ExplSyntaxOn
\tl_clear_new:N \l__test_tl
\tl_set:Nn \l__test_tl { cat~likes~fish }
\tl_use:N \l__test_tl
\ExplSyntaxOff
\end{texcode}
\end{example}

\changes{v1.0.0}{2026/10/20}{ add \env{ccode} environment and \tn{codemweNewBackend}.}

\subsection{The \env{ccode} Environment}

\begin{function}[added=2026-10-20]{\begin{ccode},\end{ccode}}
  \begin{syntax}
    \tn{begin}\marg{ccode}\oarg{options}
      \meta{C code fragment}
    \tn{end}\marg{ccode}
  \end{syntax}
\end{function}

  Typesets C code: it shows a code box only, without numbering or a
  result box, and generates a source file in the C format (see
  Section~\ref{sec:backend-en}). It is suitable for inserting C code
  fragments or function definitions.

  The \oarg{options} are the same as those of the \env{example}
  environment, except that \verb|backend| has already been preset to
  \optcode{c} and normally need not be given again.

  The \env{ccode} environment is in fact implemented by presetting the
  options \optcode{vmode}, \optcode{nonum}, \optcode{noshow} and
  \optcode{backend = c} for the \env{example} environment.

\begin{example}[vmode, noshow, nonum]{}
\begin{ccode}[filename = { hello.c }]{}
#include <stdio.h>

int main(void)
{
    printf("Hello, World!\n");
    return 0;
}
\end{ccode}
\end{example}

\begin{noteen}
  The body of the \env{ccode} environment is written verbatim to the
  \file{c} file, so \LaTeX-specific options such as \verb|cls| and
  \verb|pkg| are meaningless for it. If the code needs preliminary
  content such as \fakeverb{#include} lines, they may be written directly
  in the environment body or given in the mandatory argument (extra
  preamble) of the environment; both end up in the generated source
  file, but the latter is not shown in the code box unless the
  \verb|withextra| option is used as well.
\end{noteen}

\subsection{\tn{codemweset} for Global Settings}

\begin{function}[added=2026-10-10]{\codemweset}
  \begin{syntax}
    \tn{codemweset}\marg{options}
  \end{syntax}
\end{function}

  Modifies the default options of the following \env{example},
  \env{example*}, \env{texcode} and \env{ccode} environments in the
  current scope. The \marg{options} is a comma-separated key-value
  list. For instance:

\begin{texcode}
\codemweset{ vmode, withpkg }
\end{texcode}

\subsection{\tn{codemweNewBox} for Registering New Boxes}

\begin{function}[added=2026-10-10]{\codemweNewBox}
  \begin{syntax}
    \tn{codemweNewBox}\marg{box environment name}\oarg{options}
  \end{syntax}
\end{function}

  Registers a new box environment with \pkg{codemwe}; once registered,
  the box can be used for the code box and the result box through the
  \verb|boxtype| option.

  \marg{box environment name} must obey the argument interface

\begin{quote}
  \verb|O{background colour}| \verb|d()| \verb|O{extra options}|
\end{quote}

  It is recommended to define the box with the
  \tn{DeclareTColorBox} command of \pkg{tcolorbox}. Currently only
  \verb|withtitle| is supported in \oarg{options}, which declares
  whether the box supports a title bar;

\begin{texcode}
\codemweNewBox{ mybox }[ withtitle = true ]
\end{texcode}

  \begin{noteen}
    Internally the package maintains a property list mapping a ``box
    environment name'' to ``whether it supports a title bar'', in which
    the six built-in boxes are pre-registered. \tn{codemweNewBox} only
    records the properties; it does not define the environment itself.
    Hence one must first define \marg{box environment name} with
    \tn{DeclareTColorBox} (or an equivalent means, such as
    \tn{NewDocumentEnvironment}) and then call this command to register
    it.

    If a box with the same name as a built-in box environment is used,
    it will override the settings of the built-in box.
  \end{noteen}

\subsection{\tn{codemweNewLang} for Registering New Language Varieties}

\begin{function}[added=2026-10-13]{\codemweNewLang}
  \begin{syntax}
    \tn{codemweNewLang}\marg{variety name}\marg{eight pieces of content}
  \end{syntax}
\end{function}

  Registers a new language variety with \pkg{codemwe}, supplying the
  transition phrases, comment words and other texts for that variety;
  once registered, the variety can be selected through the
  \verb|textlang| option to typeset the transition text, the structural
  comments and so on.

  \marg{variety name} is the name of the new variety.
  \marg{eight pieces of content} consists of eight comma-separated
  pieces of text (pre-transition text, post-transition text,
  unnumbered transition text, document-class comment word, preamble
  comment word, body comment word, default document class, leading word
  for the title and the \tn{ref} result). For example:

\begin{texcode}
\codemweNewLang{ fr }
  {
    Le~résultat~de,
    est~affiché~ci-dessous.,
    Le~résultat~du~code~est~affiché~ci-dessous.,
    classe~de~document,
    préambule,
    corps,
    article,
    exemple
  }
\end{texcode}

  The package ships with two built-in varieties: \verb|en| (English)
  and \verb|zh| (Chinese). If the variety name defined by
  \tn{codemweNewLang} duplicates a built-in name, the built-in text
  content is overwritten.

\begin{noteen}
  A comma inside any of the \marg{eight pieces of content} must be
  protected with braces, and an empty field must be left blank rather
  than omitted.
\end{noteen}

\subsection{\tn{codemweNewBackend} for Registering New Code Backends}

\begin{function}[added=2026-10-20,updated=2026-10-23]{\codemweNewBackend}
  \begin{syntax}
    \tn{codemweNewBackend}\marg{backend name}\marg{file extension}\marg{comment character}\marg{compilable}
      \oarg{\pkg{minted} language name}
  \end{syntax}
\end{function}

  Registers a new code backend (source language) with \pkg{codemwe};
  once registered, the backend can be used through the \verb|backend|
  option to typeset code and generate a source file of the
  corresponding format.

  \marg{backend name} is the name of the new backend and also the
  value of the \verb|backend| option.
  \marg{file extension} is given without the dot, e.g. \optcode{c} or
  \optcode{py}.
  \marg{comment character} is read verbatim and is used for the
  first-line comment of the source file: the percent sign of \LaTeX,
  \optcode{//} of C, or the number sign of Python, none of which needs to
  be escaped.
  \marg{compilable} takes the value \optcode{true} if the source file is
  to be compiled as a \LaTeX{} document with its result shown in the
  result box, and \optcode{false} if the package is not to compile it, in
  which case the result box can only show the image given by the
  \verb|result| option.
  \oarg{\pkg{minted} language name} is optional and gives the name that
  the \pkg{minted} package uses for that language (i.e. the
  \pkg{pygments} lexer name), which is needed for the syntax
  highlighting of the \verb|minted| option, e.g. \optcode{python} or
  \optcode{javascript}. When omitted or left empty it defaults to
  \marg{backend name}. If the \verb|minted| option is not used, this
  argument has no effect on the output at all.

\begin{texcode}
\codemweNewBackend { python } { py } { # } { false }
\end{texcode}

  If the backend is also to be highlighted, give the language name as
  well:

\begin{texcode}
\codemweNewBackend { py } { py } { # } { false } [ python ]
\end{texcode}

  The package ships with two built-in backends: \optcode{tex} (the
  default) and \optcode{c}. If the backend name registered by
  \tn{codemweNewBackend} duplicates a built-in name, the settings of the
  built-in backend are overwritten.

\section{Typesetting Modes}\label{sec:mode-en}

\subsection{Horizontal Mode}

In the horizontal mode the code box is on the left and the result box
on the right, which is convenient for comparing the code with its
output. The width allocation rule of the horizontal mode is: if
\verb|width| is not specified, the spacing \verb|sep| between the two
boxes is subtracted from the line width first and the remaining width
is divided equally into two columns. For instance:

\begin{texcode}
\begin{example}{}
\ExplSyntaxOn
\tl_clear_new:N \l__fsttest_tl
\tl_set:Nn \l__fsttest_tl
  { cat~likes~fish }
\tl_use:N \l__fsttest_tl
\ExplSyntaxOff
\end{example}
\end{texcode}

\noindent
which is typeset as:

\begin{example}{}
\ExplSyntaxOn
\tl_clear_new:N \l__fsttest_tl
\tl_set:Nn \l__fsttest_tl
  { cat~likes~fish }
\tl_use:N \l__fsttest_tl
\ExplSyntaxOff
\end{example}

\subsection{Vertical Mode}

In the vertical mode the code box is on the top, the result box is at
the bottom, and an optional transition text may be inserted in
between. The mode is switched with the \verb|vmode| option. For
instance:

\begin{texcode}
\begin{example}[vmode]{}
\ExplSyntaxOn
\tl_clear_new:N \l__sectest_tl
\tl_set:Nn \l__sectest_tl { cat~likes~fish }
\tl_use:N \l__sectest_tl
\ExplSyntaxOff
\end{example}
\end{texcode}

\noindent
which is typeset as:

\begin{example}[vmode]{}
\ExplSyntaxOn
\tl_clear_new:N \l__sectest_tl
\tl_set:Nn \l__sectest_tl { cat~likes~fish }
\tl_use:N \l__sectest_tl
\ExplSyntaxOff
\end{example}

In the vertical mode the transition text between the code box and the
result box is taken from the \textbf{default transition text} of the
language variety selected by the \optcode{textlang} option (see
Section~\ref{sec:opts-en}). Since this manual has set the variety to
English, the transition text shown in the example above is ``The
result of \ref{ex:19} is shown below.'', in which the
reference \fakeverb{\ref{ex:19}} is generated automatically; if the \verb|nonum|
option is used, the non-numbered text ``The result of the code is
shown below.'' is used. A single example can also specify its own
transition text with the \verb|transition| option.

\subsection{Custom Transition Text}

The \verb|transition| option customises the transition text between
the code box and the result box for a single example (it overrides the
default transition text of the variety selected with
\optcode{textlang}). For instance:

\begin{texcode}
\begin{example}[
  vmode,
  pkg        = { tikz },
  title      = { Custom transition text },
  transition = { The typeset result of this example is shown below;
                 check that the code and the output agree: },
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
  \draw (1, 1) -- (2, 0);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
which is typeset as:

\begin{example}[
  vmode,
  pkg        = { tikz },
  title      = { Custom transition text },
  transition = { The typeset result of this example is shown below;
                 check that the code and the output agree: },
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
  \draw (1, 1) -- (2, 0);
\end{tikzpicture}
\end{example}

\subsection{Spacing in Horizontal Mode}

In the horizontal mode the \verb|sep| option controls the spacing
between the left code box and the right result box; its initial value
is \optcode{18pt}. Like \verb|width|, the value should be a \LaTeX{}
dimension such as \optcode{sep = 0.2\textwidth}; writing
\optcode{sep = 0.3} would be read as \optcode{0.3pt} because \TeX{}
appends the default unit \optcode{pt}. For instance:

\begin{texcode}
\begin{example}[
  pkg   = { tikz },
  sep   = { 0.2\textwidth },
  title = { Wider spacing },
]{}
\begin{tikzpicture}
  \draw (0, 0) circle (1);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
which is typeset as:

\begin{example}[
  pkg   = { tikz },
  sep   = { 0.2\textwidth },
  title = { Wider spacing },
]{}
\begin{tikzpicture}
  \draw (0, 0) circle (1);
\end{tikzpicture}
\end{example}

\subsection{Code Box Width}

The \verb|width| option controls the width of the code box. If it is
not specified, the horizontal mode divides the width equally while the
vertical mode uses \tn{textwidth}. The following example sets the code
box width to \fakeverb{0.35\textwidth}:

\begin{example}[
  pkg   = { tikz },
  width = 0.35\textwidth,
  title = { set box width },
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (5, 1);
\end{tikzpicture}
\end{example}

Dimension options such as \verb|width| and \verb|sep| should be given
as \LaTeX{} dimensions (e.g. \optcode{0.35\textwidth} or
\optcode{4cm}). A bare decimal such as \optcode{width = 0.35} is read
as \optcode{0.35pt} because \TeX{} appends the default unit
\optcode{pt}, which collapses the code box to a hairline.

\section{Numbering and References}

By default every \env{example} environment is numbered. In document
classes with a \tn{chapter} command (\pkg{book}, \pkg{report}, etc.)
the number looks like ``chapter.number''; otherwise (e.g.
\pkg{article}) it is a plain number. A comment line with the number is
added to the first line of the code box:

\begin{texcode}
% Example 1.3 Draw a line
\end{texcode}

At the same time a reference label such as \verb|\label{ex:1-3}| is
generated automatically and can be referenced with \tn{ref}, which
prints the leading word given by \verb|pretitle| (\optcode{example} by
default) followed by the number: ``Example~1.3''. If the
\verb|label| option customises the label, \tn{ref} resolves the
customised one.

\begin{example}[
  pkg   = { tikz },
  label = { code:drawline-en },
  title = { Draw a line },
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
\end{tikzpicture}
\end{example}

The \ref{code:drawline-en} is the effect of customising the reference label
with the

\begin{quote}
\verb|label = { code:drawline-en }|
\end{quote}

\noindent option and referencing it with \verb|\ref{code:drawline-en}|.

If no numbering is wanted, use the \verb|nonum=true| or \verb|nonum|
option: the counter is not advanced and no label is generated, but the
code box and the result box are still typeset normally.

\begin{example}[
  pkg = { tikz },
  nonum,
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
\end{tikzpicture}
\end{example}

\section{Showing the Code Only}

If only the code box is wanted, use the \verb|noshow=true| or
\verb|noshow| option:

\begin{texcode}
\begin{example}[noshow]{}
  ...
\end{example}
\end{texcode}

The code box is then typeset normally while the result box and its
transition text are omitted; numbering and reference labels are
unaffected.

\begin{example}[ noshow, vmode, pkg = { tikz } ]{}
\begin{tikzpicture}
  \draw (0, 0) cos (2, 1);
\end{tikzpicture}
\end{example}

\section{Result Figures}

If the example code is inconvenient to compile inside the document,
the \verb|result| option can specify an image file to be used as the
compiled result:

\begin{texcode}
\begin{example}[ result = fig/sine.pdf, scale = 0.8 ]{}
  ...
\end{example}
\end{texcode}

\verb|scale=0.8| inserts the image at 80\% of its natural size. To
insert it by width or height, use the \verb|wd| or \verb|ht| option
instead.

\begin{example}[
  pkg    = { tikz },
  result = sine.pdf,
  scale  = 0.8,
]{}
\begin{tikzpicture}
  \draw (0, 0) sin (2, 1);
\end{tikzpicture}
\end{example}

\subsection{Width and Height of the Result Figure}

The \verb|wd| option typesets the result figure at a given width, e.g.
\verb|wd=0.2\textwidth|:

\begin{example}[
  pkg    = { tikz },
  result = sine.pdf,
  wd     = 0.2\textwidth,
]{}
\begin{tikzpicture}
  \draw (0, 0) sin (2, 1);
\end{tikzpicture}
\end{example}

The \verb|ht| option typesets the result figure at a given height,
e.g. \verb|ht=1cm|:

\begin{example}[
  pkg    = { tikz },
  result = sine.pdf,
  ht     = 1cm,
]{}
\begin{tikzpicture}
  \draw (0, 0) sin (2, 1);
\end{tikzpicture}
\end{example}

\begin{noteen}
  When \verb|wd| is given, both \verb|ht| and \verb|scale| are
  ignored; when only \verb|ht| is given, \verb|scale| is ignored.
\end{noteen}

\section{Outputting the Preliminary Content}

Different combinations of the logical options \verb|withcls|,
\verb|withpkg|, \verb|withextra| and \verb|nobody| control whether the
document class, the packages with their options and the preliminary
content are printed in the example code box. If \verb|noshow| or
\verb|nobody| is used, this content is printed as is; otherwise a
comment sign |%| is prepended to the \verb|cls| and \verb|pkg|
content.

The following example combines \verb|withcls|, \verb|withpkg|,
\verb|withextra| and \verb|nobody|: the document class and the
preliminary content (the preamble) are printed as is in the code box,
while the
environment body (\verb|nobody|) and the compiled result are not
printed:

\begin{example}[
  cls       = { article = { 12pt, a4paper } },
  pkg       = { tikz, xcolor = { svgnames } },
  title     = { Draw a line },
  pretitle  = { Example },
  width     = { 0.8\textwidth },
  vmode,
  nonum,
  withcls,
  withpkg,
  withextra,
  nobody,
]{
\newcommand{\mya}{a}
\newcommand{\myb}{b}
}
\begin{tikzpicture}
  \draw (0, 0) node[below] { \mya } -- (1, 1) node[above] { \myb };
\end{tikzpicture}
\end{example}

\section{Code Backends}\label{sec:backend-en}

By default \pkg{codemwe} typesets \LaTeX{} example code: the content of
the code box is written into the temp \file{.tex} file, which is read
into the result box with \tn{input} and compiled there to produce the
result. This mechanism relies on the code being \LaTeX{} code itself.

In order to typeset code of other languages such as C, the package
introduces the notion of a \emph{code backend}, selected with the
\verb|backend| option. A backend records four pieces of information:
the file extension of the source file, the comment character used for
its first-line comment, whether the code of that language can be
compiled by \LaTeX, and the language name that the \pkg{minted} package
uses for that language. Two backends are built in, as shown in
Table~\ref{tab:backend-en}.

\begin{table}[htbp]
  \centering
  \renewcommand{\tablename}{Table}
  \caption{The built-in code backends}
  \label{tab:backend-en}
  \begin{tabular}{ccccc}
    \toprule
    Backend & Extension & Comment & Compilable & \pkg{minted} language \\
    \midrule
    \optcode{tex} & \file{tex} & \texttt{\char37} & yes & \optcode{tex} \\
    \optcode{c}   & \file{c}   & \optcode{//} & no  & \optcode{c} \\
    \bottomrule
  \end{tabular}
\end{table}

The last column is used only when the \verb|minted| option is enabled
(see Section~\ref{sec:minted-en}); without \pkg{minted} it has no
effect on the output.

With \verb|backend = c| the behaviour is as follows:

\begin{enumerate}[itemsep=0.3ex]
  \item the generated source file is not a \LaTeX{} document but a plain
        C source file that can be passed directly to a C compiler: its
        first line is a comment (e.g. \optcode{// Example 2.2 Sum of two numbers}),
        followed by the preliminary content given in the mandatory
        argument of the environment and the code in the code box;
  \item the comment lines of the code box use the C comment
        character |//|, and the \LaTeX-specific structural comments
        ``document class'', ``preamble'' and ``body'' are not added;
  \item options such as \verb|cls|, \verb|pkg|, \verb|withcls| and
        \verb|withpkg| are meaningless for C code and are therefore
        ignored;
  \item since C code cannot be compiled by \LaTeX, the package does not
        compile it during typesetting. If the \verb|result| option is
        given, the result box shows the given image; otherwise the
        result box is omitted altogether and an
        \optcode{backend-no-result} warning is issued.
\end{enumerate}

For example, a C function can be typeset with the following code,
using an image as the result:

\begin{texcode}
\begin{example}[
  backend  = c,
  title    = { Sum of two numbers },
  result   = { csum.png },
  scale    = 0.3,
  filename = { sum.c },
]{
#include <stdio.h>

int sum(int a, int b);

int main(void)
{
  int a, b;
  a = 3;
  b = 4;

  printf("sum=%d\n", sum(a, b));

  return 0;
}
}
int sum(int a, int b)
{
    return a + b;
}
\end{example}
\end{texcode}

\noindent
which is typeset as:

\begin{example}[
  backend  = c,
  title    = { Sum of two numbers },
  result   = { csum.png },
  scale    = 0.3,
  filename = { sum.c },
]{
#include <stdio.h>

int sum(int a, int b);

int main(void)
{
  int a, b;
  a = 3;
  b = 4;

  printf("sum=%d\n", sum(a, b));

  return 0;
}
}
int sum(int a, int b)
{
    return a + b;
}
\end{example}

Here \verb|filename = { sum.c }| saves the source file as
\file{sum.c}, whose content is:

\begin{texcode}
// Example 28 Sum of two numbers
#include <stdio.h>

int sum(int a, int b);

int main(void)
{
  int a, b;
  a = 3;
  b = 4;

  printf("sum=%d\n", sum(a, b));

  return 0;
}

int sum(int a, int b)
{
    return a + b;
}
\end{texcode}

If the name of the source file does not matter, \verb|filename| may be
omitted; the name is then constructed from \verb|dir|, \verb|prelabel|
and the number, with the extension of the current backend (C uses
\file{c}), for instance \file{codes/ex28.c}.

\begin{noteen}
  Since C code is not compiled during typesetting, the image shown in
  the result box must be prepared in advance and kept in step with the
  code. If \verb|result| is not given, the result box can be turned off
  with the \verb|noshow| option to avoid the warning; the \env{ccode}
  environment has already set \verb|noshow|.

  To typeset a language other than C (e.g. Python), it suffices to
  register a new backend with \tn{codemweNewBackend} and use it through
  the \verb|backend| option; no modification of the package itself is
  needed.
\end{noteen}

\section{Displaying Line Numbers}

Line numbers can be added to the code box with the \fakeverb{[linenos]}
option, for instance:

\begin{texcode}
\begin{example}[
  pkg   = { tikz },
  title = { Draw a line },
  linenos,
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
which is typeset as:

\begin{example}[
  pkg   = { tikz },
  title = { Draw a line },
  linenos,
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
\end{tikzpicture}
\end{example}

\begin{noteen}
  The content added by \verb|withcls|, \verb|withpkg| and
  \verb|withextra|, as well as the automatically inserted comments,
  is counted in the line numbers as well.
\end{noteen}

\section{A Complete Example}

The following example combines several options. It uses the
\verb|article| class together with the \verb|tikz| and \verb|xcolor|
packages, adds two user macros to the preamble, and uses the vertical
mode with a given code box width and a customised title:

\begin{example}[
  cls       = { article = { 12pt, a4paper } },
  pkg       = { tikz, xcolor = { svgnames } },
  title     = { Draw a line },
  label     = { code:multi-opts-en },
  pretitle  = { example },
  width     = { 0.55\textwidth },
  vmode,
  withextra,
]{
\newcommand{\myA}{A}
\newcommand{\myB}{B}
}
\begin{tikzpicture}
  \draw (0, 0) node[below] { \myA } -- (1, 1)
    node[above] { \myB };
\end{tikzpicture}
\end{example}

The \ref{code:multi-opts-en} generates the MWE \file{tex} file
\file{codes/ex25.tex}, whose content is:

\begin{texcode}
% document class
\documentclass[12pt,a4paper]{article}

% preamble
\usepackage{tikz}
\usepackage[svgnames]{xcolor}

\newcommand{\myA}{A}
\newcommand{\myB}{B}

% body
\begin{document}

\begin{tikzpicture}
  \draw (0, 0) node[below] { \myA } -- (1, 1) node[above] { \myB };
\end{tikzpicture}

\end{document}
\end{texcode}

\begin{noteen}
  The structural comment lines ``\% document class'', ``\% preamble'' and
  ``\% body'' at the top of each of the three blocks are provided by the
  language variety selected with the \optcode{textlang} option (here
  English, the default). They can simply be deleted when the MWE file
  is used.
\end{noteen}

\begin{noteen}
  If a macro such as \tn{tikzset} is needed inside the title given by
  the |title| option, the \tn{string} primitive must be used, i.e.
  \tn{string}\tn{tikzset} prints \tn{tikzset}, so that the macro is not
  expanded when the comment line is written.
\end{noteen}

\section{Saving the Environment Body to a File}

If only the environment body needs to be saved to a file, give the two
options \oarg{nonum, filename=test.tex} together. The example is then
not numbered, but the body is saved to the file given by the
\verb|filename| option, with the path prefix still taken from the
\verb|dir| option.

\begin{noteen}
  The saved file contains neither the document class nor the preamble,
  nor the \tn{begin}\marg{document} and \tn{end}\marg{document} lines,
  so it cannot be compiled independently.
\end{noteen}

\begin{example}[
  vmode,
  noshow,
  nonum,
  title    = { Define a user interface },
  filename = test.tex,
]{}
\ExplSyntaxOn
\tl_clear_new:N \l__test_tl
\tl_set:Nn \l__test_tl { cat~likes~fish }
\newcommand{\mytest}{ % define a user interface
  \tl_use:N \l__test_tl
}
\ExplSyntaxOff
\end{example}

\section{Syntax Highlighting}\label{sec:minted-en}

By default the code in the code box is typeset as is, without syntax
highlighting. If readability of the code matters, the \verb|minted|
option can be passed to the package so that the box is typeset with the
\pkg{minted} package and the code is highlighted:

\begin{texcode}
\usepackage[minted]{codemwe}
\end{texcode}

Without the \verb|minted| option the package keeps using the original
\pkg{fancyvrb} scheme, so the behaviour is the same as in previous
versions. With it, the content of the code box is typeset by
\pkg{minted} at \tn{small} size with \optcode{autogobble} enabled, so
that the common indentation is removed. Line numbers are still
controlled by the \verb|linenos| option, exactly as without \pkg{minted}.

\begin{noteen}
  \pkg{minted} invokes an external program (\optcode{latexminted} or
  \optcode{pygmentize}) to do the highlighting, so the document must be
  compiled with \optcode{-shell-escape}. If shell escape is disabled or
  \pkg{minted} is not installed, the package does not abort the run:
  it issues a \optcode{minted-unavailable} warning and falls back to
  the original scheme. The document is still produced, just without
  highlighting.

  Moreover, \pkg{minted} enables \optcode{fasthighlightmode} by default:
  on the first run only a placeholder is inserted into the code box, and
  the highlighted result appears from the second run onwards. Two or
  more runs are therefore needed once \verb|minted| is enabled.
\end{noteen}

The language name needed for highlighting is not given by the
\verb|minted| option but by the \verb|backend| option: every code
backend records its \pkg{minted} language name (see
Table~\ref{tab:backend-en}), and the package passes the name of the
current backend to \pkg{minted} automatically. With \verb|backend = c|,
for instance, the code is highlighted as \optcode{c}, and with
\verb|backend = tex| as \optcode{tex}.

The highlighting style is set with the \verb|mintedstyle| option, whose
value is a style name understood by \pkg{minted} (\pkg{pygments}); the
initial value is \optcode{default}. For example, to use the
\optcode{tango} style:

\begin{texcode}
\usepackage[minted, mintedstyle = tango]{codemwe}
\end{texcode}

Common styles include \optcode{default}, \optcode{friendly},
\optcode{tango}, \optcode{monokai} and \optcode{bw}; the complete list
is given in the style documentation of \pkg{pygments}. If
\verb|mintedstyle| is set without enabling \verb|minted|, the package
issues a \optcode{mintedstyle-unused} warning but still records the
value, so that it takes effect as soon as \verb|minted| is enabled.

Both \verb|minted| and \verb|mintedstyle| may be given as package
options, through \tn{codemweset}, or in an individual environment, just
like any other option:

\begin{texcode}
\begin{example}[
  backend     = c,
  minted,
  mintedstyle = friendly,
  result      = chelloworld.png,
  wd          = 0.45\textwidth,
  title       = { Syntax highlighting },
]{}
#include <stdio.h>
int main(void)
{
    printf("Hello, world!\n");
    return 0;
}
\end{example}
\end{texcode}

\noindent
which is typeset as:

\begin{example}[
  backend     = c,
  minted,
  mintedstyle = friendly,
  result      = chelloworld.png,
  wd          = 0.45\textwidth,
  title       = { Syntax highlighting },
]{}
#include <stdio.h>
int main(void)
{
    printf("Hello, world!\n");
    return 0;
}
\end{example}

\subsection{Switching Highlighting On and Off in the Body}

Like any other boolean option, \verb|minted| can be switched on and off
in the document body, so that only some examples are highlighted:

\begin{texcode}
\codemweset{minted}          % on: every following example is highlighted
\begin{example}{}
  ...
\end{example}
\begin{example}[minted = false]{}
  ...
\end{example}
\codemweset{minted = false}  % off: back to the original scheme
\end{texcode}

\begin{noteen}
  The \pkg{minted} package can be loaded in the preamble only. This
  package performs the check at load time (when it is necessarily still
  in the preamble): if \pkg{minted} is installed and the document is
  compiled with \verb|-shell-escape|, it loads \pkg{minted} right away.
  \verb|minted| and \verb|minted = false| therefore work anywhere ---
  in the preamble, in the body, or as an environment option --- without
  any need to enable the option once in the preamble beforehand.
  Note that \verb|minted = false| merely switches the highlighting off,
  it does not unload the \pkg{minted} package, so no reloading is needed
  when it is switched on again later.

  If \pkg{minted} is missing or \verb|-shell-escape| is not used, the
  load does not happen; enabling \verb|minted| then issues a
  \optcode{minted-unavailable} warning and the code is typeset with the
  original scheme, without highlighting.
\end{noteen}

\begin{noteen}
  The purpose of the result box is to actually compile and run the
  example code and show the outcome, so the code in the result box is
  always read in and compiled as is, never highlighted; only the code
  in the code box is highlighted by \pkg{minted}. For backends such as
  \optcode{c}, which cannot be compiled by \LaTeX, the result box is
  shown only when the \verb|result| option is given anyway, so this
  makes no difference.
\end{noteen}

\section{Package-Level Default Options}

The package accepts global default options through
\tn{usepackage}"[options]"\marg{codemwe}; they serve as the initial
values of the following \env{example}, \env{example*}, \env{texcode}
and \env{ccode} environments. The keys that may be given as package
options are \verb|vmode|, \verb|nobody|, \verb|noshow|, \verb|nonum|,
\verb|withcls|, \verb|withpkg|, \verb|withextra|, \verb|cls|,
\verb|pkg|, \verb|width|, \verb|sep|, \verb|prelabel|, \verb|pretitle|,
\verb|dir|, \verb|counter|, \verb|boxtype|, \verb|textlang|,
\verb|backend|, \verb|linenos|, \verb|minted| and \verb|mintedstyle|.

The initial values set at package level can be overridden inside an
environment by an option of the same name. For instance:

\begin{texcode}
\begin{example}[
  vmode = false,
  pkg   = { tikz },
  title = { Override package's vmode },
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1) -- (2, 0);
\end{tikzpicture}
\end{example}
\end{texcode}

\noindent
which is typeset as:

\begin{example}[
  vmode = false,
  pkg   = { tikz },
  title = { Override package's vmode },
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1) -- (2, 0);
\end{tikzpicture}
\end{example}

\section{Unknown Options and Warnings}

If an undefined key is given, the package issues an
\verb|unknown-key| warning and ignores the option. Compiling the
following example

\begin{texcode}
\begin{example}[foo, pkg={tikz}]{}
  ...
\end{example}
\end{texcode}

\noindent
produces a warning like

\begin{texcode}
Package codemwe Warning:\\
Unknown key-val option 'foo' for package 'codemwe'.
\end{texcode}

\noindent
but the compilation is not aborted.

In addition, two warnings are related to the code backend:

\begin{itemize}[itemsep=0.3ex]
  \item \optcode{unknown-backend}: the \verb|backend| option names a
        backend that is not registered, and the package falls back to
        \optcode{tex};
  \item \optcode{backend-no-result}: the current backend cannot be
        compiled by \LaTeX{} and no \verb|result| option is given, so the
        result box is omitted altogether. Giving a \verb|result| image
        or using the \verb|noshow| option removes the warning.
\end{itemize}

Three further warnings relate to syntax highlighting:

\begin{itemize}[itemsep=0.3ex]
  \item \optcode{minted-unavailable}: the \optcode{minted} option is
        enabled but shell escape is disabled for the current run or the
        \pkg{minted} package is not installed. The package falls back to
        the original scheme, so the code is still typeset, just without
        highlighting;
  \item \optcode{mintedstyle-unused}: \optcode{mintedstyle} is set while
        the \optcode{minted} option is not enabled, so the style has no
        effect for the time being;
  \item \optcode{minted-no-lexer}, \optcode{minted-unknown-lexer}: the
        current backend records no \pkg{minted} language name, or the
        recorded name is not recognised by \pkg{pygments}.
\end{itemize}

\section{Box Types}

The \verb|boxtype| option selects the box environment used for the
code box and the result box; its default value is \env{syntaxbox}.
The built-in box types are listed in
Table~\ref{tab:codemwe-boxtype-en}.

\begin{table}[!htbp]
  \centering
  \renewcommand{\tablename}{Table}
  \caption{Built-in box types}
  \label{tab:codemwe-boxtype-en}
  \begin{tabular}{llccc}
    \toprule
    \textbf{Type} & \textbf{Background} & \textbf{Border} & \textbf{Title bar} & \textbf{Dependency}\\
    \midrule
    \env{syntaxbox}  & \verb|gray!12| & none        & no  & \pkg{tcolorbox}\\
    \env{syntaxbox*} & \verb|white|   & none        & no  & \pkg{tcolorbox}\\
    \env{mwebox}     & \verb|cyan|    & none        & yes & \pkg{tcolorbox}\\
    \env{mwebox*}    & \verb|cyan|    & full border & yes & \pkg{tcolorbox}\\
    \env{mweparbox}  & \verb|purple|  & left bar    & yes & \pkg{tcolorbox}\\
    \env{mweparbox*} & \verb|white|   & left bar    & yes & \pkg{tcolorbox}\\
    \bottomrule
  \end{tabular}
\end{table}

The three starred boxes are white-background, borderless variants of
their unstarred counterparts. The \env{mwebox}/\env{mwebox*} and
\env{mweparbox}/\env{mweparbox*} boxes support a title bar: the
example number and the title automatically become the content of the
title bar. The \env{syntaxbox} and \env{syntaxbox*} boxes do not
support a title bar; in that case the number and the title are written
as a first-line comment inside the code box.

The~\ref{code:mwebox-en} is typeset with the \env{mwebox} box.

\begin{example}[ boxtype = mwebox, label = { code:mwebox-en }, pkg = { tikz } ]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1);
\end{tikzpicture}
\end{example}

A user-defined box can be registered with \tn{codemweNewBox}. As long
as the box environment obeys the interface

\begin{quote}
  \verb|O{background colour}| \verb|d()| \verb|O{extra options}|
\end{quote}

\noindent i.e. the first
optional argument \verb|[...]| takes a background colour, the second
optional argument \verb|(...)| takes a title and the third optional
argument \verb|[...]| takes extra \pkg{tcolorbox} options, it can be
used by \verb|boxtype|. For example, such a box can be defined with
the \tn{DeclareTColorBox} command of \pkg{tcolorbox}:

\begin{texcode}
% Define a tcolorbox box (same interface as the built-in boxes)
\DeclareTColorBox{ mybox }{ O{ green!30 } d() O{  } }
  {
    colback  = #1,
    colframe = #1,
    boxrule  = 0pt,
    arc      = 4mm,
    left     = 8pt,
    right    = 8pt,
    top      = 4pt,
    bottom   = 4pt,
    nobeforeafter,
    IfValueT = { #2 } { title = #2, coltitle = green!30!black },
    #3,
  }
\end{texcode}

Since the box uses its \verb|()| argument to produce a title bar, it
should be registered with \optcode{withtitle = true} (which is also
the default).

\begin{texcode}
% Register the box for typesetting
\codemweNewBox{ mybox }[ withtitle = true ]
\end{texcode}

\begin{noteen}
  If a custom box supports a title bar, \optcode{withtitle} in
  \tn{codemweNewBox} must be \optcode{true}; if it does not, declare
  \optcode{withtitle = false}. If the declaration does not match the
  actual behaviour, the number and the title may be lost or printed
  twice.
\end{noteen}

The following example is typeset with \env{mybox} (for readability the
box is defined here directly with \tn{DeclareTColorBox}; the result is
identical to defining and registering it as shown above):

\DeclareTColorBox{ mybox }{ O{ green!30 } d() O{  } }
  {
    colback  = #1,
    colframe = #1,
    boxrule  = 0pt,
    arc      = 4mm,
    left     = 8pt,
    right    = 8pt,
    top      = 4pt,
    bottom   = 4pt,
    nobeforeafter,
    IfValueT = { #2 } { title = #2, coltitle = green!30!black },
    #3,
  }
\codemweNewBox{ mybox }[ withtitle = true ]

\begin{example}[
  pkg     = { tikz },
  title   = { A custom box },
  boxtype = mybox,
]{}
\begin{tikzpicture}
  \draw (0, 0) -- (1, 1) -- (2, 0);
\end{tikzpicture}
\end{example}

\section{Options}\label{sec:opts-en}

All key-value options of \pkg{codemwe} are listed below. The ``initial
value'' is the value an option has before any setting; for boolean
options the ``default value'' is the value taken when the option is
written without a value (e.g. \optcode{vmode}).

\begin{option}{ opt = vmode, desc = {= \meta{true/false}}, init=false }
  The typesetting mode. \optcode{vmode = false} is the horizontal mode
  and \optcode{vmode = true} the vertical mode; the boolean
  ``|= true|'' may be omitted, so writing \optcode{vmode} alone means
  \optcode{vmode = true}. The initial value is \optcode{false}.
\end{option}

\begin{option}{ opt = noshow, desc = {= \meta{true/false}}, init=false }
  Whether the result box is shown. With \optcode{noshow} only the code
  box is shown; the result box and its transition text are omitted.
  The initial value is \optcode{false}.
\end{option}

\begin{option}{ opt = nonum, desc = {= \meta{true/false}}, init=false }
  Whether the example is numbered and labelled. With \optcode{nonum}
  the numbering is switched off: the counter is not advanced and no
  label is generated, but the code box and the result box are still
  typeset normally. The initial value is \optcode{false}.
\end{option}

\begin{option}{ opt = nobody, desc = {= \meta{true/false}}, init=false }
  Whether the body of the \env{example} environment is printed. With
  \optcode{nobody} the body is not printed, and hence the compiled
  result is not printed either (equivalent to also using
  \optcode{noshow}). The initial value is \optcode{false}.
\end{option}

\begin{option}{ opt = withcls, desc = {= \meta{true/false}}, init=false }
  Whether the document class content given by \optcode{cls} is added
  to the example code box. If \optcode{noshow} or \optcode{nobody} is
  used, the content of \optcode{cls} is printed as is; otherwise a
  comment sign \optcode{\%} is prepended to it. The initial value is
  \optcode{false}.
\end{option}

\begin{option}{ opt = withpkg, desc = {= \meta{true/false}}, init=false }
  Whether the package content given by \optcode{pkg} is added to the
  example code box. If \optcode{noshow} or \optcode{nobody} is used,
  the content of \optcode{pkg} is printed as is; otherwise a comment
  sign is prepended to each package. The initial value is
  \optcode{false}.
\end{option}

\begin{option}{ opt = withextra, desc = {= \meta{true/false}}, init=false }
  Whether the preliminary content given by the mandatory argument of
  \env{example} is added to the example code box. The initial value
  is \optcode{false}.
\end{option}

\begin{option}{ opt = cls, desc = {= \meta{document class}}, init=article }
  The document class required by the MWE \file{tex} file. Both the
  form without class options, \optcode{cls = { article }}, and the form
  with options given through |=|,
  \optcode{cls = { article = { 12pt, a4paper } }} are supported. The
  \fakeverb{\documentclass[12pt,a4paper]{article}} will be generated latter
  at the beginning of the MWE \file{tex} file. The initial value is
  \optcode{article}.
\end{option}

\begin{option}{ opt = pkg, desc = {= \meta{package list}}, init=none }
  The list of packages required by the MWE \file{tex} file. Similar to
  \optcode{cls}, a comma-separated list of packages is given, e.g.
  \optcode{pkg = { tikz, tabularray, listings = { numbers = left } }}.
  The initial value is empty, i.e. no package is added.
\end{option}

\begin{option}{ opt = width, desc = {= \meta{dim}}, init=0pt }
  The width of the code box. The initial value \optcode{0pt} means
  ``not specified'': in the horizontal mode the width is then divided
  equally after subtracting \optcode{sep}, and in the vertical mode
  \tn{textwidth} is used. In the horizontal mode, if the value is so
  large that the right result box would have a negative width, a
  \optcode{width-too-large} warning is issued. The value should be a
  \LaTeX{} dimension, e.g. \optcode{width = 0.35\textwidth}.
\end{option}

\begin{option}{ opt = sep, desc = {= \meta{dim}}, init=18pt }
  The spacing between the left code box and the right result box in
  the horizontal mode; the initial value is \optcode{18pt}. The value
  should be a \LaTeX{} dimension, e.g. \optcode{sep = 0.1\textwidth}.
\end{option}

\begin{option}{ opt = prelabel, desc = {= \meta{prefix}}, init=ex }
  The prefix of the MWE file names and of the automatic
  reference labels; the initial value is \optcode{ex}. For instance,
  the default \verb|label| of the first example is \optcode{ex:1} and
  the corresponding MWE file name is \file{ex1.tex}.
\end{option}

\begin{option}{ opt = pretitle, desc = {= \meta{number prefix}}, init=example }
  The leading word of the example number, used in the first comment
  line of the code box and in the text printed by \tn{ref}; the
  initial value is \optcode{example}. For instance, with
  \verb|pretitle = { Example }| the first comment line is
  ``Example~1.1'' and \tn{ref} also prints ``Example~1.1''. The value
  may contain line breaks, which are converted to spaces. In a
  non-English document it may be changed to an equivalent word in that
  language, e.g. ``example'' or ``demo''.
\end{option}

\begin{option}{ opt = dir, desc = {= \meta{directory}}, init=codes }
  The directory in which the MWE files are saved; the
  initial value is the \file{codes} folder in the current directory.
  \textbf{The given path must already exist}.
\end{option}

\begin{option}{ opt = counter, desc = {= \meta{counter name}}, init=example }
  The counter name; the initial value is \optcode{example}. If the
  given counter name is already in use, a \optcode{counter-exists}
  warning is issued and the option is ignored. Since the package
  creates the counter at \tn{AtBeginDocument}, this option normally
  needs no change.
\end{option}

\begin{option}{ opt = boxtype, desc = {= \meta{box env name}}, init=syntaxbox }
  Selects the box environment used for the code box and the result
  box; the initial value is \env{syntaxbox}. The built-in boxes are
  listed in Table~\ref{tab:codemwe-boxtype-en}. If the given box is
  not registered, an \optcode{unknown-boxtype} warning is issued and
  the box falls back to \env{syntaxbox}.
\end{option}

\begin{option}{ opt = textlang, desc = {= \meta{variety name}}, init=en }
  Selects the language variety. For each variety the \pkg{codemwe}
  package supplies a default transition text, the structural
  used in the MWE file, and the default values of \optcode{cls} and
  \optcode{pretitle}; the \optcode{textlang} option selects which set is
  used. Its value is a variety name and its initial value is
  \optcode{en} (English).

  The package ships with two built-in varieties: \optcode{en}
  (English) and \optcode{zh} (Chinese).
  If the given variety is not registered, an
  \optcode{unknown-textlang} warning is issued and the variety falls
  back to \optcode{en}. Switching the variety is normally done in the
  preamble or at the beginning of the document with \tn{codemweset},
  e.g. \fakeverb{\codemweset\{ textlang = zh \}}. A single example can
  still override the transition text with the \optcode{transition}
  option.

  A new variety is registered with the \tn{codemweNewLang} command;
  see Section~\ref{sec:iface-en}.
\end{option}

\begin{option}{ opt = backend, desc = {= \meta{backend name}}, init=tex }
  Selects the code backend, i.e. the language of the code being
  typeset. The backend determines the extension of the generated
  source file, the comment character used for its first-line comment,
  and whether the code of that language can be compiled by \LaTeX. Its
  value is a backend name and its initial value is \optcode{tex}
  (\LaTeX{} example code).

  The package ships with two built-in backends: \optcode{tex} and
  \optcode{c} (C). With \optcode{c}, a \file{c} source file is
  generated, the first-line comment of the code box uses |//|, and the
  code is not compiled: if the \optcode{result} option is given its image
  is shown, otherwise the result box is omitted and an
  \optcode{backend-no-result} warning is issued. If the given backend is
  not registered, an \optcode{unknown-backend} warning is issued and the
  backend falls back to \optcode{tex}.

  A new backend is registered with the \tn{codemweNewBackend} command;
  see Section~\ref{sec:iface-en}. The backend mechanism is described in
  detail in Section~\ref{sec:backend-en}.
\end{option}

\begin{option}{ opt = minted, desc = {= \meta{true/false}}, init=false }
  Whether the code box is typeset with the \pkg{minted} package so as to
  obtain syntax highlighting. With \optcode{minted}, the code in the box
  is highlighted by \pkg{minted} according to the language name recorded
  by the current backend, at \tn{small} size and with
  \optcode{autogobble} enabled, so that the common indentation is
  removed; line numbers are still controlled by the \optcode{linenos}
  option. The initial value is \optcode{false}, i.e. the original
  \pkg{fancyvrb} scheme is used and no highlighting is applied.

  Given as a package option, every example in the document is
  highlighted; given as an environment option, only the current example
  is highlighted and the setting is restored when the environment ends;
  given through \tn{codemweset}, it applies to all following examples
  until changed back by another \tn{codemweset}. The value
  \optcode{minted = false} thus both turns off package-level highlighting
  and switches off a single place in the body at any time.

  This option requires the \pkg{minted} package and a compilation with
  \optcode{-shell-escape}. This package checks both conditions at load
  time and loads \pkg{minted} straight away if they hold, so the option
  takes effect immediately wherever it is given --- preamble, body or
  environment --- with no need to enable it once in the preamble first.
  If the conditions are not met, the package issues a
  \optcode{minted-unavailable} warning and falls back to the original
  scheme without aborting the run. Since \pkg{minted} inserts only a
  placeholder on the first run by default, two or more runs are needed to
  see the highlighted result.

  See Section~\ref{sec:minted-en} for details.
\end{option}

\begin{option}{ opt = mintedstyle, desc = {= \meta{style name}}, init=default }
  The syntax highlighting style of \pkg{minted}, i.e. a style name of
  \pkg{pygments}; the initial value is \optcode{default}. Common values
  are \optcode{tango}, \optcode{friendly}, \optcode{monokai} and
  \optcode{bw}.

  The option takes effect only when \optcode{minted} is enabled. If it
  is set without \optcode{minted}, the package issues a
  \optcode{mintedstyle-unused} warning but still records the value, so
  that it applies once \optcode{minted} is enabled.
\end{option}

\begin{option}{ opt = title, desc = {= \meta{title}}, init=none }
  The functional title of the example, e.g. ``Draw a line''; the
  initial value is empty. If the current box supports a title bar, the
  title becomes the title bar; otherwise it becomes part of the
  first-line comment of the code box. If a macro such as \tn{tikzset}
  is needed inside \optcode{title}, the \tn{string} primitive must be
  used, i.e. \tn{string}\tn{tikzset}.
\end{option}

\begin{option}{ opt = label, desc = {= \meta{label name}}, init=none }
  The cross-reference label of the example. If it is not given,
  \meta{prelabel}|:|\meta{chapter-number} is generated automatically
  (classes with \tn{chapter}, e.g. \optcode{ex:8-1}), or
  \meta{prelabel}|:|\meta{number} (classes without \tn{chapter},
  e.g. \optcode{ex:1}).
\end{option}

\begin{option}{ opt = filename, desc = {= \meta{file name}}, init=none }
  The name of the MWE file. If it is not given,
  \meta{prelabel}\meta{chapter-number}|.tex| is generated
  automatically (classes with \tn{chapter}, e.g. \file{ex8-1.tex}), or
  \meta{prelabel}\meta{number}|.tex| (classes without \tn{chapter},
  e.g. \file{ex1.tex}). If the \optcode{nonum} option is used at the
  same time, only the environment body is saved to that file.
\end{option}

\begin{option}{ opt = result, desc = {= \meta{figure file}}, init=none }
  The file name of the result figure. Once given, the figure replaces
  the compiled result of the example code and the code is no longer
  compiled. The file name may contain a path (use \optcode{/} as the
  path separator). If the file does not exist, a
  \optcode{result-file-missing} warning is issued, but the compilation
  is not aborted.
\end{option}

\begin{option}{ opt = wd, desc = {= \meta{dim}}, init=0pt }
  The width of the result figure. The initial value \optcode{0pt}
  means ``not specified''. It always takes precedence over
  \optcode{ht} and \optcode{scale}: once \optcode{wd} is given, both
  of them are ignored.
\end{option}

\begin{option}{ opt = ht, desc = {= \meta{dim}}, init=0pt }
  The height of the result figure. The initial value \optcode{0pt}
  means ``not specified''. It takes precedence over \optcode{scale}:
  when \optcode{wd} is not given but \optcode{ht} is, \optcode{scale}
  is ignored.
\end{option}

\begin{option}{ opt = scale, desc = {= \meta{scale factor}}, init=1 }
  The scale factor of the result figure; the initial value is
  \optcode{1}. It is effective only when neither \optcode{wd} nor
  \optcode{ht} is given.
\end{option}

\begin{option}{ opt = transition, desc = {= \meta{transition text}}, init=none }
  Specifies the transition text between the code box and the result
  box in the vertical mode \textbf{for this single example}; the
  initial value is empty. When it is left empty, the global default
  transition text of the language variety selected by \optcode{textlang}
  is used. It may contain commands such as \tn{ref}, e.g.
  \optcode{transition = \{ The result of \tn{ref}\{ex:1\} is shown
  below: \}}.

  \begin{noteen}
    The division of work between \optcode{transition} and
    \optcode{textlang} is:     \optcode{textlang} determines the
    \textbf{default transition text} and the other variety-dependent
    texts of the whole document (settable with \tn{codemweset} or as a
    package option, suitable for switching the variety of a document),
    while \optcode{transition} is a local override for a single
    example. Choose either of them as needed.
  \end{noteen}
\end{option}

\begin{option}{ opt = linenos, desc = {= \meta{true/false}}, init=false }
  Whether line numbers are shown on the left of the code box. With
  \optcode{linenos}, every line of the code box is prefixed with its
  line number, separated from the code by a gap of \optcode{6pt};
  without this option no line numbers are shown. The initial value is
  \optcode{false}.

  The line numbers are implemented with the \optcode{numbers=left}
  option of the \tn{VerbatimInput} command of the \pkg{fancyvrb}
  package. The numbering starts from the first line of the code box
  and is independent of the numbering of the example itself; when
  \optcode{withcls} or \optcode{withpkg} is used, the added document
  class and package content is counted in the line numbers as well.
\end{option}

\section{Notes}

\begin{enumerate}[itemsep=0.3ex]
  \item Only when neither \verb|noshow| nor \verb|nobody| is used are
        the \verb|cls| and \verb|pkg| contents commented out with |%|
        in the code box.
  \item In the horizontal mode, if \verb|width| is too large so that
        the right result box would have a negative width, a
        \verb|width-too-large| warning is issued; decrease
        \verb|width| or \verb|sep| in that case.
  \item The box given by \verb|boxtype| must be registered (built-in
        or via \tn{codemweNewBox}); otherwise an
        \verb|unknown-boxtype| warning is issued and the box falls
        back to \env{syntaxbox}.
  \item If the counter given by \verb|counter| already exists, a
        \verb|counter-exists| warning is issued and the option is
        ignored.
  \item If packages such as \pkg{expl3} or \pkg{tcolorbox} are too
        old, a \verb|package-old| warning is issued; updating the
        \TeX{} distribution is recommended.
  \item If the values of \verb|title|, \verb|label|,
        \verb|transition|, \verb|boxtype| or \verb|pretitle| contain
        line breaks, the breaks are converted to spaces and
        leading/trailing spaces are stripped.
  \item The result figure is inserted with \tn{includegraphics}, so it
        must be in a format supported by \pkg{graphicx} (e.g.
        \file{pdf}, \file{png} or \file{jpg}); \file{eps} is not
        supported when compiling with \XeTeX{}.
\end{enumerate}

\section{Implementation Overview}

The central idea of \pkg{codemwe} is to write the body of the
\env{example} environment into a temporary file
(\file{\meta{jobname}-example.aux}), which is then read back with
\tn{verbatiminput} inside a \pkg{tcolorbox} box to typeset the code
box. The result box either typesets that temporary file in place via
\tn{input} or inserts the figure given by the \verb|result| option.
The MWE file is assembled in the structure and written to the directory given by
\verb|dir|; its file name is determined by \verb|prelabel| and
\verb|counter| (or by the \verb|filename| option).

Internally the package manages its options with the \pkg{l3keys}
mechanism of \pkg{Expl3}: at load time \tn{ProcessKeyOptions} forwards
the \verb|codemwe / pkgopts| key group to the \verb|codemwe| group,
and the \env{example}, \env{example*} and \env{texcode} environments
set their options inside their own groups with \tn{keys_set:nn}, with
the keys preset by the environment (e.g. \verb|vmode = true| for
\env{example*}) providing the defaults. Since each environment body is
processed between \tn{group_begin:} and \tn{group_end:}, the options
of different examples do not interfere with each other. The
variety-dependent texts (the default transition text, the structural
comment words, etc.) are kept together in a single ``variety $\to$
text'' property list, from which the \verb|textlang| option selects;
\tn{codemweNewLang} registers a new variety in that list. For
lower-level details, please refer to the source of
\file{codemwe.sty} directly.

\section{Frequently Asked Questions}

\subsection*{Why is the result box empty?}

If the \verb|result| option is not used, the result box is produced by
\tn{input}-ing the temporary code file; make sure that the example
code itself compiles. If the \verb|result| option is used, make sure
the figure file exists and the path is correct.

\subsection*{Why are the package names in the code box commented out?}

This is the default behaviour of \verb|withpkg| (and \verb|withcls|):
when the compiled result is printed, the document class and the
package content are prepended with the comment sign |%| and serve only
as an explanation. To print them as is, combine with the
\verb|noshow| or \verb|nobody| option.

\subsection*{How do I save the example code as a separate file?}

Use the \verb|nonum| and \verb|filename| options together and only the
environment body is saved to the given file (the path prefix is still
taken from \verb|dir|). Note that the file contains neither the
document class nor the preamble, nor the
\tn{begin}\marg{document}/\tn{end}\marg{document} lines, and cannot be
compiled independently.

\subsection*{Why does the MWE file name differ from the \texttt{label} I set?}

The MWE file name is determined only by \verb|prelabel|,
\verb|counter| and \verb|filename|; the \verb|label| option does not
influence it. \verb|label| only changes the cross-reference label, not
the file name.

\subsection*{I set a title, but no title bar appears.}

Whether a title bar appears depends on the current box type. The
\env{syntaxbox} and \env{syntaxbox*} boxes do not support a title bar;
the number and the title are then written as a first-line comment
inside the code box. To get a real title bar, use \env{mwebox},
\env{mwebox*}, \env{mweparbox} or \env{mweparbox*}.

\subsection*{Why does the result box show no output of the C program?}

C code cannot be compiled by \LaTeX, so the package does not run it;
the result box only shows the image given by the \verb|result| option.
To show the real output, run the generated \file{c} file with a C
compiler first, save the output (or a screenshot of it) as an image,
and include that image with the \verb|result| option. See
Section~\ref{sec:backend-en}.

\end{documentation}

\end{document}
