[Tex/LaTex] How to highlight code inside verbatim environment

codeverbatim

I am writing a book containing tutorials and I need to show code:

Write this: 

\begin{verbatim}
function doit() {
  console.log("Hello");
}
\end{verbatim}

And then add these lines:

\begin{verbatim}
function doit() {
  var s = "Hello";
  console.log(s);
}
\end{verbatim}

I would like to highlight var s = "Hello"; so that it is clear it is the new code added. I would like to set a different color for this text so the new line appears black and the rest appears grey.

How do I achieve this?

This is with a very standard LaTeX document, so I did not include the whole file.
fg

Best Answer

Here is an option with fancyvrb where you can change the formatting of specific lines; the code should be self-explanatory:

enter image description here

\documentclass{article}

\usepackage{fancyvrb,xcolor}

\begin{document}

Write this: 

\begin{Verbatim}
function doit() {
  console.log("Hello");
}
\end{Verbatim}

And then add these lines:

\renewcommand{\FancyVerbFormatLine}[1]{%
  \ifnum\value{FancyVerbLine}=2
    \textcolor{red}{#1}% Format specific line
  \else
    #1% Else, do nothing different
  \fi
}
\begin{Verbatim}
function doit() {
  var s = "Hello";
  console.log(s);
}
\end{Verbatim}

\renewcommand{\FancyVerbFormatLine}{}% Clear how lines are formatted differently
\begin{Verbatim}
function doit() {
  var s = "Hello";
  console.log(s);
}
\end{Verbatim}

\end{document}

It should work for elementary setups and small code formatting.