I use Sphinx to make a website that contains code samples.
I'm successful using the .. code-block
directive to get syntax highlighting.
But I can't get inline syntax highlighting using this code:
.. role:: bash(code)
:language: bash
Test inline: :bash:`export FOO="bar"`.
.. code-block:: bash
export FOO="bar"
which produces this output i.e. inline code not highlighted while block code is:
Problem to me is that the generated HTML for inline code contains long class names while it does not for code blocks. Here is the output HTML (indented for readability):
<p>Test inline:
<tt class="code bash docutils literal">
<span class="name builtin">
<span class="pre">export</span>
</span>
<span class="name variable">
<span class="pre">FOO</span>
</span>
<span class="operator">
<span class="pre">=</span>
</span>
<span class="literal string double">
<span class="pre">"bar"</span>
</span>
</tt>.
</p>
<p>Test code-block:</p>
<div class="highlight-bash">
<div class="highlight">
<pre>
<span class="nb">export </span>
<span class="nv">FOO</span>
<span class="o">=</span>
<span class="s2">"bar"</span>
</pre>
</div>
</div>
Any help would be very much appreciated.
OK I used this workaround: I generate a css file that contains both short and long names. I'm still interested in the "good" answer.
#!/usr/bin/env python
"""Generate a css file thanks to pygments that will contain both short
and long class names."""
import subprocess
import sys
PYGMENTIZE = 'pygmentize'
def parse_command_line():
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-s', '--style', default='colorful')
parser.add_argument('-p', '--prefix', default='.highlight')
return parser.parse_args()
def pygmentize(style, prefix='.highlight'):
cmd = '{0} -f html -S {1} -a {2}'.format(PYGMENTIZE, style, prefix)
# This will fail if pygmentize does not exist.
try:
p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
except OSError:
print >> sys.stderr, '{0}: command not found'.format(PYGMENTIZE)
exit(1)
out, err = p.communicate()
if p.returncode != 0:
exit(p.returncode)
return out
def main():
args = parse_command_line()
style = args.style
prefix = args.prefix
# Print new css header.
header = """\
/*
* This is pygment css style {0} generated with
* {1}
*/""".format(style, ' '.join(sys.argv))
print header
# Parse pygmentize output.
# Find long names based on comments.
content = pygmentize(style, prefix)
s = content.splitlines()
out = ''
for line in s:
start = line.find("/* ") + 3
end = line.find(" */")
# if line has a comment
if start != 2:
comment = line[start:end]
name = '.' + comment.lower()
arg = line[line.find('{ '): start - 4]
out += '%(prefix)s %(name)s %(arg)s\n' % vars()
print content
print out
if __name__ == '__main__':
main()