You can do that with a combination of relatively arcane listings
internal macros; no need to write to an external file. For convenience, I've defined a new boolean key called onlyheader
. If that key is set, any output after the first contiguous block of comment lines (i.e. the function header) is dropped.
Edit: This feature has been implemented in version 0.2 of matlab-prettifier
via a key called mlonlyheader
.
\documentclass{article}
\usepackage[T1]{fontenc}
% --- write to file ---
\usepackage{filecontents}
\begin{filecontents*}{code.txt}
function myfunction(args)
%MYFUNCTION One-line description goes here
% Comments
% about the function
% with an unknown number of lines
[ 2 3 4 ]
command1(); % another comment
command2();
% another comment
command3();
end
\end{filecontents*}
\usepackage[framed]{matlab-prettifier}
\lstset{style = Matlab-editor}
\begin{document}
\lstinputlisting
[caption = {\texttt{mlonlyheader=false}}]
{code.txt}
\lstinputlisting
[
caption = {\texttt{mlonlyheader=true}},
mlonlyheader = true,
]{code.txt}
\end{document}
Using only listings
\documentclass{article}
% --- write to file ---
\usepackage{filecontents}
\begin{filecontents*}{code.txt}
function myfunction(args)
%MYFUNCTION One-line description goes here
% Comments
% about the function
% with an unknown number of lines
[ 2 3 4 ]
command1(); % another comment
command2();
% another comment
command3();
end
\end{filecontents*}
\usepackage{listings}
\makeatletter
% We define a new boolean key for convenience
\lst@Key{onlyheader}{false}[t]{\lstKV@SetIf{#1}\lst@ifonlyheader}
% We'll use this switch to keep track of where we are
\newif\iffirstnoncommentline
% --- Careful! the following modifications are global ---
% (i.e. will apply to all listings)
\lst@AddToHook{PreInit}{\global\firstnoncommentlinetrue}
\lst@AddToHook{Output}{\dropOutput}
\lst@AddToHook{OutputOther}{\dropOutput}
% helper macro
\newcommand\dropOutput
{%
\lst@ifonlyheader%
\ifnum\lst@lineno>1%
\lst@ifLmode%
\else
\iffirstnoncommentline%
\lst@EnterMode\lst@Pmode{}%
\lst@BeginDropOutput\lst@Pmode%
\fi
\global\firstnoncommentlinefalse%
\fi
\fi
\fi
}
\makeatother
\lstset{
language = Matlab,
frame = single,
}
\begin{document}
\lstinputlisting
[caption = {\texttt{onlyheader=false}}]
{code.txt}
\lstinputlisting
[
caption = {\texttt{onlyheader=true}},
onlyheader = true,
]{code.txt}
\lstinputlisting
[
caption = {\texttt{onlyheader=true}},
onlyheader = true,
]{code.txt}
\end{document}
listings
, such asMatlab
?mcode
package (mathworks.com/matlabcentral/fileexchange/…)matlab-prettifier
package; it improves uponmcode
in many ways. See this answer.