首页 > 解决方案 > 带有逐字或列表的 LaTeX 新命令:`#` 问题(哈希键)

问题描述

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

我是宏的新手,所以我尝试了一些简单的方法:它适用于 \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)中使用这些环境吗?

提前致谢

标签: macroslatexspecial-characterslistingsverbatim

解决方案


逐字逐句的内容很棘手。您必须问自己的意图是什么。如果是打印代码,那么山中之王就是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}

推荐阅读