1

When I complile the following code with xelatex, %\end{lstlisting} is a necessary line to prevent error. What is the problem?

\documentclass[a4paper,11pt, onecolumn, openany,]{memoir}
\usepackage[english]{babel} % English please
%\usepackage[final]{microtype} % Less badboxes
\usepackage{fontspec}


\usepackage{listings}
\usepackage{xcolor}


\newfontfamily{\lstcode}[Scale=0.85]{Ubuntu Mono}
\lstdefinestyle{csharp}
{
     language=[Sharp]C,
     frame=shadowbox,
     rulecolor=\color{white!80!black},
     rulesepcolor=\color{white!80!black},
     basicstyle=\lstcode,
     showstringspaces=false,     
     breaklines=true
}

\def\bcsh#1\ncsh
{
    \lstset{style=csharp}
    \begin{lstlisting}[numbers=left]
    #1
    \end{lstlisting}
}

\begin{document}
\bcsh
class Program
{  
    static void Main()
    {
        System.Console.WriteLine("Hello World!");
        System.Console.ReadKey();
    }
}
\ncsh
%\end{lstlisting}

\end{document}
  • Welcome to TeX.SX! You cannot pass a lstlisting as the argument to a macro. – egreg Feb 7 '16 at 21:22
  • Welcome to TeX.SX! It might be very fascinating to define shortcuts for environments, but most times they fail due to specific needs of the environment. And lstlisting is more cunning than tabular etc. ;-) – user31729 Feb 7 '16 at 21:22
1

Short answer: you can't pass a lstlisting environment as the argument to a macro.

You can define a new environment, instead.

\documentclass[a4paper,11pt, onecolumn, openany,]{memoir}
\usepackage[english]{babel} % English please
%\usepackage[final]{microtype} % Less badboxes
\usepackage{fontspec}


\usepackage{listings}
\usepackage{xcolor}


\newfontfamily{\lstcode}[Scale=0.85]{Ubuntu Mono}
\lstdefinestyle{csharp}
{
     language=[Sharp]C,
     frame=shadowbox,
     rulecolor=\color{white!80!black},
     rulesepcolor=\color{white!80!black},
     basicstyle=\lstcode,
     showstringspaces=false,     
     breaklines=true
}

\lstnewenvironment{bcsh}[1][]
 {\lstset{style=csharp,numbers=left,#1}}
 {}

\begin{document}
\begin{bcsh}
class Program
{  
    static void Main()
    {
        System.Console.WriteLine("Hello World!");
        System.Console.ReadKey();
    }
}
\end{bcsh}

\end{document}

enter image description here

  • I get an error: ! LaTeX Error: Missing \begin{document}. – nano Feb 7 '16 at 21:30
  • @iranano With that very example? – egreg Feb 7 '16 at 21:31
  • Yes. With your code that error is shown. – nano Feb 7 '16 at 21:32
  • @iranano Check whether some invisible character got inserted during the paste on your system. I copied the code in a fresh file and it gives no problem. – egreg Feb 7 '16 at 21:34
  • Yes you are right. A few more characters were copied. sorry. – nano Feb 7 '16 at 21:36

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.