如何快速更改 lstlisting 的间距以使用两个空格而不是四个空格?

如何快速更改 lstlisting 的间距以使用两个空格而不是四个空格?

我正在处理一些 LaTeX 代码列表,并决定将间距从 4 改为 2。问题是我的文档(约 500 页)中有大量列表... 有什么方法可以快速重新格式化所有列表以使用 2 个空格而不是 4/8/12/...?

答案1

您可以使用literate键将四个连续的空格变成两个输出空格:

\documentclass{article}

\usepackage{listings}
\lstset{literate={\ \ \ \ }{\space\space}{2}}

\begin{document}
\begin{lstlisting}[language=python]
if x is None:
    print('yes')
   # just a quick test that 3 spaces aren't touched
     # just a quick test that 5 spaces are touched
\end{lstlisting}
\end{document}

在此处输入图片描述

八个空格的块与两个四个空格的块相同,通过literate密钥进行上述替换将起作用。如果您需要更多替换,您可以简单地添加它们,密钥literate将任意多的替换规则作为三个参数的块(要替换的内容、替换、替换将占用的虚拟列数)。

\documentclass{article}

\usepackage{listings}
\lstset
  {
    literate=
      {\ \ \ \ }{\space\space}{2}
      {yes}{no}{2}
  }

\begin{document}
\begin{lstlisting}[language=python]
if x is None:
    print('yes')
    if y is None:
        print('yes again')
   # just a quick test that 3 spaces aren't touched
     # just a quick test that 5 spaces are touched
\end{lstlisting}
\end{document}

在此处输入图片描述

相关内容