在宏内部使用逐字环境

时间:2009-11-05 10:35:02

标签: latex

我想要定义一个带有三个参数的宏:一个字符串和两个代码段。 我的第一个想法是使用逐字环境显示代码段,但是这会因错误消息而失败

! File ended while scanning use of \@xverbatim.

相反,我提出了以下宏。

\newcommand{\definematlabfunction}[3]{
    \noindent
    \begin{minipage}{\textwidth}
        \noindent
        #1 \vspace{0.2cm} \\
        Function definition: \\
        \texttt{#2} \vspace{0.2cm} \\
        Example usage of the function: \\
        \texttt{#3} \\
    \end{minipage}
}

目前我使用此宏如下所示。

\definematlabfunction
{Create a function which takes one input argument (a list of numbers) 
and returns the last five elements of this list. If the list does not contain 
five elements, the function should display a warning.}
{function res = lastFiveElements(list)}
{>> lastFiveElements(1:10) \\
ans = [6, 7, 8, 9, 10] \\
>> lastFiveElements(7:10) \\
warning}

我可以以某种方式避免双反斜杠(\),同时仍能获得正确的代码格式吗?

2 个答案:

答案 0 :(得分:4)

首先,您应该定义主宏

\def\definematlabfunctionMain#1#2#3{    
\noindent    
\begin{minipage}{\textwidth}        
\noindent        
 #1 \vspace{0.2cm} \\        
 Function definition: \\        
 \texttt{#2} \vspace{0.2cm} \\        
 Example usage of the function: \\        
 \texttt{#3} \\    
\end{minipage}} 

然后,您可以使用\definematlabfunction

定义\definematlabfunctionMain
\makeatletter 
\def\definematlabfunction#1{\def\tempa{#1}\begingroup 
  \let\do\@makeother \dospecials \catcode`\{=1 \catcode`\}=2 \obeylines \@vobeyspaces
  \definematlabfunctionplus}
\def\definematlabfunctionplus#1#2{\definematlabfunctionMain{\tempa}{#1}{#2}\endgroup}
\makeatother

现在不需要\\

\definematlabfunction{Create a function which takes one input argument (a list of
numbers) and returns the last five elements of this list. If the list does not contain
five elements, the function should display 
a warning.}{function res = lastFiveElements (list)}{>> lastFiveElements(1:10)
ans = [6, 7, 8, 9, 10] 
>> lastFiveElements(7:10) 
warning}

答案 1 :(得分:2)

听起来你需要fancyvrb包。