Better R support in pygments by monkey patching SLexer

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.

Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.