TransWikia.com

How do I stop matlab-prettifier thinking print strings are comments?

TeX - LaTeX Asked by K-Q on August 1, 2021

I am trying to put my code into a Latex document using matlab-prettifier. I am doing this by using lstinputlisting[style=Matlab-editor]{Trap.m}.

An example of Trap.m (a MATLAB file) is as follows

step size = 5
sub_int=100
fprintf("To get an estimation to two decimal places we needed a step size of %f which is %.0f intervals. n",  step_size, sub_int)

When I run matlab-prettifier it assumes that after ‘%’ the string is actually a comment and not a statement. As it is meant to be inputting a float into a string then the colour should be black. I am unsure how to correct this.

I have included a MWE below for Latex.

documentclass{article}
usepackage{matlab-prettifier}
Text...
lstinputlisting[style=Matlab-editor]{Trap.m}

Output

2 Answers

You can use single quotes instead of double quotes to wrap the string

Or else you can define some escape character and put '%' inside the escape characters. Here is a MWE.

documentclass{article}
usepackage{matlab-prettifier}
lstset{
escapechar         = `,
    }
begin{document}
Text...
lstinputlisting[style=Matlab-editor]{Trap.m}
end{document}

Trap.m

step size = 5
sub_int=100
fprintf('To get an estimation to two decimal places we needed a step size of %f which is %.0f intervals. n',  step_size, sub_int)
fprintf("To get an estimation to two decimal places we needed a step size of `%`f which is `%`.0f intervals. n",  step_size, sub_int)

Output: enter image description here

Correct answer by nidhin on August 1, 2021

Try:

lstset{style=Matlab-editor}
lstset{morestring=[m]"}

lstinputlisting{filename.m}

It really ought to be added to the style file, perhaps with a version option so that buggy pre-2017 code is still highlighted "correctly", but CTAN doesn't list a repository so I can't just send a pull request.

Answered by Philip on August 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP