0

This question is building off the code and solution found here. I would like to add the option to point the actual code file (either a Matlab or Python code file) and put that into my options. I have the current command

\begin{mcode}{Some Matlab Code}{matcode1.m} that specifies that this is a Matlab environment mcode, the name of the script (in this case "Some Matlab Code") and finally the path to the file.

For some reason, the filecontents contents do not show up in their respective environments and I just output these "empty" cells:

enter image description here

Can you tell me what I need to do, to have the contents of the file show up in their respective environments? Thanks!

\documentclass[a4paper, 10pt, oneside, fleqn, openright]{report}
\usepackage[no-math]{fontspec}

\usepackage{calc}
\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
\usepackage{pdfpages,graphicx}
\usepackage{mdframed}
\usepackage{listings}
\usepackage{filecontents}

\begin{filecontents*}{matcode1.m}
V = diag([0.02, 0.5*pi/180].^2);
P0 = diag([0.005, 0.005, 0.001].^2);
W = diag([0.1, 1*pi/180].^2);
map = LandmarkMap(20);
veh = Bicycle('covar', V);
veh.add_driver( RandomPath(map.dim) );
\end{filecontents*}

\begin{filecontents*}{pycode1.py}
"""
===============
Many plot types can be combined in one figure to create
powerful and flexible representations of data.
"""

import matplotlib.pyplot as plt
import numpy as np

# np.random.seed(19680801)
# data = np.random.randn(2, 100)
#
# fig, axs = plt.subplots(2, 2, figsize=(5, 5))
# axs[0, 0].hist(data[0])
# axs[1, 0].scatter(data[0], data[1])
# axs[0, 1].plot(data[0], data[1])
# axs[1, 1].hist2d(data[0], data[1])

fig, ax = plt.subplots()
plt.plot(x, y, label='Loaded from file!')
plt.fill_between(x, y, color='#539ecd')
\end{filecontents*}

\definecolor{light-gray}{gray}{0.92}

\definecolor{mainColor}{RGB}{211, 47, 47} % some dark red

\usepackage[numbered,framed]{matlab-prettifier}

\renewcommand\lstlistingname{Python Code}
\lstdefinestyle{pycode}{
    language=Python,
    numbers=left,
    numbersep= 7mm,
    numberstyle=\color{Black},
    stepnumber=1,
    tabsize=3,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    basicstyle=\color{Black}\ttfamily,
    commentstyle=\color{LimeGreen},
    keywordstyle=\color{BurntOrange}\bfseries,
    stringstyle=\color{WildStrawberry},
    keywords={var, func, extends, import},
    frame=leftline,
    framesep=0mm,
    xleftmargin=3mm,
    framesep=2mm,
    framerule=0mm,
    abovecaptionskip=5mm,
    aboveskip=\baselineskip,
    belowskip=\baselineskip,
    basicstyle=\ttfamily\scriptsize,
}

\lstdefinestyle{mcode}{
    style = {Matlab-editor},
    numbers=left,
    numbersep= 7mm,
    numberstyle=\color{Gray!80}\scriptsize,
    stepnumber=1,
    tabsize=3,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    frame=leftline,
    framesep=0mm,
    xleftmargin=3mm,
    framesep=2mm,
    framerule=0mm,
    abovecaptionskip=5mm,
    aboveskip=\baselineskip,
    belowskip=\baselineskip,
    %backgroundcolor=\color{cyan!20},
    basicstyle=\ttfamily\scriptsize,
}

%\lstnewenvironment{myPyCode}
%{\lstset{style=pycode}}
%{}
%
%\lstnewenvironment{myMatCode}
%{\lstset{style=mcode}}
%{}

\usepackage{tcolorbox}
\tcbuselibrary{skins,breakable,listings}

\newcounter{pylst}
\newtcblisting[use counter=pylst]{pycode}[3][]{%
        enhanced,noparskip,breakable,colback=light-gray,colframe=DarkSlateGray,opacitybacktitle=.8,%
        fonttitle=\bfseries,before upper={\hspace*{-1em}\includegraphics[height=\baselineskip]{example-image-a}~#2},%
        title after break={\centering\footnotesize\itshape\strut\lstlistingname~\thelstlisting~--~continued},%
        listing only,listing options={style=pycode, xleftmargin=-1mm},after upper={\centering\strut Python Code~\thetcbcounter:~#2},
        frame hidden,arc=0pt,outer arc=0pt,boxrule=0pt,frame code={\draw[gray,line width=2mm]([xshift=-0.5pt]frame.north west) -- ([xshift=-0.5pt]frame.south west);},
        listing file = {#3}, #1}

\newcounter{mlst}
\newtcblisting[use counter=mlst]{mcode}[3][]{%
        enhanced,noparskip,breakable,colback=cyan!20,colframe=DarkSlateGray,opacitybacktitle=.8,%
        fonttitle=\bfseries,before upper={\hspace*{-1em}\includegraphics[height=\baselineskip]{example-image-b}~#2},%
        title after break={\centering\footnotesize\itshape\strut\lstlistingname~\thelstlisting~--~continued},%
        listing only,listing options={style=mcode, xleftmargin=-1mm},after upper={\centering\strut Matlab Code~\thetcbcounter:~#2},
        frame hidden,arc=0pt,outer arc=0pt,boxrule=0pt,frame code={\draw[gray,line width=2mm] ([xshift=-0.5pt]frame.north west) -- ([xshift=-0.5pt]frame.south west);},
        listing file = {#3}, #1}


\begin{document}

\begin{mcode}{Some Matlab Code}{matcode1.m}
\end{mcode}

\begin{pycode}{Some Python Code}{pycode1.py}
\end{pycode}


\end{document} 

1 Answer 1

1

Basically, you need to use \newtcbinputlisting instead of \newtcblisting. The latter expects the listing contents to be provided as the body of the environment you are defining (in your case: empty). On the other hand, \newtcbinputlisting uses the file named by /tcb/listing file as input.

Before running the following code, make sure matcode1.m and pycode1.py don't already exist in the directory in which LaTeX is run, because previous runs of \newtcblisting would have truncated them to size zero, and filecontents or filecontents* without the overwrite option wouldn't rewrite them. Alternatively, you can use \begin{filecontents}[overwrite,noheader]{〈file name〉} ... \end{filecontents} if your LaTeX kernel is from October 2019 or later (which supersedes the filecontents package, see the LaTeX News Issue number 30).

(just prepend \RequirePackage{filecontents} at the very top of the file in case your LaTeX kernel is too old)

\begin{filecontents*}{matcode1.m}
V = diag([0.02, 0.5*pi/180].^2);
P0 = diag([0.005, 0.005, 0.001].^2);
W = diag([0.1, 1*pi/180].^2);
map = LandmarkMap(20);
veh = Bicycle('covar', V);
veh.add_driver( RandomPath(map.dim) );
\end{filecontents*}

\begin{filecontents*}{pycode1.py}
"""
===============
Many plot types can be combined in one figure to create
powerful and flexible representations of data.
"""

import matplotlib.pyplot as plt
import numpy as np

# np.random.seed(19680801)
# data = np.random.randn(2, 100)
#
# fig, axs = plt.subplots(2, 2, figsize=(5, 5))
# axs[0, 0].hist(data[0])
# axs[1, 0].scatter(data[0], data[1])
# axs[0, 1].plot(data[0], data[1])
# axs[1, 1].hist2d(data[0], data[1])

fig, ax = plt.subplots()
plt.plot(x, y, label='Loaded from file!')
plt.fill_between(x, y, color='#539ecd')
\end{filecontents*}

\documentclass{article}
\usepackage[dvipsnames,svgnames]{xcolor}
\usepackage{listings}
\usepackage[numbered,framed]{matlab-prettifier}
\usepackage{tcolorbox}
\tcbuselibrary{skins,breakable,listings}

\definecolor{light-gray}{gray}{0.92}
\definecolor{mainColor}{RGB}{211, 47, 47} % some dark red

\renewcommand\lstlistingname{Python Code}
\lstdefinestyle{pycode}{
    language=Python,
    numbers=left,
    numbersep= 7mm,
    numberstyle=\color{Black},
    stepnumber=1,
    tabsize=3,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    basicstyle=\color{Black}\ttfamily,
    commentstyle=\color{LimeGreen},
    keywordstyle=\color{BurntOrange}\bfseries,
    stringstyle=\color{WildStrawberry},
    keywords={var, func, extends, import},
    frame=leftline,
    framesep=0mm,
    xleftmargin=3mm,
    framesep=2mm,
    framerule=0mm,
    abovecaptionskip=5mm,
    aboveskip=\baselineskip,
    belowskip=\baselineskip,
    basicstyle=\ttfamily\scriptsize,
}

\lstdefinestyle{mcode}{
    style = {Matlab-editor},
    numbers=left,
    numbersep= 7mm,
    numberstyle=\color{Gray!80}\scriptsize,
    stepnumber=1,
    tabsize=3,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    frame=leftline,
    framesep=0mm,
    xleftmargin=3mm,
    framesep=2mm,
    framerule=0mm,
    abovecaptionskip=5mm,
    aboveskip=\baselineskip,
    belowskip=\baselineskip,
    basicstyle=\ttfamily\scriptsize,
}

\newcounter{pylst}
\newtcbinputlisting[use counter=pylst]{\pycode}[3][]{%
        enhanced,noparskip,breakable,colback=light-gray,colframe=DarkSlateGray,opacitybacktitle=.8,%
        fonttitle=\bfseries,before upper={\hspace*{-1em}\includegraphics[height=\baselineskip]{example-image-a}~#2},%
        title after break={\centering\footnotesize\itshape\strut\lstlistingname~\thelstlisting~--~continued},%
        listing only,listing options={style=pycode, xleftmargin=-1mm},after upper={\centering\strut Python Code~\thetcbcounter:~#2},
        frame hidden,arc=0pt,outer arc=0pt,boxrule=0pt,frame code={\draw[gray,line width=2mm]([xshift=-0.5pt]frame.north west) -- ([xshift=-0.5pt]frame.south west);},
        listing file = {#3}, #1}

\newcounter{mlst}
\newtcbinputlisting[use counter=mlst]{\mcode}[3][]{%
        enhanced,noparskip,breakable,colback=cyan!20,colframe=DarkSlateGray,opacitybacktitle=.8,%
        fonttitle=\bfseries,before upper={\hspace*{-1em}\includegraphics[height=\baselineskip]{example-image-b}~#2},%
        title after break={\centering\footnotesize\itshape\strut\lstlistingname~\thelstlisting~--~continued},%
        listing only,listing options={style=mcode, xleftmargin=-1mm},after upper={\centering\strut Matlab Code~\thetcbcounter:~#2},
        frame hidden,arc=0pt,outer arc=0pt,boxrule=0pt,frame code={\draw[gray,line width=2mm] ([xshift=-0.5pt]frame.north west) -- ([xshift=-0.5pt]frame.south west);},
        listing file = {#3}, #1}

\begin{document}

\mcode{Some Matlab Code}{matcode1.m}

\pycode{Some Python Code}{pycode1.py}

\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .