【问题标题】:LaTeX newcommand with verbatim or listings : problem with `#` (hash key)带有逐字或列表的 LaTeX 新命令:`#` 问题(哈希键)
【发布时间】:2019-06-12 13:17:16
【问题描述】:

我正在尝试使用verbatimlistings 环境定义带有\newcommand 的宏。由于verbatimlistings#1(代表参数)中的哈希键似乎被转义了。

我是宏的新手,所以我尝试了一些简单的方法:它适用于\begin{center} ... \end{center}

\documentclass[a4paper,oneside,11pt]{report}
\newcommand{\script}[1]{
  \begin{center}
    #1
  \end{center}
}
\begin{document}
  \script{blabla}
  blibli
\end{document}

当我将 center 替换为 verbatim 时,我收到此错误:

扫描使用@xverbatim 时文件结束。

lstlisting

列表开始后删除的文本

我在 stackoverflow 和 https://tex.stackexchange.com 上都没有找到任何东西:你会建议在宏中使用这些环境(\newcommand 还是 \newenvironment)?

提前致谢

【问题讨论】:

标签: macros latex special-characters listings verbatim


【解决方案1】:

逐字逐句的内容很棘手。您必须问自己的意图是什么。如果是打印代码,那么山中之王就是listings。我建议并为大量特定于代码的输出定义自己的环境。

这是一个例子:

\documentclass{article}

\usepackage{listings}

\lstnewenvironment{code}[1][]
  {\lstset{#1}}% Add/update settings locally
  {}

\lstset{% Global options
  frame = single,
  basicstyle = \ttfamily\small,
  language = PHP
}

\begin{document}

My first PHP ``Hello World'' page:

\begin{code}
<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <?php echo '<p>Hello World</p>'; ?> 
 </body>
</html>
\end{code}

When you write \lstinline!<title>PHP Test</test>!, it sets the \textit{title} of the page.

\end{document}

【讨论】:

  • 非常感谢 Werner,您说服我了解更多关于 listings 的信息。不知道\lstinline。您能否解释一下{\lstset{#1}} 的语法:这是否意味着我可以添加一个选项作为参数?
  • @vvffl:是的。我将code 定义为可以采用可选参数的环境。所以你可以打电话(比如说)\begin{code}[language = bash]...\end{code} 来切换language。根据语言定义 style 对您来说可能是理想的(样式包括颜色和其他格式规范)。
  • 谢谢,这正是我的想法(我的 tex 文件中有一篇旧论文,我在其中使用了自定义语法颜色的 xml,所以我要先“grep”)。所以宏并不难,但语法对我来说仍然很奇怪。
  • @vvffl:这是一个常见的要求,但没有得到很好的支持。请参阅Viewer-independent copyable spaces at the beginning of a line? 输出(在生成的 PDF 中)不包括空格的事实,它们不能用于复制和粘贴。因此,不保留缩进。 (La)TeX 的目的是生成精美的文档,因此可能不完全支持将内容复制/粘贴到其他地方的“反向”。
【解决方案2】:

使用\verb 命令找到verbatim 的解决方法,并使用波浪号作为分隔符(如果我想在脚本中使用波浪号,我必须使用\textasciitilde):

\documentclass{article}

\newcommand{\scr}[1]{
    \begin{minipage}{0.9\textwidth} 
        \fbox{
            \parbox{\textwidth}{            
                \verb~#1~               % <-- HERE
            }
        }
    \end{minipage}  
}   

\begin{document}        
    \scr{Some script code here... 

    here a tilde : \textasciitilde
    }
\end{document}

但是listings 什么都没有...


编辑: 我刚刚注意到这种解决方法不会让“自动”字符转义,所以这不是我想要的。我希望能够在不转义特殊字符的情况下粘贴代码。

【讨论】:

  • 这不起作用。在verbatim 设置中(在verbatim 环境或\verb 中),\textasciitilde 之类的宏不会扩展为它们的含义,因为\ 已更改为表示字符。因此,您的输出应包含\textasciitilde,而不是~
  • 感谢您的回复。实际上它确实适用于我的安装......不知道如何也不知道为什么!
猜你喜欢
  • 1970-01-01
  • 2010-11-26
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
  • 2013-12-30
  • 2020-05-31
  • 1970-01-01
相关资源
最近更新 更多