1

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

2
3

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.

2

Took this: How can I highlight some lines from source code?

Made this:

\documentclass{article}
\usepackage{soul,listings,xcolor}

    \lstnewenvironment{teX}[1][]
      {\lstset{language=[LaTeX]TeX}\lstset{escapeinside={(*@}{@*)},
       numbers=left,numberstyle=\normalsize,stepnumber=1,numbersep=5pt,
       breaklines=true,
       %firstnumber=last,
           %frame=tblr,
           framesep=5pt,
           basicstyle=\normalsize\ttfamily,
           showstringspaces=false,
           keywordstyle=\itshape\color{blue},
          %identifierstyle=\ttfamily,
           stringstyle=\color{maroon},
        commentstyle=\color{black},
        rulecolor=\color{black},
        xleftmargin=0pt,
        xrightmargin=0pt,
        aboveskip=\medskipamount,
        belowskip=\medskipamount,
               backgroundcolor=\color{white}, #1
    }}
    {}
    \begin{document}


Write this: 

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

And then add these lines:

\begin{teX}
function doit() {
(*@ \hl{var s = "Hello";} @*)
console.log(s);
}
\end{teX}

    \end{document}

Got this:

Result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.