[Tex/LaTex] How to make a text { in alltt

verbatim

I am trying to type computer code in my document using the alltt environment. Some symbols, such as ' and {, do not appear in the document the way they do in the code. I solved the problem with ' by using the upquote package. But I still have a problem with { and }; these symbols are taller than the surrounding text in the alltt environment. For example,

\documentclass{article}
\usepackage[margin=2cm]{geometry} %set margins
\usepackage{color}
\usepackage{alltt}
\usepackage{upquote}

\begin{document}

    \begin{alltt}
    for (i in 1:3){
        print(i^2)
        }
    \end{alltt}

\end{document}

doesn't do what I want (since the braces do not appear), and neither does using \{ and \} in place of { and } (the braces are too tall). I think this question is something similar, but I do not understand the answers given there.

Best Answer

The alltt environment is a kind of "semiverbatim": it uses the typewriter font, but still \, { and } maintain their meaning, for being able to use commands (say for changing color, fonts or whatever).

For real verbatim, use the verbatim environment:

\documentclass{article}
\usepackage{upquote}

\begin{document}

\begin{verbatim}
for (i in 1:3){
     print(i^2)
    }
\end{verbatim}

\end{document}

enter image description here

Limitation: you shouldn't "globally" indent it; all spaces at the beginning of lines are honored, so begin at the left margin and indent as much as you want inside the environment.

More features are provided by the fancyvrb package. Still many more are available with the very powerful listings package.

Related Question