在 \fbox 中使用 lstlistings 环境

在 \fbox 中使用 lstlistings 环境

我的文档中使用了一个函数:

\documentclass{article}
% Change "article" to "report" to get rid of page number on title page
\usepackage{amsmath,amsfonts,amsthm,amssymb}
\usepackage{setspace}
\usepackage{Tabbing}
\usepackage{listings}
\usepackage{fancyhdr}
\usepackage{lastpage}
\usepackage{caption}
\usepackage{epstopdf}
\usepackage{Pgfplots}
\usepackage[]{mcode}
\usepackage{tikz}
\usetikzlibrary{shapes,arrows}
\usepackage{extramarks}
\usepackage{chngpage}
\usepackage{soul,color}
\usepackage{graphicx,float,wrapfig}

% In case you need to adjust margins:
\topmargin=-0.45in      %
\evensidemargin=0in     %
\oddsidemargin=0in      %
\textwidth=6.5in        %
\textheight=9.0in       %
\headsep=0.25in         %


\newcommand{\sectionAnswer}[1]
  {% We put this space here to make sure we're disconnected from the previous
   % passage

   \noindent\fbox{\begin{minipage}[c]{\columnwidth}#1\end{minipage}}%
   \enterProblemHeader{\homeworkProblemName}\exitProblemHeader{\homeworkProblemName}%
   \marginpar{\fbox{\homeworkSectionName}}%

   % We put the blank space above in order to make sure this
   % \marginpar gets correctly placed.
   }%

然后我稍后使用(我只想添加几行 MATLAB 代码,因此请注意使用了包 mcode):

\sectionAnswer{
\begin{lstlisting}
a = 1;
b = 2;
c = a^2 + b^2;
\end{lstlisting}
}

我知道这是因为列表(包括逐字内容)不能作为参数传递给其他函数/宏……所以我在寻找解决方法?理想情况下,我不想修改原始宏,因为它确实运行得很好。所以,如果我确实修改了它,\fbox就需要用具有相同属性的东西来替换它。


根据 Werner 的建议,宏观现在是:

\newcommand{\sectionAnswer}[1]
  {% We put this space here to make sure we're disconnected from the previous
   % passage

   \noindent\fbox{\begin{minipage}[c]{\dimexpr\linewidth-2\fboxsep-2\fboxrule}#1\end{minipage}}
 % modify page width from \columnwidth to \dimexpr\linewidth-2\fboxsep-2\fboxrule
   \enterProblemHeader{\homeworkProblemName}\exitProblemHeader{\homeworkProblemName}%
   \marginpar{\fbox{\homeworkSectionName}}%

   % We put the blank space above in order to make sure this
   % \marginpar gets correctly placed.
   }%

我还应该注意,这是一个修改后的模板,基于泰德·帕夫利克

答案1

如果您希望保留当前设置,那么您可以在lstlisting将其传递给之前将其存储在一个盒子里\sectionAnswer

\newsavebox{\codebox}% For storing code in a box

\begin{lrbox}{\codebox}
\begin{lstlisting}
a = 1;
b = 2;
c = a^2 + b^2;
\end{lstlisting}
\end{lrbox}

\sectionAnswer{%
\usebox{\codebox}%
}

请注意,您的minipage宽度最好设置为\dimexpr\linewidth-2\fboxsep-2\fboxrule

相关内容