[Tex/LaTex] How to break lines automatically when there are inline code format

line-breaking

My TeX have a lot of inline code to compile, so sometimes the output of PDF seems like this:

enter image description here

The outlined part is coded in {\tt set_task_state(current_state)}, How to automatically break the line within the set_task_state(current_stat)?

Best Answer

Line breaking for monotype font is a hard issue. Below, five options (really less since some of them produce results which are not acceptable); I'd suggest you to use the listings package instead of just \ttfamily (by the way, \tt is deprecated and shouldn't ne used anymore) to write your listings. I loaded showframe to have a visual guide of the text area.

\documentclass{article}
\usepackage{listings}
\usepackage{underscore}
\usepackage{showframe}

\lstset{
  basicstyle=\ttfamily\small,
  columns=fullflexible,
  breaklines=true
}

\begin{document}

The method {\ttfamily set_current_state(current_state)} is synonimous to {\ttfamily set_task_state(current_state)}

The method \lstinline|set_current_state(current_state)| is synonimous to \lstinline|set_task_state(current_state)|

{\sloppy
The method \lstinline|set_current_state(current_state)| is synonimous to \lstinline|set_task_state(current_state)|\par}

{\sloppy
The method {\ttfamily set_current_state(current_state)} is synonimous to {\ttfamily set_task_state(current_state)}\par}  

{\raggedright
The method \lstinline|set_current_state(current_state)| is synonimous to \lstinline|set_task_state(current_state)|\par}

{\raggedright
The method {\ttfamily set_current_state(current_state)} is synonimous to {\ttfamily set_task_state(current_state)}\par}

{{\ttfamily\hyphenchar\the\font=`\-}%
The method {\ttfamily set_current_state(current_state)} is synonimous to {\ttfamily set_task_state(current_state)}\par}

\end{document}

The result

enter image description here

Some comments

Using linebreaks=true enables line-break points; however, in this case, the verbatim text still protrudes.

Using sloppy leaves horrible big gaps between words.

Using \raggedright gives a somehow better and acceptable result here.

Related Question