Better R support in pygments by monkey patching SLexer

[This article was first published on f3lix » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

I started using knitr with reStructuredText today and I found that the syntax highlighting with pygments (used by rst2html.py) was not as nice as the output of pandoc. So I ended up doing some monkeypatching.

Try adding the following to rst2html.py:

# SLexer is the lexer used for R
from pygments.lexers.math import SLexer
from pygments.token import Keyword, Name

# monkey patching SLexer ...

# add some builtin functions (TODO: add more)
SLexer.tokens['keywords'].append(
   (r'(?<![A-Za-z0-9_-])(c|library)(?=\()', Name.Builtin))

# treat all names in front of a parenthesis as function names
SLexer.tokens['keywords'].append(
   (r'[a-zA-Z][a-zA-Z_0-9]+(?=\s*\()', Name.Function))

# parameter names inside function calls/definitions
SLexer.tokens['root'].insert(0,
   (r'(?<=[\(,])\s*[a-z]+\s*(?==)', Name.Attribute)) 

Before:

After:

Note: I assume you already added pygments’ rst-directive.py to rst2html.py.

To leave a comment for the author, please follow the link and comment on their blog: f3lix » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)