Question

If I run a python source file through pygments, it outputs html code whose elements class belong to some CSS file pygments is using. Could the style attributes be included in the outputted html so that I don't have to provide a CSS file?

Was it helpful?

Solution

By setting the noclasses attribute to True, only inline styles will be generated. Here's a snippet that does the job just fine:


formatter = HtmlFormatter(style=MyStyle)
formatter.noclasses = True
print highlight(content,PythonLexer(),formatter)

OTHER TIPS

Pass full=True to the HtmlFormatter constructor.

@Ignacio: quite the opposite:

from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter

code = 'print "Hello World"'
print highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))

[ ref.: http://pygments.org/docs/formatters/, see HtmlFormatter ]

( Basically it is the same as Tempus's answer, I just thought that a full code snippet may save a few seconds ) )

PS. The ones who think that the original question is ill-posed, may imagine e.g. the task of pasting highlighted code into a blog entry hosted by a third-party service.

Usually, your code is only one of many things on a web page. You often want code to look different from the other content. You, generally, want to control the style of the code as part of the overall page style. CSS is your first, best choice for this.

However, you can embed the styles in the HTML if that seems better. Here's an example that shows the <style> tag in the <head> tag.

http://www.w3schools.com/TAGS/tag_style.asp

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top