I am compiling a LaTeX file my_document.tex
into an HTML page my_document.html
using htlatex with the following command:
htlatex my_document.tex "xhtml,mathml-" " -cmozhtf"
I have a MATLAB code file main.m
that I want to include in my_document.html
with formatting that matches the MATLAB editor. When compiling with pdflatex
, I use the following:
\documentclass{article}
\usepackage{listings}
\usepackage[numbered]{matlab-prettifier}
\lstset{
style=Matlab-editor
}
\begin{document}
\lstinputlisting{main.m}
\end{document}
Compiling the above code with htlatex
, however, creates output that is black-and-white. Our current approach is to use m2tex to translate the .m file into a .tex file, but this makes the process of updating the HTML files more complicated because it adds a step, so I'm trying to find a way to simplify the process. I've included one approach as an answer, below, but am looking for other suggestions.
EDIT: Here is an example MATLAB file, main.m
:
% This is a comment
var = "this is a string";
for i = 1:5
doThing(i)
end
disp this_is_some_text
function doThing(i)
fprintf('Number %d\n', i)
end
In the MATLAB code editor, main.m
looks like the following screenshot, so the goal is to make the HTML output match this as well:
Best Answer
Working with colors is a bit complicated with TeX4ht. Stuff like
\textcolor
works, but colors that are set by\color
cannot be supported out of the box. You need to add some HTML tags with color information yourself.For listings, we can use hooks provided by the package to insert some elements around each keyword. We can get the current color and insert CSS instructions.
Try this configuration file,
config.cfg
:In the
OutputBox
hook, we define the\html@color
macro. It holds the current color suitable for CSS thanks to\extractcolorspec
and\convertcolorspec
commands. We insert it to the HTML output thanks to\lst@AddToHook{PostOutput}{\HCode{</span>}}
command. In thePostOutput
hook, we insert the closing</span>
tag.Here is a MWE:
Compile using (don't use
htlatex
, it is deprecated):This is the result:
One last thing. I've found a bug in the configuration file for the Color package,
color.4ht
. It prevents the correct conversion of colors. Here is the correct version: