可用的格式化器¶
本页列出了所有的内置格式化器。
通用选项¶
所有格式化器都支持这些选项:
- encoding
如果给定,必须是一个编码名称(如
"utf-8"
)。这将用于在输出中把标记字符串(Unicode 字符串)转换成字节字符串(默认:None
)。如果给了full
选项,它也将被写入适合文档格式的编码声明中(例如,HTML 中的meta content-type
指令或 LaTeX 中调用inputenc
包)。如果这是
""
或None
,Unicode 字符串将被写入输出文件,大多数类文件对象都不支持。例如,如果调用pygments.highlight()
时没有outfile
参数,并且格式化器的encoding
设置为None
,将返回一个Unicode字符串,因为它使用一个StringIO.StringIO
对象,支持 Unicode 参数给write()
。使用一个普通的文件对象是不行的。0.6 新版功能.
- outencoding
当从命令行使用 Pygments 时,任何 encoding 选项都会传递给 lexer 和格式化器。这有时是不可取的,例如,如果你想把输入编码设置为
"guess"
。因此,引入了outencoding
,如果给出的话,它将覆盖格式化器的encoding
。0.7 新版功能.
格式化器类¶
所有这些类都可以从 pygments.formatters
导入。
- class BBCodeFormatter¶
- 短名称
bbcode, bb
- 文件名
None
Format tokens with BBcodes. These formatting codes are used by many bulletin boards, so you can highlight your sourcecode with pygments before posting it there.
This formatter has no support for background colors and borders, as there are no common BBcode tags for that.
Some board systems (e.g. phpBB) don’t support colors in their [code] tag, so you can’t use the highlighting together with that tag. Text in a [code] tag usually is shown with a monospace font (which this formatter can do with the
monofont
option) and no spaces (which you need for indentation) are removed.Additional options accepted:
- style
The style to use, can be a string or a Style subclass (default:
'default'
).- codetag
If set to true, put the output into
[code]
tags (default:false
)- monofont
If set to true, add a tag to show the code with a monospace font (default:
false
).
- class BmpImageFormatter¶
- 短名称
bmp, bitmap
- 文件名
*.bmp
Create a bitmap image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.
1.0 新版功能.
- class GifImageFormatter¶
- 短名称
gif
- 文件名
*.gif
Create a GIF image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.
1.0 新版功能.
- class GroffFormatter¶
- 短名称
groff, troff, roff
- 文件名
None
Format tokens with groff escapes to change their color and font style.
2.11 新版功能.
Additional options accepted:
- style
The style to use, can be a string or a Style subclass (default:
'default'
).- monospaced
If set to true, monospace font will be used (default:
true
).- linenos
If set to true, print the line numbers (default:
false
).- wrap
Wrap lines to the specified number of characters. Disabled if set to 0 (default:
0
).
- class HtmlFormatter¶
- 短名称
html
- 文件名
*.html, *.htm
Format tokens as HTML 4
<span>
tags within a<pre>
tag, wrapped in a<div>
tag. The<div>
’s CSS class can be set by the cssclass option.If the linenos option is set to
"table"
, the<pre>
is additionally wrapped inside a<table>
which has one row and two cells: one containing the line numbers and one containing the code. Example:<div class="highlight" > <table><tr> <td class="linenos" title="click to toggle" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"> <pre>1 2</pre> </td> <td class="code"> <pre><span class="Ke">def </span><span class="NaFu">foo</span>(bar): <span class="Ke">pass</span> </pre> </td> </tr></table></div>
(whitespace added to improve clarity).
Wrapping can be disabled using the nowrap option.
A list of lines can be specified using the hl_lines option to make these lines highlighted (as of Pygments 0.11).
With the full option, a complete HTML 4 document is output, including the style definitions inside a
<style>
tag, or in a separate file if the cssfile option is given.When tagsfile is set to the path of a ctags index file, it is used to generate hyperlinks from names to their definition. You must enable lineanchors and run ctags with the -n option for this to work. The python-ctags module from PyPI must be installed to use this feature; otherwise a RuntimeError will be raised.
The get_style_defs(arg=’’) method of a HtmlFormatter returns a string containing CSS rules for the CSS classes used by the formatter. The argument arg can be used to specify additional CSS selectors that are prepended to the classes. A call fmter.get_style_defs(‘td .code’) would result in the following CSS classes:
td .code .kw { font-weight: bold; color: #00FF00 } td .code .cm { color: #999999 } ...
If you have Pygments 0.6 or higher, you can also pass a list or tuple to the get_style_defs() method to request multiple prefixes for the tokens:
formatter.get_style_defs(['div.syntax pre', 'pre.syntax'])
The output would then look like this:
div.syntax pre .kw, pre.syntax .kw { font-weight: bold; color: #00FF00 } div.syntax pre .cm, pre.syntax .cm { color: #999999 } ...
Additional options accepted:
- nowrap
If set to
True
, don’t wrap the tokens at all, not even inside a<pre>
tag. This disables most other options (default:False
).- full
Tells the formatter to output a “full” document, i.e. a complete self-contained document (default:
False
).- title
If full is true, the title that should be used to caption the document (default:
''
).- style
The style to use, can be a string or a Style subclass (default:
'default'
). This option has no effect if the cssfile and noclobber_cssfile option are given and the file specified in cssfile exists.- noclasses
If set to true, token
<span>
tags (as well as line number elements) will not use CSS classes, but inline styles. This is not recommended for larger pieces of code since it increases output size by quite a bit (default:False
).- classprefix
Since the token types use relatively short class names, they may clash with some of your own class names. In this case you can use the classprefix option to give a string to prepend to all Pygments-generated CSS class names for token types. Note that this option also affects the output of get_style_defs().
- cssclass
CSS class for the wrapping
<div>
tag (default:'highlight'
). If you set this option, the default selector for get_style_defs() will be this class.0.9 新版功能: If you select the
'table'
line numbers, the wrapping table will have a CSS class of this string plus'table'
, the default is accordingly'highlighttable'
.- cssstyles
Inline CSS styles for the wrapping
<div>
tag (default:''
).- prestyles
Inline CSS styles for the
<pre>
tag (default:''
).0.11 新版功能.
- cssfile
If the full option is true and this option is given, it must be the name of an external file. If the filename does not include an absolute path, the file’s path will be assumed to be relative to the main output file’s path, if the latter can be found. The stylesheet is then written to this file instead of the HTML file.
0.6 新版功能.
- noclobber_cssfile
If cssfile is given and the specified file exists, the css file will not be overwritten. This allows the use of the full option in combination with a user specified css file. Default is
False
.1.1 新版功能.
- linenos
If set to
'table'
, output line numbers as a table with two cells, one containing the line numbers, the other the whole code. This is copy-and-paste-friendly, but may cause alignment problems with some browsers or fonts. If set to'inline'
, the line numbers will be integrated in the<pre>
tag that contains the code (that setting is new in Pygments 0.8).For compatibility with Pygments 0.7 and earlier, every true value except
'inline'
means the same as'table'
(in particular, that means alsoTrue
).The default value is
False
, which means no line numbers at all.Note: with the default (“table”) line number mechanism, the line numbers and code can have different line heights in Internet Explorer unless you give the enclosing
<pre>
tags an explicitline-height
CSS property (you get the default line spacing withline-height: 125%
).- hl_lines
Specify a list of lines to be highlighted. The line numbers are always relative to the input (i.e. the first line is line 1) and are independent of linenostart.
0.11 新版功能.
- linenostart
The line number for the first line (default:
1
).- linenostep
If set to a number n > 1, only every nth line number is printed.
- linenospecial
If set to a number n > 0, every nth line number is given the CSS class
"special"
(default:0
).- nobackground
If set to
True
, the formatter won’t output the background color for the wrapping element (this automatically defaults toFalse
when there is no wrapping element [eg: no argument for the get_syntax_defs method given]) (default:False
).0.6 新版功能.
- lineseparator
This string is output between lines of code. It defaults to
"\n"
, which is enough to break a line inside<pre>
tags, but you can e.g. set it to"<br>"
to get HTML line breaks.0.7 新版功能.
- lineanchors
If set to a nonempty string, e.g.
foo
, the formatter will wrap each output line in an anchor tag with anid
(and name) offoo-linenumber
. This allows easy linking to certain lines.0.9 新版功能.
- linespans
If set to a nonempty string, e.g.
foo
, the formatter will wrap each output line in a span tag with anid
offoo-linenumber
. This allows easy access to lines via javascript.1.6 新版功能.
- anchorlinenos
If set to True, will wrap line numbers in <a> tags. Used in combination with linenos and lineanchors.
- tagsfile
If set to the path of a ctags file, wrap names in anchor tags that link to their definitions. lineanchors should be used, and the tags file should specify line numbers (see the -n option to ctags).
1.6 新版功能.
- tagurlformat
A string formatting pattern used to generate links to ctags definitions. Available variables are %(path)s, %(fname)s and %(fext)s. Defaults to an empty string, resulting in just #prefix-number links.
1.6 新版功能.
- filename
A string used to generate a filename when rendering
<pre>
blocks, for example if displaying source code. If linenos is set to'table'
then the filename will be rendered in an initial row containing a single <th> which spans both columns.2.1 新版功能.
- wrapcode
Wrap the code inside
<pre>
blocks using<code>
, as recommended by the HTML5 specification.2.4 新版功能.
Subclassing the HTML formatter
0.7 新版功能.
The HTML formatter is now built in a way that allows easy subclassing, thus customizing the output HTML code. The format() method calls self._format_lines() which returns a generator that yields tuples of
(1, line)
, where the1
indicates that theline
is a line of the formatted source code.If the nowrap option is set, the generator is the iterated over and the resulting HTML is output.
Otherwise, format() calls self.wrap(), which wraps the generator with other generators. These may add some HTML code to the one generated by _format_lines(), either by modifying the lines generated by the latter, then yielding them again with
(1, line)
, and/or by yielding other HTML code before or after the lines, with(0, html)
. The distinction between source lines and other code makes it possible to wrap the generator multiple times.The default wrap() implementation adds a
<div>
and a<pre>
tag.A custom HtmlFormatter subclass could look like this:
class CodeHtmlFormatter(HtmlFormatter): def wrap(self, source, outfile): return self._wrap_code(source) def _wrap_code(self, source): yield 0, '<code>' for i, t in source: if i == 1: # it's a line of formatted code t += '<br>' yield i, t yield 0, '</code>'
This results in wrapping the formatted lines with a
<code>
tag, where the source lines are broken using<br>
tags.After calling wrap(), the format() method also adds the “line numbers” and/or “full document” wrappers if the respective options are set. Then, all HTML yielded by the wrapped generator is output.
- class IRCFormatter¶
- 短名称
irc, IRC
- 文件名
None
Format tokens with IRC color sequences
The get_style_defs() method doesn’t do anything special since there is no support for common styles.
Options accepted:
- bg
Set to
"light"
or"dark"
depending on the terminal’s background (default:"light"
).- colorscheme
A dictionary mapping token types to (lightbg, darkbg) color names or
None
(default:None
= use builtin colorscheme).- linenos
Set to
True
to have line numbers in the output as well (default:False
= no line numbers).
- class ImageFormatter¶
- 短名称
img, IMG, png
- 文件名
*.png
Create a PNG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.
0.10 新版功能.
Additional options accepted:
- image_format
An image format to output to that is recognised by PIL, these include:
“PNG” (default)
“JPEG”
“BMP”
“GIF”
- line_pad
The extra spacing (in pixels) between each line of text.
Default: 2
- font_name
The font name to be used as the base font from which others, such as bold and italic fonts will be generated. This really should be a monospace font to look sane.
- Default: “Courier New” on Windows, “Menlo” on Mac OS, and
“DejaVu Sans Mono” on *nix
- font_size
The font size in points to be used.
Default: 14
- image_pad
The padding, in pixels to be used at each edge of the resulting image.
Default: 10
- line_numbers
Whether line numbers should be shown: True/False
Default: True
- line_number_start
The line number of the first line.
Default: 1
- line_number_step
The step used when printing line numbers.
Default: 1
- line_number_bg
The background colour (in “#123456” format) of the line number bar, or None to use the style background color.
Default: “#eed”
- line_number_fg
The text color of the line numbers (in “#123456”-like format).
Default: “#886”
- line_number_chars
The number of columns of line numbers allowable in the line number margin.
Default: 2
- line_number_bold
Whether line numbers will be bold: True/False
Default: False
- line_number_italic
Whether line numbers will be italicized: True/False
Default: False
- line_number_separator
Whether a line will be drawn between the line number area and the source code area: True/False
Default: True
- line_number_pad
The horizontal padding (in pixels) between the line number margin, and the source code area.
Default: 6
- hl_lines
Specify a list of lines to be highlighted.
1.2 新版功能.
Default: empty list
- hl_color
Specify the color for highlighting lines.
1.2 新版功能.
Default: highlight color of the selected style
- class JpgImageFormatter¶
- 短名称
jpg, jpeg
- 文件名
*.jpg
Create a JPEG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.
1.0 新版功能.
- class LatexFormatter¶
- 短名称
latex, tex
- 文件名
*.tex
Format tokens as LaTeX code. This needs the fancyvrb and color standard packages.
Without the full option, code is formatted as one
Verbatim
environment, like this:\begin{Verbatim}[commandchars=\\\{\}] \PY{k}{def }\PY{n+nf}{foo}(\PY{n}{bar}): \PY{k}{pass} \end{Verbatim}
The special command used here (
\PY
) and all the other macros it needs are output by the get_style_defs method.With the full option, a complete LaTeX document is output, including the command definitions in the preamble.
The get_style_defs() method of a LatexFormatter returns a string containing
\def
commands defining the macros needed inside theVerbatim
environments.Additional options accepted:
- style
The style to use, can be a string or a Style subclass (default:
'default'
).- full
Tells the formatter to output a “full” document, i.e. a complete self-contained document (default:
False
).- title
If full is true, the title that should be used to caption the document (default:
''
).- docclass
If the full option is enabled, this is the document class to use (default:
'article'
).- preamble
If the full option is enabled, this can be further preamble commands, e.g.
\usepackage
(default:''
).- linenos
If set to
True
, output line numbers (default:False
).- linenostart
The line number for the first line (default:
1
).- linenostep
If set to a number n > 1, only every nth line number is printed.
- verboptions
Additional options given to the Verbatim environment (see the fancyvrb docs for possible values) (default:
''
).- commandprefix
The LaTeX commands used to produce colored output are constructed using this prefix and some letters (default:
'PY'
).0.7 新版功能.
在 0.10 版更改: The default is now
'PY'
instead of'C'
.- texcomments
If set to
True
, enables LaTeX comment lines. That is, LaTex markup in comment tokens is not escaped so that LaTeX can render it (default:False
).1.2 新版功能.
- mathescape
If set to
True
, enables LaTeX math mode escape in comments. That is,'$...$'
inside a comment will trigger math mode (default:False
).1.2 新版功能.
- escapeinside
If set to a string of length 2, enables escaping to LaTeX. Text delimited by these 2 characters is read as LaTeX code and typeset accordingly. It has no effect in string literals. It has no effect in comments if texcomments or mathescape is set. (default:
''
).2.0 新版功能.
- envname
Allows you to pick an alternative environment name replacing Verbatim. The alternate environment still has to support Verbatim’s option syntax. (default:
'Verbatim'
).2.0 新版功能.
- class NullFormatter¶
- 短名称
text, null
- 文件名
*.txt
Output the text unchanged without any formatting.
- class PangoMarkupFormatter¶
- 短名称
pango, pangomarkup
- 文件名
None
Format tokens as Pango Markup code. It can then be rendered to an SVG.
2.9 新版功能.
- class RawTokenFormatter¶
- 短名称
raw, tokens
- 文件名
*.raw
Format tokens as a raw representation for storing token streams.
The format is
tokentype<TAB>repr(tokenstring)\n
. The output can later be converted to a token stream with the RawTokenLexer, described in the lexer list.Only two options are accepted:
- compress
If set to
'gz'
or'bz2'
, compress the output with the given compression algorithm after encoding (default:''
).- error_color
If set to a color name, highlight error tokens using that color. If set but with no value, defaults to
'red'
.0.11 新版功能.
- class RtfFormatter¶
- 短名称
rtf
- 文件名
*.rtf
Format tokens as RTF markup. This formatter automatically outputs full RTF documents with color information and other useful stuff. Perfect for Copy and Paste into Microsoft(R) Word(R) documents.
Please note that
encoding
andoutencoding
options are ignored. The RTF format is ASCII natively, but handles unicode characters correctly thanks to escape sequences.0.6 新版功能.
Additional options accepted:
- style
The style to use, can be a string or a Style subclass (default:
'default'
).- fontface
The used font family, for example
Bitstream Vera Sans
. Defaults to some generic font which is supposed to have fixed width.- fontsize
Size of the font used. Size is specified in half points. The default is 24 half-points, giving a size 12 font.
2.0 新版功能.
- class SvgFormatter¶
- 短名称
svg
- 文件名
*.svg
Format tokens as an SVG graphics file. This formatter is still experimental. Each line of code is a
<text>
element with explicitx
andy
coordinates containing<tspan>
elements with the individual token styles.By default, this formatter outputs a full SVG document including doctype declaration and the
<svg>
root element.0.9 新版功能.
Additional options accepted:
- nowrap
Don’t wrap the SVG
<text>
elements in<svg><g>
elements and don’t add a XML declaration and a doctype. If true, the fontfamily and fontsize options are ignored. Defaults toFalse
.- fontfamily
The value to give the wrapping
<g>
element’sfont-family
attribute, defaults to"monospace"
.- fontsize
The value to give the wrapping
<g>
element’sfont-size
attribute, defaults to"14px"
.- linenos
If
True
, add line numbers (default:False
).- linenostart
The line number for the first line (default:
1
).- linenostep
If set to a number n > 1, only every nth line number is printed.
- linenowidth
Maximum width devoted to line numbers (default:
3*ystep
, sufficient for up to 4-digit line numbers. Increase width for longer code blocks).- xoffset
Starting offset in X direction, defaults to
0
.- yoffset
Starting offset in Y direction, defaults to the font size if it is given in pixels, or
20
else. (This is necessary since text coordinates refer to the text baseline, not the top edge.)- ystep
Offset to add to the Y coordinate for each subsequent line. This should roughly be the text size plus 5. It defaults to that value if the text size is given in pixels, or
25
else.- spacehack
Convert spaces in the source to
 
, which are non-breaking spaces. SVG provides thexml:space
attribute to control how whitespace inside tags is handled, in theory, thepreserve
value could be used to keep all whitespace as-is. However, many current SVG viewers don’t obey that rule, so this option is provided as a workaround and defaults toTrue
.
- class Terminal256Formatter¶
- 短名称
terminal256, console256, 256
- 文件名
None
Format tokens with ANSI color sequences, for output in a 256-color terminal or console. Like in TerminalFormatter color sequences are terminated at newlines, so that paging the output works correctly.
The formatter takes colors from a style defined by the style option and converts them to nearest ANSI 256-color escape sequences. Bold and underline attributes from the style are preserved (and displayed).
0.9 新版功能.
在 2.2 版更改: If the used style defines foreground colors in the form
#ansi*
, then Terminal256Formatter will map these to non extended foreground color. See 终端样式 for more information.在 2.4 版更改: The ANSI color names have been updated with names that are easier to understand and align with colornames of other projects and terminals. See this table for more information.
Options accepted:
- style
The style to use, can be a string or a Style subclass (default:
'default'
).- linenos
Set to
True
to have line numbers on the terminal output as well (default:False
= no line numbers).
- class TerminalFormatter¶
- 短名称
terminal, console
- 文件名
None
Format tokens with ANSI color sequences, for output in a text console. Color sequences are terminated at newlines, so that paging the output works correctly.
The get_style_defs() method doesn’t do anything special since there is no support for common styles.
Options accepted:
- bg
Set to
"light"
or"dark"
depending on the terminal’s background (default:"light"
).- colorscheme
A dictionary mapping token types to (lightbg, darkbg) color names or
None
(default:None
= use builtin colorscheme).- linenos
Set to
True
to have line numbers on the terminal output as well (default:False
= no line numbers).
- class TerminalTrueColorFormatter¶
- 短名称
terminal16m, console16m, 16m
- 文件名
None
Format tokens with ANSI color sequences, for output in a true-color terminal or console. Like in TerminalFormatter color sequences are terminated at newlines, so that paging the output works correctly.
2.1 新版功能.
Options accepted:
- style
The style to use, can be a string or a Style subclass (default:
'default'
).
- class TestcaseFormatter¶
- 短名称
testcase
- 文件名
None
Format tokens as appropriate for a new testcase.
2.0 新版功能.