3

I want to place a listing, with colored background, in a two-columns document. For safety (for cases when the width of listing only slightly exceeds column width) I put the listing in a \maxsizebox. It partly works, but somehow the colored background is also scaled: the longest program line fits column width, but the colored background not. If you comment out the \maxsizebox line, the line width exceeds column width, and the colored background fits it.

Two further problems:

  1. when the caption contains a comma, the package attempts to identify the part after the comma as an xkeyval value

  2. when I use the lstlisting environment instead of lstinputlisting, the compilation hangs.


\documentclass[14pt,twocolumn]{memoir}
   \usepackage{listings}
   \usepackage{xcolor}
   \usepackage{mwe}
   \usepackage{adjustbox}
   \newcommand\MESourceFile[4][]{
   \noindent\maxsizebox{\columnwidth}{.5\textheight}
        {
        %   \begin{lstlisting}[language=C,backgroundcolor=\color{green!10}]
        %int main ( int argc, char ** argv )
        %{
        %std::cout << "Hello World" << std::endl;
        %}      
        %   \end{lstlisting}

                \lstinputlisting[ label=#4, name=#4,linewidth=\columnwidth,
                caption =#3,language=C,backgroundcolor=\color{green!10}
                ]{#2}
            }   
       }

\begin{document}
    \blindtext
    \MESourceFile{HelloWorld.cpp}{The hello
 %          ,with comma
        }{lst:hello1}
        \blindtext
\end{document}
2

I suggest to use a tcbinputlisting box and the listing option breaklines=true → further configuration of style depends on listings and tcolorbox.

The comma problem can be addressed by using caption={#3}, i.e. using a {...} pair!

C++ file:

  #include <iostream>
  // Hello World - Example
  int main( int argc, char **argv )
  {
    std::cout << "Hello World\n";
    return 0;
  }

LaTeX source:

\documentclass[14pt,twocolumn]{memoir}
\usepackage{xcolor}
\usepackage{blindtext}
\usepackage[most]{tcolorbox}
\newcommand\MESourceFile[4][]{%
  \tcbinputlisting{%
    enhanced jigsaw,
    boxrule = 0pt,
    sharp corners,
    listing remove caption=false,
    nobeforeafter,
    listing options={label=#4, name=#4,breaklines=true,
      caption={#3},language=C},
    colback=red!70,
    listing file={#2},
    listing only,
    left=1pt,
    fontupper={\tiny},
  }%
}


\begin{document}
\blindtext
\MESourceFile{HelloWorld.cpp}{Some text, with a comma}{lst:hello1}
\blindtext
\end{document}

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.