August 11, 2017

Blog Entry Syntax Highlighting

  —A method for syntax highlighting using the Pygments Python module.

I've had good success using Pygments to highlight code on this blog. It provides the best of both worlds: a large selection of language support and it generates standalone HTML.

Standalone HTML was important because many of the other solutions relied upon java script and some of these scripts are hosted on external servers which increased the possibility that the highlighting would disappear whenever the server was down.

I use:
pygmentize -f html -O style=emacs,linenos=1 -o test.html cmd.py
To produce:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def cmd(path, *args, **kwargs):
"""
Generate a git log command using the the provided arguments. Empty git log
lines are stripped by this function.

Params:
[in] path - location of repo
[in] args - non-keyword arguments to provide to the git log command
[in] kwargs - keyword arguments to provide to the git log command

Returns: a list of lines returned from the git log command
"""
repo = Repo(path)
assert repo.bare == False
result = list()
for line in repo.git.log(*args, **kwargs).split('\n'):
if len(line) == 0:
continue
result.append(line)
return result

The horizontal scrollbar shows up in the codeblock embedded in the file.

 The crude but effective source code to produce the same result:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from BeautifulSoup import BeautifulSoup as beautify
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
import sys

file = open(sys.argv[1], 'r')

print("""\
<style>
#codeblock {
overflow-x: scroll;
width: auto;
white-space: nowrap;
}
""")
print HtmlFormatter().get_style_defs('.highlight')
print("""\
</style>

<div id="codeblock">
""")
formatter = HtmlFormatter(linenos=True)
print highlight(file.read(), PythonLexer(), formatter)
print("""\
</div>
""")
file.close()
Update: GitHub Gists offers a script which greatly simplifies adding code to your blog.

comments powered by Disqus