如何建立一個新命令,其單一參數能夠應用於“lstinputlisting”的“標題”和“路徑”參數

如何建立一個新命令,其單一參數能夠應用於“lstinputlisting”的“標題”和“路徑”參數

我想建立一個命令來簡化使用lstinputlisting套件清單中的命令,該命令可以接受單一參數作為檔案路徑並將其傳遞給 lstinputlisting 的標題和路徑參數。簡而言之,使用檔案路徑作為標題。

考慮以下 LaTeX 來源:

\documentclass[UTF8]{ctexart}
\usepackage{listings}

\newcommand{\myincludecode}[1]{\lstinputlisting[caption=#1, language=matlab]{#1}}
\newcommand{\mysecondincludecode}[2]{\lstinputlisting[caption={#2}, language=matlab]{#1}}


\begin{document}

\myincludecode{main.m}                        % line 10
\myincludecode{gen_data.m}                    % line 11

\mysecondincludecode{main.m}{main.m}          % line 13
\mysecondincludecode{gen_data.m}{gen\_data.m} % line 14

\end{document}

顯然,第 13 行和第 14 行中的命令運作良好,它們都正確包含相應的檔案並列印相應的標題。

10號線也運作良好。然而,第 11 行包含相應的文件,但不輸出標題。日誌檔說:

Try.tex|11 error| Missing $ inserted.
Try.tex|11 error| Extra }, or forgotten $.
Try.tex|11 error| Missing $ inserted.
Try.tex|11 error| Missing } inserted.

很明顯,底線破壞了我的命令。所以,我想知道如何修改myincludecode以使其工作 - 即使遇到一些特殊字符,例如這裡的下劃線。

答案1

去標記化論證:

\documentclass[UTF8]{ctexart}
\usepackage[T1]{fontenc}
\usepackage{listings}

\newcommand{\myincludecode}[1]{\lstinputlisting[caption=\detokenize{#1}, language=matlab]{#1}}

\begin{document}

\myincludecode{main.m}
\myincludecode{gen_data.m} 

\end{document}

在此輸入影像描述

答案2

下劃線mathmode有一個功能。它將下一個字元更改為下標。因此它期望有一個$跡象。這是解決您問題的簡單方法。

\documentclass[UTF8]{ctexart}
\usepackage{listings}

\begin{document}
\begingroup
\newcommand{\myincludecode}[1]{\catcode`_=11\lstinputlisting[caption=#1, language=matlab]{#1}}
\myincludecode{main.m}
\myincludecode{gen_data.m}
\endgroup
$1_2$
\end{document}

Catcode是類別代碼的意思。類別_是 8,它為它分配了一些功能,如果我將其更改為 11,它將下劃線更改為字母類別,這可能是您想要的。在\begingroup&之間加入此命令\endgroup可以使下標函數在其作用域之外保持不變。

答案3

您必須避免在檔案名稱和 cite 或 ref 標籤中使用“_”,或者您必須使用 babel 套件及其活動字元控件,或者您必須提供 [strings] 選項,該選項會嘗試重新定義多個命令(並且可能會不能完美工作)。即使沒有 [strings] 選項或 babel,您也可以偶爾使用底線,例如:「\include{file\string_name}」。

預設操作非常簡單,無需自訂;但是在 LaTeX 將參數用作某些控制函數的字串或名稱的任何地方,您必須避免使用“_”。其中包括 \cite 和 \ref 的標籤、\input、\include 和 \includegraphics 的檔案名稱、環境名稱、計數器名稱和放置參數(如 [t])。這些上下文的問題在於它們是“移動參數”,但 LaTeX 不會為它們“打開”“\保護機制”。

如果需要在這些地方使用下劃線字符,可以提供包選項 [strings] 來重新定義採用此類字串參數的命令,以便套用保護(將 \protect 改為 \string)。此規定影響的命令清單在 \UnderscoreCommands 中給出,每個命令之前都有 \do ;加上其他幾個涵蓋 \input、\includegraphics、\cite、\ref 及其變體。

請參見 -http://ctan.imsc.res.in/macros/latex/contrib/underscore/underscore.pdf 和 -名稱/路徑中帶有底線的檔案列表

在此輸入影像描述 在此輸入影像描述

相關內容