I have a .m file with Matlab code and I want to paste it in Lyx. How can I do this easily?
I'd recommend using the
matlab-prettifier package (see https://tex.stackexchange.com/a/158816/586), which is really just provides a style for the
listings package. This will give you good highlighting of Matlab code, while still enabling you to use the built-in stuff in LyX related to code listings (if you so desire).
To use the package, take these two steps:
Document --> Settings --> LaTeX preamble: Add
Document --> Settings --> Listings: Add
Now, there are two different methods for getting code into LyX. Either input a file directly, or copy-paste code from Matlab:
In your document, do Insert --> File --> Child Document. Choose Program listing as "Include type", click the Browse button, and find an
.m that you want to include:
You can write caption and label right away, if you like, or do it later by right-clicking on the inset and choosing settings.
The key-thing if you do want to copy-paste code into a listing (made with Insert --> Program listing, or ERT), is that you need to use paste special, i.e. Ctrl + Shift + V or Edit --> Paste special --> Plain text. If you don't, line breaks in the code will not be preserved.
For the code environment, you can use Mark Pace's code in an ERT directly, or you can use Insert --> Program listing, which inserts a
lstlisting environment, just as Mark's code. If you right-click in that inset and choose settings,
you can adjust some things. To adjust settings that are not available from the first tab of the settings dialog, go to the Advanced tab, and write them as key=value pairs in the right panel. This includes things like caption and label.
One caveat here: if you use this method to insert a listing with a caption, you will not be able to access that label in LyX's cross-reference system. That is, if you do Insert --> Cross-reference, the code listings will not show up in the list of labels. A child document-listing on the other hand, will show up. (You can circumvent that by adding a new label via Insert --> Label inside a LyX note, made with Insert --> Note --> LyX Note, but it's more of a hassle.)