[Tex/LaTex] Break Lines in minted environment

line-breakingmdframedmintedpage-breaking

Usually when adding code in a LaTeX document, I use the listings package. When trying to modify and personalise styles in listings, @1010011010 suggested to use the minted package.

To be quite frank, I was impressed! I've managed to install it and make it work according to my needs and taste. I've added line numbers and used the mdframed package to add colored background that breaks along pages. At the moment I am trying to break a line when it's too large to fit within the \textwidth. I used @MarcoDaniel 's answer on Box around minted environment to break the lines but it's not working as expected.

My code is

\documentclass{book}

\usepackage[]{minted}
\usepackage{tcolorbox}
\usepackage{lineno}
\usepackage{mdframed}


\def\gobble#1{}
\renewcommand\DeleteFile[1]{}
\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 
       \tl_set:Nn \l_fvrb_tl { #1 }
       \fvrb_use_tl:N \l_fvrb_tl
      } 
      {%box fits
       \box_use:N \l_fvrb_box
      }
 }

\cs_new:Npn \fvrb_use_tl:N  #1
 {
  \group_begin:
   \null\hfill\vbox_set:Nn \l_fvrb_box
     {\hsize=\linewidth
      \renewcommand\thelinenumber
           {
             \ifnum\value{linenumber}=1\relax\else
                  $\rightarrow$
             \fi
           }
      \begin{internallinenumbers}
        \advance\hsize by -2em
        \hspace*{-2em}\tl_use:N #1
      \end{internallinenumbers}
     }
   \box_use:N \l_fvrb_box
  \group_end:
}

\ExplSyntaxOff


\usepackage{etoolbox}
\usepackage{xcolor}
\definecolor{lbcolor}{rgb}{0.9,0.9,0.9}

\usepackage[margin=2.8cm]{geometry}
\begin{document}
 \section{Section}
  \begin{minted}[linenos=true,bgcolor=lbcolor,numberblanklines=true,showspaces=false]{java}
  int slotADC = 22;// Change CAMAC controller's backpanel jumper, accordingly
  int count = 0;                                                
  int[] data = new int[1];
  int[] offset = {0, 0};
  int[] in = {1, 2};
  int[] ones = {1,1};

  report.setProperty("INSERT", "["+now.format(new Date())+"] Acquisition Started\n");
  report.setProperty("INSERT", "["+now.format(new Date())+"] I am set to read "+evSize+" detectors.\n");
  Initialize(); 
 \end{minted} 

\begin{mdframed}[linecolor=black, topline=true, bottomline=true,
  leftline=false, rightline=false, backgroundcolor=lbcolor,userdefinedwidth=\textwidth]
  \begin{minted}[fontsize=\normalsize, linenos, frame=lines]{java}
   import java.awt.event.*;//for ActionListener

public class Runtime implements KmaxRuntime {
    KmaxToolsheet tlsh;//Store a reference to the toolsheet environment
    KmaxWidget wSlot;
    KmaxWidget wAdd;
    KmaxWidget wData;
    KmaxWidget dataField;
    KmaxWidget countField;
    KmaxWidget setSRQ;
    KmaxDevice dev;
    KmaxHist hist1,hist2,hist3,hist4,hist5,hist6, histoLowX, histoLowY;
    KmaxHist dee1;
    KmaxWidget report;

    KmaxWidget liveTime;
    KmaxWidget realTime;
    KmaxWidget deadTime;    

    KmaxWidget progress;

    KmaxWidget xcombo, ycombo, offsetButton;

    KmaxWidget combo, checkBoxCalib;

    /** ADC Levels */
    KmaxWidget lld;
    KmaxWidget setLLD;
    KmaxWidget getLLD;
    KmaxWidget lldText;
    KmaxWidget uld;
    KmaxWidget setULD;
    KmaxWidget getULD;
    KmaxWidget uldText;

    /** Calibration - Check Box(use calibration) */
    boolean eventFileOn = true;

    int slotADC = 22;// Change CAMAC controller's backpanel jumper, accordingly
    int count = 0;                                                
    int[] data = new int[1];
    int[] offset = {0, 0};
    int[] in = {1, 2};
    int[] ones = {1,1};
    int points = 10;
    int[] region = new int[points];
    int timeTicks;
    int totalTime;
    int LiveTime = 0;
    int totcount;
    int evType = 1; //The Type ID for these kinds of events
    SimpleDateFormat today = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat now = new SimpleDateFormat("HH:mm:ss:SSS");

    Map<String,KmaxHist> histograms = new HashMap<String,KmaxHist>();

    static final int evSize = 6;//The num of parameters per event of this type
    static final int BUF_SIZE = evSize*1000;// Buffer size  
    static final int LP_MEM_TOP = 0xFFFF00;//Memory size 16MB   
    static final int READ_START = LP_MEM_TOP  -  BUF_SIZE;//We start the read/write pointer 1 buffer before the end
  \end{minted}

    %\inputminted[fontsize=\normalsize, linenos, frame=lines]{java}{DAQ.java}%[linenos=true,bgcolor=lbcolor]{java}{DAQ.java}
\end{mdframed}

\end{document}

Line breaking seems to be working fine when using it's built in option for colored background bgcolor.

enter image description here

This isn't the case when using mdframed. For instance text jumps out of the frame and there's a rather annoying identation when detecting a line break. Take a look for instance lines 39 and 60 in the following image

enter image description here

Any idea on how can this be fixed?

Best Answer

The development version of minted supports automatic line breaks via the new breaklines option. Here's a way to get even better breaks than what is currently provided by the development version. I will add this to the development version with a new option, but that may take a little while since I expect that some refactoring and additional refining will be necessary.

Add the code below in your preamble, after you have set the highlighting style that you want. If you aren't using the default style, then replace the word default in the code below with the name of the style you are using. This code prevents linebreaks within tokens. The \allowbreak{} allows line breaks between adjacent tokens with no intervening space. If that produces breaks at undesirable locations, then simply remove it \makeatletter \let\oldPYGdefault\PYGdefault \def\PYGdefault#1#2{\hbox{\oldPYGdefault{#1}{#2}}\allowbreak{}} \makeatother

Here's what that does to the first example in @Thanos's answer. The second-to-last string in line 9 is no longer broken right before the closing quote.

enter image description here

Keep in mind that preventing breaks in tokens can produce worse results when tokens are very long. For example, if you have a really long string, then it will go into the margin.

Edit 2015/01/16: The development version of minted now contains a breakbytoken option based on this answer.