# How can I use \\ with \texttt inside a node?

Take the following MWE:

I made this node with tikz using the normal font:

However, I need to use a monospaced font to get the following result:

Since the node has two lines of text, I would normally do \texttt{line1\\line2}. However when I compile it I get lots of errors.

If I do \texttt{line1}\\\texttt{line2} it compiles with no errors.

Why can't I use \\ inside \texttt{}? Is there a solution to avoid putting \texttt{} on every line of text?

\documentclass{standalone}

\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\node[draw,rectangle,align=center] {line1\\line2};
\end{tikzpicture}
\end{document}

• Try {\ttfamily text1\\ text2} – Sigur Jan 18 '17 at 20:35
• Why not \node[draw,rectangle,align=center,font=\ttfamily] {line1\\line2};? – clemens Jan 18 '17 at 20:36
• @Sigur I tried that already, but it only affects to the first line of text. The second line remains with the normal font. – codeaviator Jan 18 '17 at 20:37
• Primarily this is similar to Manual/automatic line breaks and text alignment in TikZ nodes – Werner Jan 18 '17 at 22:12

Why this use of \texttt doesn't work in node text is explained in section 17.4.3 of the pgfmanual.
When the node text is parsed, the command \\ is redefined internally. This redefinition is done in such a way that the text from the start of the node to the first occurrence of \\ is put in an \hbox. Then the text following \\ up to the next \\ is put in another \hbox.
Thus writing \texttt{line1\\line2} in a node will result in two \hboxes, the first containing \texttt{line, the second containing line2}, neither of which will parse correctly.
The above description also shows why the suggestion of writing \ttfamily line1\\ line2 only produces typewriter font on the first line.
As clemens points out the easiest way to use the typewriter font for the whole node is to pass the argument font=\ttfamily to the node.
• Thanks a lot Andrew for your contribution! Now I understand the reason for the errors. Thanks also for pointing me to the relevant section of the pgfmanual. By the way, I think clemens should be credited instead of me :-) – codeaviator Jan 18 '17 at 22:17