[Tex/LaTex] Verbatim Linebreaks

line-breakingverbatim

I would like to enable automatic line breaking in Verbatim environment; besides I do not want to use lstlisting as it will not have exactly the same font shapes as Verbatim and some other special characters used in Logic Programming like \+ does not show the same. I should only use Verbatim environment but it seems that the option of line breaking is not available. fancyvrb also doesn't work as we need to know when we want the line to break. I need this to be automatic.

Best Answer

Here a small hack. It saves the contents of a verbatim line inside a vertical box which allows line breaks:

\documentclass[a5paper]{article}
\usepackage[T1]{fontenc}
\usepackage{fancyvrb}
\usepackage{showframe}

\usepackage{xparse}
\ExplSyntaxOn
\box_new:N \l_fvrb_box
\tl_new:N \l_fvrb_tl

\RenewDocumentCommand \FancyVerbFormatLine { m }
 {
   \hbox_set:Nn \l_fvrb_box { #1 }
    \dim_compare:nNnTF { \box_wd:N \l_fvrb_box }>{ \linewidth }
      {%box to big 
       \fvrb_use_linecontents:n { #1 }
      } 
      {%box fits
       \box_use:N \l_fvrb_box
      }
 }

\cs_new:Npn \fvrb_use_linecontents:n  #1
 {
  \group_begin:
   \vbox_set:Nn \l_fvrb_box
     {\hsize=\linewidth\parindent0pt
       \advance\hsize by -2em
       \hspace*{-2em}
        #1
     }
    \hspace*{2em}\box_use:N \l_fvrb_box
  \group_end:
}

\ExplSyntaxOff

\begin{document}
\begin{Verbatim}
asdsadsadsa asd  a

asdsadsadsa asd  asd  asd sa sd sd as  sdadas sa+ dsa +sa++94+4+ +4sd+as 
\end{Verbatim}
\end{document}