Debian Codegraph @

doc/docs/formatterdevelopment.rst

raw
1 .. -*- mode: rst -*-
2
3 ========================
4 Write your own formatter
5 ========================
6
7 As well as creating :doc:`your own lexer <lexerdevelopment>`, writing a new
8 formatter for Pygments is easy and straightforward.
9
10 A formatter is a class that is initialized with some keyword arguments (the
11 formatter options) and that must provides a `format()` method.
12 Additionally a formatter should provide a `get_style_defs()` method that
13 returns the style definitions from the style in a form usable for the
14 formatter's output format.
15
16
17 Quickstart
18 ==========
19
20 The most basic formatter shipped with Pygments is the `NullFormatter`. It just
21 sends the value of a token to the output stream:
22
23 .. sourcecode:: python
24
25 from pygments.formatter import Formatter
26
27 class NullFormatter(Formatter):
28 def format(self, tokensource, outfile):
29 for ttype, value in tokensource:
30 outfile.write(value)
31
32 As you can see, the `format()` method is passed two parameters: `tokensource`
33 and `outfile`. The first is an iterable of ``(token_type, value)`` tuples,
34 the latter a file like object with a `write()` method.
35
36 Because the formatter is that basic it doesn't overwrite the `get_style_defs()`
37 method.
38
39
40 Styles
41 ======
42
43 Styles aren't instantiated but their metaclass provides some class functions
44 so that you can access the style definitions easily.
45
46 Styles are iterable and yield tuples in the form ``(ttype, d)`` where `ttype`
47 is a token and `d` is a dict with the following keys:
48
49 ``'color'``
50 Hexadecimal color value (eg: ``'ff0000'`` for red) or `None` if not
51 defined.
52
53 ``'bold'``
54 `True` if the value should be bold
55
56 ``'italic'``
57 `True` if the value should be italic
58
59 ``'underline'``
60 `True` if the value should be underlined
61
62 ``'bgcolor'``
63 Hexadecimal color value for the background (eg: ``'eeeeeee'`` for light
64 gray) or `None` if not defined.
65
66 ``'border'``
67 Hexadecimal color value for the border (eg: ``'0000aa'`` for a dark
68 blue) or `None` for no border.
69
70 Additional keys might appear in the future, formatters should ignore all keys
71 they don't support.
72
73
74 HTML 3.2 Formatter
75 ==================
76
77 For an more complex example, let's implement a HTML 3.2 Formatter. We don't
78 use CSS but inline markup (``<u>``, ``<font>``, etc). Because this isn't good
79 style this formatter isn't in the standard library ;-)
80
81 .. sourcecode:: python
82
83 from pygments.formatter import Formatter
84
85 class OldHtmlFormatter(Formatter):
86
87 def __init__(self, **options):
88 Formatter.__init__(self, **options)
89
90 # create a dict of (start, end) tuples that wrap the
91 # value of a token so that we can use it in the format
92 # method later
93 self.styles = {}
94
95 # we iterate over the `_styles` attribute of a style item
96 # that contains the parsed style values.
97 for token, style in self.style:
98 start = end = ''
99 # a style item is a tuple in the following form:
100 # colors are readily specified in hex: 'RRGGBB'
101 if style['color']:
102 start += '<font color="#%s">' % style['color']
103 end = '</font>' + end
104 if style['bold']:
105 start += '<b>'
106 end = '</b>' + end
107 if style['italic']:
108 start += '<i>'
109 end = '</i>' + end
110 if style['underline']:
111 start += '<u>'
112 end = '</u>' + end
113 self.styles[token] = (start, end)
114
115 def format(self, tokensource, outfile):
116 # lastval is a string we use for caching
117 # because it's possible that an lexer yields a number
118 # of consecutive tokens with the same token type.
119 # to minimize the size of the generated html markup we
120 # try to join the values of same-type tokens here
121 lastval = ''
122 lasttype = None
123
124 # wrap the whole output with <pre>
125 outfile.write('<pre>')
126
127 for ttype, value in tokensource:
128 # if the token type doesn't exist in the stylemap
129 # we try it with the parent of the token type
130 # eg: parent of Token.Literal.String.Double is
131 # Token.Literal.String
132 while ttype not in self.styles:
133 ttype = ttype.parent
134 if ttype == lasttype:
135 # the current token type is the same of the last
136 # iteration. cache it
137 lastval += value
138 else:
139 # not the same token as last iteration, but we
140 # have some data in the buffer. wrap it with the
141 # defined style and write it to the output file
142 if lastval:
143 stylebegin, styleend = self.styles[lasttype]
144 outfile.write(stylebegin + lastval + styleend)
145 # set lastval/lasttype to current values
146 lastval = value
147 lasttype = ttype
148
149 # if something is left in the buffer, write it to the
150 # output file, then close the opened <pre> tag
151 if lastval:
152 stylebegin, styleend = self.styles[lasttype]
153 outfile.write(stylebegin + lastval + styleend)
154 outfile.write('</pre>\n')
155
156 The comments should explain it. Again, this formatter doesn't override the
157 `get_style_defs()` method. If we would have used CSS classes instead of
158 inline HTML markup, we would need to generate the CSS first. For that
159 purpose the `get_style_defs()` method exists:
160
161
162 Generating Style Definitions
163 ============================
164
165 Some formatters like the `LatexFormatter` and the `HtmlFormatter` don't
166 output inline markup but reference either macros or css classes. Because
167 the definitions of those are not part of the output, the `get_style_defs()`
168 method exists. It is passed one parameter (if it's used and how it's used
169 is up to the formatter) and has to return a string or ``None``.