[Tex/LaTex] Latex doesn’t break spaces in \texttt correctly (Overfull \hbox)

line-breakingtypewriter

I'm having some text in an \texttt environment and it turns out that latex breaks the lines in these environments sometimes correctly and sometimes not.

A working minimum example

\documentclass{scrartcl}
\begin{document}
\section{Test}

This is some text text and even more text \texttt{and some variable names which are written in typewriter font

\end{document}

And a non-working one (leading to an overfull \hbox)

\documentclass{scrartcl}
\begin{document}
\section{Test}

This is some text text and even more text \texttt{and some variable names which are writtenin typewriter font}

\end{document}

It seems like if there is an too long word at the end of the line LaTeX isn't capable of setting a proper line break? I've found some similar problems with line breaks in \texttt, but the problem was always that there was no space in the \texttt, this is definitely not the problem here.

Is there a workaround for this problem?

Best Answer

LaTeX doesn't hyphenate tt fonts, which makes it hard to set the paragraph.

You could use sloppypar to allow white space to stretch more to compensate, or you could reset the hyphen for the tt font (which is a global change, affecting tt for the rest of the document).

enter image description here

\documentclass{scrartcl}
\begin{document}

\section{Test1}

This is some text text and even more text \texttt{and some variable names which are writtenin typewriter font}

\section{Test2}
\begin{sloppypar}
This is some text text and even more text \texttt{and some variable names which are writtenin typewriter font}
\end{sloppypar}

\section{Test3}
{{\ttfamily \hyphenchar\the\font=`\-}%
This is some text text and even more text \texttt{and some variable names which are writtenin typewriter font}\par}

\end{document}