I am wondering if it is still possible to print characters chosen to be moredelim
in \lstdefinestyle
. It turns out that since I've defined a character as moredelim
, it can only be used inside quotes or comments with no obvious way to escape it. Here is some code to help understanding what I mean:
% !TEX encoding = UTF-8 Unicode
\documentclass{article}
\usepackage{listings,xcolor}
\usepackage[T1]{fontenc}
\usepackage{verbatim}
\newcommand{\listingsfont}{\fontfamily{courier}}
\lstdefinestyle{test}{
language={sh},
moredelim=**[is][\color{red}]{~}{~},
basicstyle=\ttfamily,
}
\begin{document}
I want to highlight first two command arguments in the following code:
\begin{verbatim}
$ ./my-command some-dir some-dir2 some-other-argument
$ ./my-command ~/Desktop ~/Documents some-other-argument
\end{verbatim}
What I get:
\begin{lstlisting}[style=test]
$ ./my-command ~some-dir~ ~some-dir2~ some-other-argument
$ ./my-command ~"~/Desktop"~ ~~./Documents~ some-other-argument
# ~ is not shown before ./Documents because of being used in moredelim,
# but it can be still printed in comments / inside strings.
\end{lstlisting}
\end{document}
Of course, in my simple example I can overcome the problem by using some other characters instead of ~, but when it comes to a document with several hundred pages and lots of listings, it's good to know that whatever moredelims you choose, you won't put yourself into a trap.
How can I keep ~ (or any other character) as moredelim
, but still be able to print it when needed?
:)
How islistings
supposed to know when~
should be printed or act as a delimiter? Choose your delimiters carefully, ones that have no chance of appearing in your code. You can even choose exotic sequences of characters formoredelim
, such as<<@<<
and>>@>>
to reduce that risk.moredelim
too often. But if you want to highlight something frequently, your code becomes unreasonably cluttered.