在不同環境中的多個位置重複文字(lstlisting?)?

在不同環境中的多個位置重複文字(lstlisting?)?

各位——

我有一個問題,我不知道如何解決。我正在將我的考試問題匯總在一個 pdf 中,我想與其他也使用 LaTeX 的老師分享。問題在於,雖然 LaTeX 提供了一個漂亮的 pdf,但如果其他人想使用我的問題,將 pdf 複製/貼上到不同的 TeX 檔案中可能會非常困難。當然,我會在自己的小問題文件中提供每個問題的源代碼,但是深入整個資料夾或單個文件來查找特定問題可能會有點痛苦。

我知道──這些似乎是微不足道的抱怨,不值得,而且大多是懶惰的產物。但如果這些問題能夠解決,那麼與其他人一起解決這個問題就會更不容易出錯,並且在未來審查、複製和修改問題時會更順利。

我希望能夠做類似的事情:

\documentclass[options]{exam}

\usepackage{graphicx}
\usepackage{tikz}
\tikzlibrary{blahblah}
\usepackage{listings}
\usepackages{any other necessary packages to make this work}

\begin{document}

\begin{questions}

\some-command-to-duplicate-question,but-in-a-lstlistings-sort-of-environment{%
\question A question?

\begin{solution}
The solution
\end{solution}
}

\same-command-as-before{%
\includegraphics{diagramforquestion}%could also be for Tikz drawings, tables, other figures, etc

\question Another question?

\begin{solution}
Another solution.
\end{solution}
}

\end{questions}

\end{document}

這樣,在 pdf 就會有:

  • 問題列表,附有由 LaTeX 正確排版的圖表等;

  • 一些 lstlistings 或類似的環境,顯示該問題的原始碼。

顯然,我可以將問題的文字複製/貼上到列表環境中,但如果進行任何更改,與我合作對問題進行更改的人(或者更有可能的是我)將必須記住複製第二個環境中的所有更改,而如果有某種方式發出某些命令或重新定義此概要的某些環境,它將在其中排版輸出原始程式碼以便於複製,只需要修改一處,這將使各個問題檔案變得更加乾淨並且隨著時間的推移更容易維護。

感謝大家提供的任何幫助!

答案1

兩個都input都是lstinputlisting你在這裡的朋友。

您也可以修改\question命令以包含解決方案的文件,唯一的問題是它們是否被使用,因為\input它們必須是有效的 TeX。

\documentclass[10pt]{article}

\usepackage{graphicx}
\usepackage{tikz}
\usepackage{listings}
\lstset{basicstyle=\footnotesize\ttfamily,breaklines=true}

\newcommand{\question}[4]{
    #1

    The question is

    \begin{center}
        \input{#2}
    \end{center}

    For copy-pasting, the question is

    \lstinputlisting{#2}

    The solution is here:
    \begin{center}
        #3
    \end{center}

    #4
}

\begin{document}

Introduction

\begin{enumerate}
    \item \question{For undergraduates:}{q1}{My solution}{
        A figure to help explain

        \begin{tikzpicture}
        \draw (0,0) -- (2,0) -- (2,2) -- (0,0);
        \end{tikzpicture}
    }
    \item \question{For grad students:}{q1}{Another solution}{No figure needed for grad students}
\end{enumerate}


\end{document}

為了使其成為真正的 MWE,我q1.tex在同一目錄中調用了一個文件,如下所示:

If $n = 3$, $x^n + y^n = z^n$ has no integer solutions. If you have extra time, please prove this for all other $n > 2$.

相關內容