3

Why must I use style work-around to set C# language in listings?

Why \begin{lstlisting}[language=[Sharp]C] cannot be processed by LaTeX?

\documentclass[a4paper,12pt]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{listings}
\usepackage{inconsolata}

\usepackage{xcolor}
\definecolor{bluekeywords}{rgb}{0.0,0.0,0.9}
\definecolor{greencomments}{rgb}{0,0.6,0}
\definecolor{redidentifiers}{rgb}{0.9,0,0}
\definecolor{orangestrings}{rgb}{0.6,0.3,0}

% Formatting for any language 
\lstset{columns=flexible,
basicstyle=\ttfamily,
commentstyle=\color{greencomments},
keywordstyle=\color{bluekeywords},
stringstyle=\color{orangestrings},
identifierstyle=\color{redidentifiers},
showstringspaces=false
}

\lstdefinestyle{CSstyle} {
  language=[Sharp]C
}

\begin{document}

Java
\begin{lstlisting}[language=Java]
// HelloWorld.java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World");
    }
}
\end{lstlisting}
and C\#
%\begin{lstlisting}[language=[Sharp]C]
\begin{lstlisting}[style=CSstyle]
// Hello1.cs
public class Hello1 {
   public static void Main() {
      System.Console.WriteLine("Hello, World");
   }
}
\end{lstlisting}
look similar.

Python looks different.
\begin{lstlisting}[language=Python]
# Hello.py
s = 'Hello, World'
print s 
\end{lstlisting}

\end{document}
2
  • 3
    the option goes up to the first ] so is \begin{lstlisting}[language=[Sharp] with an unknown language [Sharp try \begin{lstlisting}[language={[Sharp]C}] but not having brackets in the language name would be better Jun 25, 2015 at 16:20
  • 2
    Page 12 of the manual: “language=[77]Fortran does not work inside an optional argument. You must put braces around the value if a value with optional argument is used inside an optional argument. In the case here write language={[77]Fortran} to select Fortran 77.”
    – egreg
    Jun 25, 2015 at 17:25

1 Answer 1

6

It is explained in the manual of listings, page 12 (near the end of section 2.3):

language=[77]Fortran does not work inside an optional argument.
You must put braces around the value if a value with optional argument is used inside an optional argument. In the case here write language={[77]Fortran} to select Fortran 77.

So do

\begin{lstlisting}[language={[Sharp]C}]

You must log in to answer this question.

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