[Tex/LaTex] How to include program listings in C# with custom font and syntax highlighting in LyX

fontshighlightinglistingslyxxetex

I'm rather new to LaTeX and use LyX editor to create my documents. There are similar questions but none of them answer how to do that in LyX. I am wondering, how to include a program listing in C/C++/C# which would satisfy these conditions:

  • Syntax highlighting, example:

Highlighting example

  • Custom font (I've set a non-TeX Consolas font to be used as "Typewriter" font but nothing happens in program listing even though it works when used inline i.e. \mathtt{Foo}
  • It would be a bonus, if I could include the code as a file, like I did now (Insert -> File -> Child Document -> Program Listing)
  • Line numbers are also a bonus.

So far, what I could come up with was:
TeX example

Thank you for any advice!

Best Answer

There is no one duplicate of your question, though most parts of the answer can be found in other questions, such as

When you do Insert --> Program Listing, or Insert --> File --> Child document --> Program listing, LyX uses the features of the listings package to typeset the source code. The listings output can be customized in many different ways, which are described in the manual.

You can add customizations for each listing, or do it globally. To do it for a single listing, right click it and choose Settings. If it is a child document, add options to the More parameters box. If it is plain listing, you'll find this same box under the Advanced tab in the settings. To do it globally, which is likely what you want, go to Document --> Settings --> Listings.

Parameters are entered as key=value pairs, just as you see in the questions linked to above, but in the LyX settings you add one parameter per line, commas are not needed. Syntax highlighting is covered by the first of the questions above. To add line numbering, add numbers=left, which adds the numbers to the left of the line, and you may want something like numberstyle=\tiny which sets the numbers in a small size.

A complete set of parameters, that you can copy-paste to Document --> Settings --> Listings, is

basicstyle={\ttfamily}
commentstyle={\color{green}\ttfamily}
keywordstyle={\color{blue}\ttfamily}
language={C++}
morecomment={[l][\color{magenta}]{\#}}
numbers=left
numberstyle={\tiny}
stringstyle={\color{red}\ttfamily}

You may also be interested in columns=fullflexible and breaklines=true.