Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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!

share|improve this question
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 Jul 22 '13 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 Jul 22 '13 at 0:57

2 Answers 2

up vote 3 down vote accepted

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

share|improve this answer
    
If someone knows, why the quotation marks in my strings are not set in Consolas, please let me know. –  LaRiFaRi Jul 22 '13 at 10:50
    
maybe use upquote=true –  MaPePeR Jul 22 '13 at 11:16
    
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 Jul 22 '13 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 Jul 22 '13 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 Jul 22 '13 at 12:15

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}
share|improve this answer
    
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 Jul 22 '13 at 11:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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