12

How can I modify the following command to make it work?

\newcommand{\code}[1]{\begingroup \fontsize{10pt}{10pt}\selectfont \begin{verbatim} #1 \end{verbatim} \endgroup}

I currently get the following error on the close of the following verbatim block:

! Undefined control sequence.
<argument> ...endgroup ^^M^^M$\eta_{xi} = r_{xi} -
                                                   q_i \cdot p_x$ \\^^M$q_i ...
l.227     \end{verbatim}
1

4 Answers 4

10

listings is the de-facto standard for typesetting of code these days and offers syntax highlighting and font selection, amongst other things; fancyvrb might be easier to handle for your use case.

To answer your more immediate question: you can't put the argument of a command into a verbatim environment, verbatim needs to change the way text is read and it's too late for that then.

20

You can also place the verbatim environment inside a small environment:

\begin{small}
\begin{verbatim}
\LaTeX
\end{verbatim}
\end{small}

Source: https://www.namsu.de/latex/kapitel5.html

4
  • 2
    Not really. Without a blank line before \begin{small} you get wrong line spacing in the text above the verbatim material.
    – egreg
    Commented Nov 2, 2018 at 11:52
  • 2
    Also small is not an environment... Commented Nov 2, 2018 at 13:04
  • 3
    Thanks. I can confirm that this answer works. You can also do \begin{footnotesize}. Commented Apr 26, 2021 at 3:07
  • 2
    I confirm that it works for \begin{footnotesize}
    – TrungDung
    Commented Apr 3, 2023 at 19:59
10

You can use the verbatim environment; just patch it so that it selects a smaller font. In the example I use \small which is 9pt, 10pt or 11pt when the main font size is 10pt, 11pt or 12pt respectively.

Instead of \small you can substitute any other \fontsize{X}{Y}\selectfont instruction, but keep in mind that Y stands for the baseline skip, which should be larger than the font size X.

\documentclass{article}
\usepackage{etoolbox}
\makeatletter
\patchcmd{\@verbatim}
  {\verbatim@font}
  {\verbatim@font\small}
  {}{}
\makeatother

\begin{document}
This is text to show the font size
\begin{verbatim}
This is smaller
\end{verbatim}
Some other text
\end{document}

Explanation: \verbatim@font selects the typewriter type font; by adding \small we force it to another size.

enter image description here

Just to make clearer that it works, I repeat the output with \tiny instead of \small:

enter image description here

3

The verbatimbox package can take optional arguments, such as \fontsize.

\documentclass{article}
\usepackage{verbatimbox}
\begin{document}
\begin{verbnobox}[\fontsize{8pt}{8pt}\selectfont]
Thi$ i$ my \/erbatim
text
\end{verbnobox}
\begin{verbnobox}[\fontsize{12pt}{12pt}\selectfont]
Thi$ i$ my \/erbatim
text
\end{verbnobox}
\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .