0 Replies Latest reply: Jun 6, 2012 10:55 PM by Dan Allen RSS

Syntax highlighting JavaScript in pdfs generated by asciidoc (via dblatex)

Dan Allen Master

AsciiDoc supports syntax highlighting of code in PDFs when you use the dblatex backend (the default).

 

a2x -f pdf yourdoc.asciidoc

 

However, dblatex does not include support for JavaScript (rather suprisingly). Thus, the following snippet in your document will cause pdf generation to fail:

 

[source,javascript]
----
function add(a, b) {
    return a + b;
}

int total = add(2, 2);
----

 

In order to make this work, you need to define a new language in a custom dblatex style configuration file (extension .sty). AsciiDoc already uses a custom file, and dblatex only supports a single configuration file, so you first need to copy the file into your build directory (or wherever you want to stick it).

 

cp %ASCIIDOC_INSTALL_DIR%/dblatex/asciidoc-dblatex.sty custom-asciidoc-dblatex.sty

 

Next, append the following code to that custom file:

 

\usepackage[usenames,dvipsnames]{xcolor}

% Set custom colors
\definecolor{code}{gray}{0}
\definecolor{canvas}{gray}{0.96}
\definecolor{comment}{rgb}{0, 0.456, 0}
\definecolor{keyword}{rgb}{0.5, 0, 0.5}

% JavaScript is not part of the listings package...
% but thankfully this page shows how to add it:
% http://lenaherrmann.net/2010/05/20/javascript-syntax-highlighting-in-the-latex-listings-package

\lstdefinelanguage{javascript}{
  keywords={typeof, new, true, false, catch, function, return, null, catch, switch, var, if, for, in, while, do, else, case, break},
  ndkeywords={class, export, boolean, throw, implements, import, this},
  sensitive=false,
  comment=[l]{//},
  morecomment=[s][\color{blue}\ttfamily]{/*}{*/},
  morestring=[b]',
  morestring=[b]"
}

% Parameters for formatting code (optional, affects all code listings)
\lstset{
  backgroundcolor=\color{canvas},
  basicstyle=\ttfamily\small\color{code},
  commentstyle=\color{comment},
  identifierstyle=\color{black},
  keywordstyle=\color{keyword}\bfseries,
  ndkeywordstyle=\color{keyword}\bfseries,
  stringstyle=\color{blue}\ttfamily
}

 

Finally, you need to pass this style configuration to the a2x command via the dblatex-opts flag:

 

a2x -f pdf --dblatex-opts="-s custom-asciidoc-dblatex.sty" yourdoc.asciidoc

 

Now you should see the JavaScript code highlighted in the generated pdf.

 

This tip builds on the following blog post on this topic: http://lenaherrmann.net/2010/05/20/javascript-syntax-highlighting-in-the-latex-listings-package