如何格式化长段代码

如何格式化长段代码

(原标题:《在对齐环境中设置字体》。)

问题

我想默认在任何地方创建一个align带有(或更一般地说,任何字体)的环境。\texttt

动机

R我在大学二年级课程的统计模块作业报告附录中展示了代码。目前我是这样写的:

\begin{align*}
    & \texttt{some code} \\
    & \texttt{some more code} \\
    & \texttt{yet still more further code} \\
    & \texttt{this gets pretty inconvenient over many lines, especially} \\
    & \hspace{1em} \texttt{if I have to break a line of code over two lines.}
\end{align*}

迄今为止的尝试

帖子展示了如何定义自定义字体环境,但我不知道如何将其应用到环境中align

\documentclass{article}
\usepackage{amsmath}
\newenvironment{myfont}{\fontfamily{lmtt}\selectfont}{\par} % from the post
\newenvironment{mycodeA}{\fontfamily{lmtt}\selectfont\begin{align*}}{\end{align*}} % what I want, attempt 1
\newenvironment{mycodeB}{\begin{align*}\fontfamily{lmtt}\selectfont}{\end{align*}} % what I want, attempt 2
\begin{document}
\begin{myfont}hi\end{myfont} % works
\begin{mycodeA}hi\end{mycodeA} % doesn't work
\begin{mycodeB}hi\end{mycodeB} % doesn't work
\end{document}

解决方案

我的特殊问题解决了

\newenvironment{mycode}{\begin{quote}\fontfamily{lmtt}\selectfont}{\end{quote}}

根据@egreg 的建议。但是,@chsk 针对更普遍的情况提出了更强大的解决方案。我已重命名该帖子以反映重点的变化。

答案1

这不是对您的问题的直接回答,但(我希望)是对您要解决的更大问题的回答:在家庭作业、论文或类似的东西中呈现代码。

为此,我认为最好求助于提供语法高亮、格式化等功能的专用包,例如包listings。以下示例使用 Google 找到的随机 R 示例代码片段(我不使用 R),以及取自这个答案在 stackoverflow.com 上

\documentclass{article}
\usepackage{listings}
\usepackage[dvipsnames]{xcolor}
\lstset{ 
  language=R,                     % the language of the code
  basicstyle=\tiny\ttfamily, % the size of the fonts that are used for the code
  numbers=left,                   % where to put the line-numbers
  numberstyle=\tiny\color{Blue},  % the style that is used for the line-numbers
  stepnumber=1,                   % the step between two line-numbers. If it is 1, each line
                                  % will be numbered
  numbersep=5pt,                  % how far the line-numbers are from the code
  backgroundcolor=\color{white},  % choose the background color. You must add \usepackage{color}
  showspaces=false,               % show spaces adding particular underscores
  showstringspaces=false,         % underline spaces within strings
  showtabs=false,                 % show tabs within strings adding particular underscores
  frame=single,                   % adds a frame around the code
  rulecolor=\color{black},        % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. commens (green here))
  tabsize=2,                      % sets default tabsize to 2 spaces
  captionpos=b,                   % sets the caption-position to bottom
  breaklines=true,                % sets automatic line breaking
  breakatwhitespace=false,        % sets if automatic breaks should only happen at whitespace
  keywordstyle=\color{RoyalBlue},      % keyword style
  commentstyle=\color{YellowGreen},   % comment style
  stringstyle=\color{ForestGreen}      % string literal style
}
\begin{document}
\begin{lstlisting}
num = as.integer(readline(prompt="Enter a number: "))
factorial = 1
if(num < 0) {
    print("Sorry, factorial does not exist for negative numbers")
} else if(num == 0) {
    print("The factorial of 0 is 1")
} else {
    for(i in 1:num) {
        factorial = factorial * i
    }
    print(paste("The factorial of", num , "is", factorial))
}
\end{lstlisting}
\end{document}

在此处输入图片描述

R 代码的呈现方式相当易于调整,并且调用有据可查\lstset,因此它应该是一个有用的起点。

答案2

如果不需要语法着色,则可以使用fancyvrb

\documentclass{article}
\usepackage{fancyvrb,upquote}

\usepackage{lipsum} % for context

\DefineVerbatimEnvironment{Rcode}{Verbatim}{xleftmargin=\parindent,fontsize=\small}

\begin{document}

\lipsum[1][1-3]
\begin{Rcode}
num = as.integer(readline(prompt="Enter a number: "))
factorial = 1
if(num < 0) {
    print("Sorry, factorial does not exist for negative numbers")
} else if(num == 0) {
    print("The factorial of 0 is 1")
} else {
    for(i in 1:num) {
        factorial = factorial * i
    }
    print(paste("The factorial of", num , "is", factorial))
}
\end{Rcode}
\lipsum[2][3-6]

\end{document}

在此处输入图片描述

相关内容