10

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!

2
  • 1
    The minted package, which works with Pygments will automatically prettyprint source code in the Visual Studio style if you tell it to use the vs option, but it can't break the lines to fit the page automatically.
    – ChrisS
    Commented Jul 22, 2013 at 0:43
  • hi @ChrisS I write an compile my texcode on link for minted I need a installation of Python and so on as far as I think this cant be realised with the online compiler.
    – kimliv
    Commented Jul 22, 2013 at 0:57

3 Answers 3

15

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

8
  • If someone knows, why the quotation marks in my strings are not set in Consolas, please let me know.
    – LaRiFaRi
    Commented Jul 22, 2013 at 10:50
  • maybe use upquote=true
    – MaPePeR
    Commented Jul 22, 2013 at 11:16
  • 1
    Hi @LaRiFaRi, thx for your work I have two problems left. Here is a link to my solution. Problem 1 is the caption not going from left till end of the right side. Problem 2 is if a comment in the listing is going over two lines the frame gets colered green. I woud be happy do get hints to fix it. thank you!
    – kimliv
    Commented Jul 22, 2013 at 12:01
  • Hi, that compiles for me. What are your two problems? If it is regarding the framebox and the captions, I can't help you at the moment (see the listings and caption manual...). Maybe do another question or edit your post above (not recommended as maybe nobody will see it).
    – LaRiFaRi
    Commented Jul 22, 2013 at 12:10
  • @MaPePeR No, that doesn't work. But thx. In kimlivs ne MWE they look right. I will check the differences and edit it. (ah, she/he doesn't use consolas, but I want to use that further)
    – LaRiFaRi
    Commented Jul 22, 2013 at 12:15
4

There were several problems in your code. First of all i removed all the dead code and your comments, so i could point out my changes:

Your morecomment-definition morecomment=[s][\color{green}]{//}{} should be morecomment=[l][\color{green}]{//}

\DeclareCaptionFormat{listing}{\colorbox{8}{\parbox{\textwidth}{\hspace{15pt}#1#2#3}}}

i dont know a color named 8. - changed it to blue

The additional \lstset{ language=csh } overwrote most of the formatting.

\documentclass{article}

\usepackage{color}
\usepackage{listings}
%\usepackage{courier} %caused problems for me

\lstloadlanguages{% Check Dokumentation for further languages ...
C,
C++,
csh,
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, 
numbers=left, 
numberstyle=\tiny, 
numbersep=5pt, 
tabsize=2, 
extendedchars=true, 
breaklines=true, 
frame=b,
stringstyle=\color{blue}\ttfamily, 
showspaces=false, 
showtabs=true, 
xleftmargin=17pt,
framexleftmargin=17pt,
framexrightmargin=5pt,
framexbottommargin=4pt,
commentstyle=\color{green},
morecomment=[l]{//}, %use comment-line-style!
morecomment=[s]{/*}{*/}, %for multiline comments
showstringspaces=false, 
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},
keywordstyle=\color{cyan},
identifierstyle=\color{red},
}
\usepackage{caption}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{blue}{\parbox{\textwidth}{\hspace{15pt}#1#2#3}}} %changed \colorbox{8} to \colorbox{blue} cause 8 is not a color!
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white, singlelinecheck=false, margin=0pt, font={bf,footnotesize}}

%remove that, it caused most of the problems
%\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
{
/*
Multiline comment
*/
    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}
1
  • Thx for your solution and for finding my mistakes! I woud like to vote for your answer but i do not have enough reputation points so far.
    – kimliv
    Commented Jul 22, 2013 at 11:45
2

Since i wasn't able to find a really satisfying solution to C# listings in Latex , i invested a few hours and created a really perfect set of listing settings. I know this thread is really old but i hope it helps some dudes searching for a solution themselves. Have fun with my Example and leave an upvote if i was able to help :)

I recreated the darkmode style from Visual Studio for C#. This is an example how it looks like:

enter image description here

This is the code in the header of the document before \begin{document}:

\usepackage{color}
\usepackage{cascadia-code}
\usepackage{listings}

%Color scheme in Visual Studio darkmode
\definecolor{black}{cmyk}{0,0,0,1}             
\definecolor{white}{cmyk}{0,0,0,0}
\definecolor{darkgrey}{cmyk}{0,0,0,0.97}      %background in Visual Studio
\definecolor{green}{cmyk}{0.6,0,0.84,0}       %comments in Visual Studio
\definecolor{blue}{cmyk}{0.65,0.33,0,0.05}       %keywords in Visual Studio
\definecolor{rose}{cmyk}{0,0.26,0.38,0}       %strings in Visual Studio
\definecolor{lavender}{cmyk}{0,0.42,0,0.1}   %if/else,switch/case etc. in Visual Studio
\definecolor{lightblue}{cmyk}{0.35,0,0,0}     %local variables in Visual Studio
\definecolor{aqua}{cmyk}{0.65,0,0.23,0}       %class types in Visual Studio
\definecolor{lightgreen}{cmyk}{0.12,0,0.33,0.05} %enumerations and methods in Visual Studio

\lstset{
language=[Sharp]C,
numbers=left, 
numberstyle=\tiny\color{black}, 
rulesep=10pt,
xleftmargin=12pt,
framexleftmargin=-2pt,
framexrightmargin=-5pt,
showtabs=false,
showspaces=false,
showstringspaces=true,
breaklines=true,
breakatwhitespace=true,
backgroundcolor=\color{darkgrey},
rulecolor=\color{darkgrey},
commentstyle=\color{green},
morecomment=[s][\color{green}]{/*+}{*/},
morecomment=[s][\color{green}]{/*-}{*/},
basicstyle=\ttfamily\footnotesize\color{white},
stringstyle=\color{rose},
frame=trbl,
framesep=5pt,
numbersep=7pt,
belowcaptionskip=1\baselineskip,
%**********************
%ADD YOUR KEYWORDS HERE
%**********************
%-------------------------------------------
%keywords like string, int, false, true ...
keywordstyle=\color{blue},
morekeywords={partial, var, value, get, set},
%-------------------------------------------
%keywords like if/else, switch/cas ...
emphstyle=\color{lavender},
emph={if, else, return, throw, switch, case},
%-------------------------------------------
%Collection of your local and global variables
emphstyle={[2]\color{lightblue}},
emph={[2]someLocalVariable, someGlobalVariable},
%-------------------------------------------
%Collection of your class types
emphstyle={[3]\color{aqua}},
emph={[3]SomeOwnClassType},
%-------------------------------------------
%Collection of your methods
emphstyle={[4]\color{lightgreen}},
emph={[4]ToLower},
}

%Optional
%Define a new floating environment to be able to generate an own list of codes in the document
\usepackage{newfloat}
\DeclareFloatingEnvironment[fileext=frm,placement={!ht},name=Codeexample]{myCode}

This is the implementation of the code example inside the document:

\begin{myCode} %Only when using the optional floating environment
\begin{lstlisting}
//This is a test for Latex listing C# with Visual Studio darkmode style
var someLocalVariable = "This is a test string";
if(someLocalVariable.ToLower() == "this is a test string")
{
    someGlobalVariable = new SomeOwnClassType();
}
\end{lstlisting}
\captionsetup{width=.95\textwidth}
\caption[This is the caption in the list of code examples]{This is the caption below the code example in the document}
\label{list:CodeExample}
\end{myCode}%Only when using the optional floating environment

This is the implementation of the list of code examples:

\begin{addmargin}[-1.5em]{0cm}
\listof{myCode}{\hspace{1.1em}List of Codes}
\end{addmargin}

You must log in to answer this question.

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