[Tex/LaTex] Syntax highlighting in listings for C# that it looks like in Visual Studio

highlightinglistingssyntax

Community,

I want to get my C# listings syntax highlighted like in Visual Studio but I did not get it so far.

Here's an image of the syntax highlighting of Visual Studio:

enter image description here

Here is the code I have:

\documentclass{article}

\usepackage{color}
\usepackage{listings}
\usepackage{courier}

\lstloadlanguages{% Check Dokumentation for further languages ...
%[Visual]Basic
%Pascal
C,
C++,
csh,
%XML
%HTML
Java
}

\definecolor{red}{rgb}{0.6,0,0} % for strings
\definecolor{blue}{rgb}{0,0,0.6}
\definecolor{green}{rgb}{0,0.8,0}
\definecolor{cyan}{rgb}{0.0,0.6,0.6}

\lstset{
language=csh,
basicstyle=\footnotesize\ttfamily, % Standardschrift
numbers=left, % Ort der Zeilennummern
numberstyle=\tiny, % Stil der Zeilennummern
%stepnumber=2, % Abstand zwischen den Zeilennummern
numbersep=5pt, % Abstand der Nummern zum Text
tabsize=2, % Groesse von Tabs
extendedchars=true, %
breaklines=true, % Zeilen werden Umgebrochen
%keywordstyle=\color{red}\bfseries,
frame=b,
%keywordstyle=[1]\textbf, % Stil der Keywords
% keywordstyle=[2]\textbf, %
% keywordstyle=[3]\textbf, %
% keywordstyle=[4]\textbf, \sqrt{\sqrt{}} %
stringstyle=\color{blue}\ttfamily, % Farbe der String
showspaces=false, % Leerzeichen anzeigen ?
showtabs=true, % Tabs anzeigen ?
xleftmargin=17pt,
framexleftmargin=17pt,
framexrightmargin=5pt,
framexbottommargin=4pt,
commentstyle=\color{blue},
morecomment=[s][\color{green}]{//}{},
%backgroundcolor=\color{grey},
showstringspaces=false, % Leerzeichen in Strings anzeigen ?
%morekeywords={__global__} % CUDA specific keywords
morekeywords={  abstract, event, new, struct,
                as, explicit, null, switch,
                base, extern, object, this,
                bool, false, operator, throw,
                break, finally, out, true,
                byte, fixed, override, try,
                case, float, params, typeof,
                catch, for, private, uint,
                char, foreach, protected, ulong,
                checked, goto, public, unchecked,
                class, if, readonly, unsafe,
                const, implicit, ref, ushort,
                continue, in, return, using,
                decimal, int, sbyte, virtual,
                default, interface, sealed, volatile,
                delegate, internal, short, void,
                do, is, sizeof, while,
                double, lock, stackalloc,
                else, long, static,
                enum, namespace, string},% list your attributes here
keywordstyle=\color{cyan},
identifierstyle=\color{red},
}
%\DeclareCaptionFont{blue}{\color{blue}}

%\captionsetup[lstlisting]{singlelinecheck=false, labelfont={blue}, textfont={blue}}
\usepackage{caption}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{8}{\parbox{\textwidth}{\hspace{15pt}#1#2#3}}}
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white, singlelinecheck=false, margin=0pt, font={bf,footnotesize}}

\lstset{       % keyword style
  language=csh,
  }

\begin{document}


\begin{lstlisting}[label=some-code,caption=Some Code]
using System.Diagnostics;
using MathNet.Numerics.LinearAlgebra.Double; 
using MathNet.Numerics.LinearAlgebra.Double.Factorization;

namespace App
{
    public partial class Form_Main : Form
    {
        private void saveObjectToTemp()
        {
            //path to the tempfolder of this application.
            string path = Path.GetTempPath() + @"\temperatureapp";

            //check if the folder "temperatureapp" exist in the local temp folder (if not create it)
            bool folderExist = System.IO.Directory.Exists(path);
            if (!folderExist)
                System.IO.Directory.CreateDirectory(path);
        }

        private void saveObjectToTemp(object chart, string chartname)
        {
            //path to the tempfolder of this application.
            string path = Path.GetTempPath() + @"\temperatureapp";

            //check if the folder "temperatureapp" exist in the local temp folder (if not create it)
            bool folderExist = System.IO.Directory.Exists(path);
            if (!folderExist)
                System.IO.Directory.CreateDirectory(path);

            Chart tmpChart = (Chart)chart;

            tmpChart.SaveImage(path + @"\" + chartname, ChartImageFormat.Png);

        }
    }
}
\end{lstlisting}


\end{document}

The key words are not correctly identified and colored. Comments are also not identified and colored. (Comment lines in C# start with "//")

Any hints are taken gratefully by me!

Best Answer

You can have a try with my solution (which I found somewhere around this homepage I guess):

\setmonofont{Consolas} %to be used with XeLaTeX or LuaLaTeX
\definecolor{bluekeywords}{rgb}{0,0,1}
\definecolor{greencomments}{rgb}{0,0.5,0}
\definecolor{redstrings}{rgb}{0.64,0.08,0.08}
\definecolor{xmlcomments}{rgb}{0.5,0.5,0.5}
\definecolor{types}{rgb}{0.17,0.57,0.68}

\usepackage{listings}
\lstset{language=[Sharp]C,
captionpos=b,
%numbers=left, %Nummerierung
%numberstyle=\tiny, % kleine Zeilennummern
frame=lines, % Oberhalb und unterhalb des Listings ist eine Linie
showspaces=false,
showtabs=false,
breaklines=true,
showstringspaces=false,
breakatwhitespace=true,
escapeinside={(*@}{@*)},
commentstyle=\color{greencomments},
morekeywords={partial, var, value, get, set},
keywordstyle=\color{bluekeywords},
stringstyle=\color{redstrings},
basicstyle=\ttfamily\small,
}

To be used with:

\begin{lstlisting}[caption=a test for a C$^\sharp$ code, label=lst:test]
\end{lstlisting}

Keywords work just fine. However there are some things not working till now:

  • #region is not set as a keyword. Tried that but didn't succeed.
  • all bright blue stuff (objects) aren't recognized which will be a difficult point. Maybe there is a solution just to recognize e. g. Math. or other often used paths. As most objects are defined by the user, it would be a lot of handwork.
  • quotation marks in strings don't fit the chosen font

Things which could get improved here (but I don't have the time to do it):

  • set ///, <...> and <.../> grey if it doesn't appear after // (where it should keep green). The XML comment itself should stay green.
  • find objects and print them light blue. E. g. private enum Object, public class Object : Object, private virtual Object but private virtual double which are all keywords.
  • find attributes and print them light blue. E. g. [Serializable, CLSCompliant(false)].
  • remember found objects and treat them the same way all over the document.
  • Possibility to define objects manually or to recognize MSDN-objects like Math.

Looks like this until now:

enter image description here