开发者

Use of the verbatim environment inside a macro

I latex i want to define a macro which takes three arguments: a string and two code segments. My first idea were to display the code segments using the verbatim environment, but this fails horribly with the error message

! File ended while scanning use of \@xverbatim.

Instead I have come up with the following macro.

\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}
}

Currently I use this macro like below.

\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}

Can I somehow avoid the double backslashes (\) while still getting the correct code formatting?


First of all you should define your main macros

\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}} 

Then you can define \definematlabfunction using \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

Now no \\ is needed.

\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}


It sounds like you need the fancyvrb package.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜