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

    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:


      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:


      % Set custom colors
      \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
        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},
      % Parameters for formatting code (optional, affects all code listings)


      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