[Tex/LaTex] How to prevent line breaks in code listings

bashline-breakinglistingssourcecode

I am adding a big Linux terminal output as a listing and would like to prevent these line breaks from happening:

e.g.

user@pc ~ $ top
PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     
TIME+ COMMAND                                  
19173 user      20   0   26720   1572   1048 R   6.4  0.0   
0:00.01 top                           
    1 root      20   0   33904   3200   1496 S   0.0  0.0   
0:06.67 init   

EDIT: Working solution

\documentclass{article}
\usepackage{linegoal,listings}
\usepackage{adjustbox}
\lstdefinestyle{Bash}
{
  language=bash,
  breaklines=false,
  showspaces=true,
}
\makeatletter
\def\lst@visiblespace{\lst@ttfamily{\char32} } % <-- hack
\makeatother

\begin{document}
\begin{adjustbox}{width=\textwidth,keepaspectratio}

\begin{lstlisting}[style=Bash, caption={bash output}]
PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND                                  
19173 user      20   0   26720   1572   1048 R   6.4  0.0   0:00.01 top                           
    1 root      20   0   33904   3200   1496 S   0.0  0.0   0:06.67 init                          
    2 root      20   0       0      0      0 S   0.0  0.0   0:00.01 kthreadd                      
    3 root      20   0       0      0      0 S   0.0  0.0   0:04.00 ksoftirqd/0 
\end{lstlisting}
\end{adjustbox}

\end{document}

Best Answer

Looks like a bug of listings package, because no line breaks should be produced unless you explicitly request them with breaklines=true.

Moreover, if you use showspaces=true, then line breaks are not produced (but you have all spaces visible as ␣, of course).

This suggested me the following hack: use showspaces=true, but redefine the "visible space" to be a blank space instead of ␣.

This is the code:

\documentclass{article}
\usepackage{linegoal,listings}
\lstdefinestyle{Bash}
{
  language=bash,
  breaklines=false,
  showspaces=true,
}
\makeatletter
\def\lst@visiblespace{\lst@ttfamily{\char32} } % <-- hack
\makeatother

\begin{document}

\begin{lstlisting}[style=Bash, caption={bash output}]
PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND                                  
19173 user      20   0   26720   1572   1048 R   6.4  0.0   0:00.01 top                           
    1 root      20   0   33904   3200   1496 S   0.0  0.0   0:06.67 init                          
    2 root      20   0       0      0      0 S   0.0  0.0   0:00.01 kthreadd                      
    3 root      20   0       0      0      0 S   0.0  0.0   0:04.00 ksoftirqd/0 
\end{lstlisting}
\end{document}

Result:

Result

This works but of course produces a listing which is too wide for the text area and overlaps the right margin. You can reduce the font in the listing, or change the page layout, etc.

Related Question