Break Lines in minted environment

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}
\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 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 progress;

KmaxWidget xcombo, ycombo, offsetButton;

KmaxWidget combo, checkBoxCalib;

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.

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

Any idea on how can this be fixed?

• The development version of minted has a breaklines option inspired by the answer you referenced. It seems to work fine with your example. The development version also has some options for customizing the break symbol and indent. – G. Poore Sep 9 '14 at 16:00
• @G.Poore : This is great news! However, how to install it in my TeXlive distrinution? – Thanos Sep 9 '14 at 18:26
• If you download the minted.sty from GitHub and put it in the same directory as your document, it will be used for that document. That would be a good way to check and see if it works for you. Longer term, you could install in texmf-local (see this). Or you could replace the minted.sty in /texmf-dist/tex/latex/minted (though that might be frowned on, since it puts texmf-dist out of sync with the repository). – G. Poore Sep 9 '14 at 19:00
• Actually I did and used breaklines=true in the optional arguments but it seems that it's not recogized... – Thanos Sep 9 '14 at 19:05
• Did you download the latest minted.sty (not the release download)? Are you using breaklines as an optional argument for the minted environment? – G. Poore Sep 9 '14 at 20:57

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.

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.

• Thank you very much for your answer! The thing is that I don't see any difference... Take a look here for instance... imgur.com/17lEmuG – Thanos Sep 12 '14 at 18:00
• @Thanos If you compare against your example, line 9 (wrapped) no longer begins with a quotation mark " from the string on the previous line being broken. The image you linked to shows the downside of this approach. If tokens can't be broken, then a long token like a long comment will go off into the margin. I have some ideas about possible ways to allow breaking tokens while trying to keep tokens intact, but nothing I can implement and try quickly. – G. Poore Sep 12 '14 at 19:07
• @G.Poore can you please update stackoverflow.com/questions/1966425/… to reflect that you are the author and update the git repo details. Also, as this is a relatively common question for minted can you indicate that 'breaklines=true' is now an option -- almost. Testing atm and it works great. – SpmP Sep 29 '14 at 2:30
• @SpmP I just updated the linked question, so it should be fixed as soon as it is reviewed. I also updated the answer above to mention breaklines explicitly. – G. Poore Sep 29 '14 at 3:17
• Great to see support for automatic line breaking in minted! Any estimated date for uploading the development version to CTAN? – Gonzalo Medina Jan 17 '15 at 4:47

In order to make it work, I downloaded the latest version of minted.sty.

There are some ways to make it work, but I feel that there need to be some improvements, so everybody please be my guest!

Short code using environment/inputminted seems to be working fine!

\documentclass{book}

\usepackage[]{minted}
\usepackage{xcolor}
\definecolor{lbcolor}{rgb}{0.9,0.9,0.9}
\usepackage[margin=2.8cm]{geometry}
\begin{document}
\section{Minted Environment}%For a weird reason the code is put at the bottom side of the page
\begin{minted}[linenos=true,bgcolor=lbcolor,numberblanklines=true,showspaces=false,breaklines=true]{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}
\end{document}


Large code that needs to span over one page doesn't work pretty well. There's one blank page at the beggining and the the code doesn't break in a new page.

\documentclass{book}

\usepackage[]{minted}
\usepackage{xcolor}
\definecolor{lbcolor}{rgb}{0.9,0.9,0.9}
\usepackage[margin=2.8cm]{geometry}
\begin{document}
\section{Minted Environment Large}%This code is too large to fit in a page, yet it does not break
\begin{minted}[linenos=true,bgcolor=lbcolor,numberblanklines=true,showspaces=false,breaklines=true]{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();
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();
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();
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();
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();
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}
\end{document}


Large code breaking in more pages using mdframed seems to be working fine. The only issue is that the line break occures in a space character which sometimes can be inconvenient.

    \documentclass{book}

\usepackage[]{minted}
\usepackage{mdframed}
\usepackage{xcolor}
\definecolor{lbcolor}{rgb}{0.9,0.9,0.9}
\usepackage[margin=2.8cm]{geometry}
\begin{document}
\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 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 progress;

KmaxWidget xcombo, ycombo, offsetButton;

KmaxWidget combo, checkBoxCalib;

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}
\end{mdframed}
\end{document}


• The bgcolor option provides a background color but will not break across pages. If you need breaks across pages, you should always use a proper framing package like mdframed or tcolorbox. In you final example, code runs off the page because breaklines wasn't used. I agree that the location of automatic breaks can be inconvenient. Unfortunately, to get really good automatic breaks, you probably need a language-specific tool. I believe I have found a way to prevent breaks in the middle of strings (line 9 in your first example). Solution coming soon. – G. Poore Sep 11 '14 at 21:50
• @G.Poore : Thank you very much! I'll be waiting!!!Looking forward to it!!! – Thanos Sep 12 '14 at 8:27

I simply added a space in the code at the point in a long string, that got interpreted by minted as not be able to get broken over two lines. This combined with the breaklines option helped me modify the breakpoints for visual optimation. I would say it's quick and dirty, but it works!

Example:

my_cool_variable.my_super_cool_function(:what_a_long_name_for_a_parameter).yes_i_needed_to_call_something_more <- broken wrong with breaklines option

my_cool_variable.my_super_cool_function (:what_a_long_name_for_a_parameter) .yes_i_needed_to_call_something_more <- whitespace in the code creates a breakpoint