1

How can I place \lstinline code inside commands like \chapter, \section, \subsection, etc.?

Or it's a bad or tasteless practice?

  • It's not usually a good idea. Why are you wanting to do that? – Teepeemm Oct 29 '21 at 21:46
  • @Teepeemm: Same reasons listings is used in other places, highlight code from normal text. For example, a section could be named: Use of while keyword. – Alberto López Oct 29 '21 at 21:53
  • You can, just use \protect\lstinline!...! since the argument of the titles are moving and therefore fragile. – Werner Oct 29 '21 at 22:24

1 Answers1

3

You can, as long as you \protect moving arguments:

enter image description here

enter image description here

\documentclass{report}

\usepackage{listings} \lstset{ basicstyle=\ttfamily }

\begin{document}

\tableofcontents

\chapter{The \protect\lstinline!if! command}

\section{The \protect\lstinline!while! command}

\subsection[More commands]{The \lstinline!end! command}

\end{document}

Werner
  • 603,163
  • I have something more difficult here if you have time: place text with \lstinline code inside \item description AND automatically add the \item content to a glossaries entry. – Alberto López Oct 30 '21 at 22:36
  • Sorry @Werner, it almost works, only fails with the characters %#&, etc. – Alberto López Nov 18 '21 at 21:39
  • @AlbertoLópez: It works when I use \% or \#. – Werner Nov 18 '21 at 21:57
  • I mean %#& simbols as code in \lstinline. – Alberto López Nov 19 '21 at 15:15
  • @AlbertoLópez: Me too. See this code that produces this output. – Werner Nov 19 '21 at 17:07
  • Ok, I just saw the error in my code, thanks. – Alberto López Nov 20 '21 at 18:24
  • I also see this kinds of error when I try to use \lstinline|MOV A, #12H| in the choice items of this https://tex.stackexchange.com/a/141643/24012, the result is that I see two ## in the rendered output. Luckily, I find the answer here. I just try to use this \protect\lstinline|MOV A, \#12H|, and the problem is gone, I mean the rendered text is correct. But I see this is still a bit complex, any better solutions? BTW, I think Werner's code mentioned here https://pastebin.com/raw/DDWm7FRP should be added to the answer. – ollydbg23 Feb 09 '23 at 09:05