如何在文章中使用 lstsample 環境(lstdoc 套件)?

如何在文章中使用 lstsample 環境(lstdoc 套件)?

我想嘗試隨包一起分發的lstsample環境lstdoclistings包裹

為此,我編寫了以下文檔:

\documentclass{article}
\usepackage{lstdoc}
\usepackage{lipsum}

\begin{document}

\begin{lstsample}{}{}
  \color{blue}
  \lipsum[68]
\end{lstsample}

\end{document}

但編譯失敗並顯示以下訊息:

! Undefined control sequence.
\lst@sampleInput ->\MakePercentComment 
                                       \catcode `\^^M=10\relax \small \lst@s...
l.10     \end{lstsample}

我缺什麼?

答案1

lstdoc包主要用於使用該ltxdoc類別的文檔中。該類別doc在內部載入該類,其中包含兩個與此處特別相關的巨集定義:

\def\MakePercentIgnore{\catcode`\%9\relax}
\def\MakePercentComment{\catcode`\%14\relax}

因為lstsample環境需要這兩個宏,但您正在使用的類別article沒有定義它們,所以當您嘗試編譯程式碼時,LaTeX 會正確地將這些宏報告為未定義。在序言中添加上面顯示的兩個定義將解決該問題。

此外,lstsample環境的一個怪癖是,為了讓一切正常運作,其中的所有行必須以 a 開頭,%後面跟著至少 4 個空格。遵守這條規則,你就會幸福。

在此輸入影像描述

\documentclass{article}

\usepackage{lstdoc}
\usepackage{xcolor}
\usepackage{lipsum}

% The following definitions are taken from doc.dtx.
% see http://mirrors.ctan.org/macros/latex/base/doc.dtx
\def\MakePercentIgnore{\catcode`\%9\relax}
\def\MakePercentComment{\catcode`\%14\relax}

\begin{document}

\begin{lstsample}{}{}
%    \color{blue}
%    \lipsum[68]  
\end{lstsample}

\end{document}

相關內容