Right way to write commands and parameters

macrosminted

I was about to ask a question related to what I thought was a bug in the minted package, but I now realise that I'm to blame for not defining commands correctly. I've always believed it was as simple as:

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

But I was wrong: the following shorthands I tried to write duplicate the # character, and things are even worse if I decide to use %, which gets parsed as a LaTeX comment rather than a modulo operator.

\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}

What am I doing wrong, and what is the right way to write these commands?

Best Answer

You can not use verbatim-like commands in the argument or definition of another command.

If you have

\mycommand{zzz % zzz}

Then the % is already seen as a comment (and so the closing } is not seen at all) so zzz % zzz is never passed to the inner minted command.

Such commands need to change the parsing rules before grabbing the argument.

The minted package provides a \newmintinline command to define shortcut commands that call \mintedinline with specific options.

Related Question