This post is about adding custom rules for code highlighting for pkgdown site, taking string %>% as an example.

It felt really nice to achieve custom code highlighting on this site with highlight.js (see this post ). After that, I found myself working with pkgdown , one of many great Hadley’s packages. It is “designed to make it quick and easy to build a website for your package”. It converts all package documentation into appropriate HTML pages. Naturally, I had the same question as before: is there an easy way to highlight pipe operator %>% separately? This time the best answer I was able to come up with was “Yes, if you don’t mind some hacking.”

Overview

After looking into HTML code of site built with pkgdown , I noticed next key features of code highlighting:

Text is already parsed with appropriate strings wrapped in <span></span> . This is done during building site with pkgdown::build_site() . Class attribute of <span> is used to customize highlighting.

. This is done during building site with . Class attribute of is used to customize highlighting. Code from reference pages is processed differently. For example, function mean is wrapped as <span class="kw">mean</span> in Home page but <span class='fu'>mean</span> in Reference.

is wrapped as in Home page but in Reference. The most valuable feature of code preprocessing is creating links to appropriate help pages for R functions. This is done with adding <a> tag inside <span> for certain function name.

So the default method of customising code highlighting in pkgdown is to define CSS styles for present classes (which are essentially different across site).

To highlight certain strings, such as %>% , one should parse HTML for certain <span> tags inside <pre> node (tag for preformatted text used for separate code blocks) and add appropriate class for further CSS customisation. This path is described in With adding tag class.

Although this method solves the problem of highlighting the %>% , it is somewhat constrained: one can’t customize parsing rules. For example, there is no easy way to highlight <- differently because it is not wrapped in <span> . I thought it would be better to reuse the existing solution with highlight.js, but I didn’t consider this path for some time because of preformatted nature of code (unlike my previous experience) and concerns about function links to disappear. However, after manually adding necessary JavaScript code, it worked! Well, kind of: reference pages were not highlighted. The good news was that links stayed in place. How to add appropriate JavaScript code to pkgdown site and deal with reference pages is described in With highlight.js

All code and short version of how to use it is placed in my highdown package.