Insert programming code in a Lyx document

Lyx

Lyx Problem Overview


What is the best way of inserting python/C++ code in a Lyx document? The code is small examples less than 20 lines.

My Lyx document is using the Book document class.

Orjanp

Lyx Solutions


Solution 1 - Lyx

I prefer to insert the listings as a child document, so the code is grabbed directly from a file that you can further edit and keep updated (you avoid to duplicate an information and maintenance is a lot easier). To do this in Lyx:
Insert->File->Child document
Then in the window that will appear change the type to program listing and configure it as you need, for example you could want to enter the parameter language=Python (you can type a ? to view all the parameters).
A set of parameters I usually use is:

breaklines=true //--> breaks lines to margin
captionpos=b  //--> caption at the bottom of the listing (default is "t")
frame=tb  //--> frame at the top and at the bottom of the listing
language=Python  //--> syntax highlighting for python

Solution 2 - Lyx

There should be an Insert -> Program Listing option. That uses listings Latex package, so you should have that installed. The support seems to have been added in Lyx 1.5, and from their screenshot, it seems it gives you a lot of customization options.

Solution 3 - Lyx

The insert->Program Listing feature works great. I just want to add that if you are on Mac, and try to directly paste, using command+V or right-click+paste, a block of code into the program listing, the whitespace will not be preserved, and you have to manually insert the whitespace by typing tabs, returns, etc.

A very easy way to get around this is is to paste using shift+command+V. This preserves all the whitespace of your original source code.

Categories
Recommended Lyx Solutions

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOrjanpView Question on Stackoverflow
Solution 1 - LyxVincenzo PiiView Answer on Stackoverflow
Solution 2 - LyxAlok SinghalView Answer on Stackoverflow
Solution 3 - LyxxdavidliuView Answer on Stackoverflow