How to deal with bad line-wrapping of \texttt?

Depending on how you want the variables to be broken, you can define a macro that allows breaking with certain rules. Here I just allowed breaking after _. Apart from that, you use a more semantic command that you can redefine with flexibility.

\documentclass{report}

\newcommand*\ttvar[1]{\texttt{\expandafter\dottvar\detokenize{#1}\relax}}
\newcommand*\dottvar[1]{\ifx\relax#1\else
  \expandafter\ifx\string_#1\string_\allowbreak\else#1\fi
  \expandafter\dottvar\fi}

\begin{document}

Most of the time, \LaTeX{} line-wrapping works fine. However, sometimes when
I'm writing about code with lots of \ttvar{long_monospace_variables},
\ttvar{the_line_wrapping} doesn't quite get the position correct resulting in
slightly-too-long lines.

\end{document}

enter image description here


Based on the answers to this question

Line wrapping on narrow pages

it seems that the best way to do this is to wrap the offending paragraph in a sloppypar environment.

\documentclass{report}
\begin{document}
\begin{sloppypar}
Most of the time, LaTeX line-wrapping works fine.  However, sometimes when I'm writing about code with lots of \texttt{long\_monospace\_variables}, \texttt{the\_line\_wrapping} doesn't quite get the position correct resulting in slightly-too-long lines.
\end{sloppypar}
\end{document}

A PDF generated from the text.  The long line issue has been fixed by the use of sloppypar.

Using a \sloppy command has a similar effect for the whole document, but this seems a little dangerous since it could break formatting elsewhere.


It's easy to do with the url package. I define a \longvar command which does the job:

\documentclass{report}

\usepackage{url}

\newcommand\longvar[1]{\mathchardef\UrlBreakPenalty=100
\mathchardef\UrlBigBreakPenalty=100\url{#1}}

 \begin{document}

Most of the time, LaTeX line-wrapping works fine. However, sometimes when I'm writing about code with lots and lots of \longvar{very_long_monospace_variables}, \texttt{the\_line\_wrapping} doesn't quite get the position correct resulting in slightly-too-long lines.

\end{document} 

enter image description here