正确编写命令和参数的方法

正确编写命令和参数的方法

我原本想问一个与我认为是软件包中的错误有关的问题minted,但现在我意识到我应该为没有正确定义命令负责。我一直认为它很简单:

\newcommand{\mycommand}[1]{do some stuff with parameter #1}

但我错了:我尝试编写的以下简写重复了字符#,如果我决定使用,情况会变得更糟%,它会被解析为 LaTeX 注释而不是模运算符。

\documentclass[a4paper,12pt]{article}

\usepackage{minted}
\newcommand{\shellinline}[1]{\mintinline{shell}{#1}}
\newcommand{\pythoninline}[1]{{\mintinline{shell}{#1}}}

\begin{document}

\noindent This is a ``shell comment'' with mintinline: \mintinline{shell}{# comment} % prints # comment

\noindent This is a ``shell comment'' with my command: \shellinline{# comment} % prints ## comment

\noindent This is a ``python comment'' with mintinline: \mintinline{python}{# comment} % prints # comment

\noindent This is a ``python comment'' with my command: \pythoninline{# comment} % prints ## comment

\end{document}

我做错了什么?如何正确编写这些命令?

答案1

您不能在另一个命令的参数或定义中使用逐字命令。

如果你有

\mycommand{zzz % zzz}

然后%已经被视为注释(因此}根本看不到结束),所以zzz % zzz永远不会传递给内部的 minted 命令。

此类命令需要改变解析规则抓住论点。

minted包提供了一个命令来定义使用特定选项\newmintinline调用的快捷命令。\mintedinline

答案2

David Carlisle 已经解释过,诸如\mintinline在获取参数之前改变解析规则之类的评论,您可以使用\newmintinline

但是,在您的特殊情况下,您可以定义\shellinline\pythoninline以某种方式获取要更改其解析规则的参数,该参数由 -command\mintinline而不是由用户定义的命令获取:

\documentclass[a4paper,12pt]{article}

\usepackage{minted}
\newcommand{\shellinline}{\mintinline{shell}}
\MakeRobust\shellinline
\newcommand{\pythoninline}{\mintinline{python}}
\MakeRobust\pythoninline

\begin{document}

\noindent This is a ``shell comment'' with mintinline: \mintinline{shell}{# comment} % prints # comment

\noindent This is a ``shell comment'' with my command: \shellinline{# comment} % prints # comment

\noindent This is a ``python comment'' with mintinline: \mintinline{python}{# comment} % prints # comment

\noindent This is a ``python comment'' with my command: \pythoninline{# comment} % prints # comment

\noindent This is a ``shell comment'' with mintinline: \mintinline{shell}{% comment} % prints % comment

\noindent This is a ``shell comment'' with my command: \shellinline{% comment} % prints % comment

\noindent This is a ``python comment'' with mintinline: \mintinline{python}{% comment} % prints % comment

\noindent This is a ``python comment'' with my command: \pythoninline{% comment} % prints % comment

\end{document}

在此处输入图片描述

相关内容