eric6/ThirdParty/Pygments/pygments/formatters/svg.py

changeset 6942
2602857055c5
parent 5713
6762afd9f963
child 7547
21b0534faebc
equal deleted inserted replaced
6941:f99d60d6b59b 6942:2602857055c5
1 # -*- coding: utf-8 -*-
2 """
3 pygments.formatters.svg
4 ~~~~~~~~~~~~~~~~~~~~~~~
5
6 Formatter for SVG output.
7
8 :copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
9 :license: BSD, see LICENSE for details.
10 """
11
12 from pygments.formatter import Formatter
13 from pygments.util import get_bool_opt, get_int_opt
14
15 __all__ = ['SvgFormatter']
16
17
18 def escape_html(text):
19 """Escape &, <, > as well as single and double quotes for HTML."""
20 return text.replace('&', '&amp;'). \
21 replace('<', '&lt;'). \
22 replace('>', '&gt;'). \
23 replace('"', '&quot;'). \
24 replace("'", '&#39;')
25
26
27 class2style = {}
28
29 class SvgFormatter(Formatter):
30 """
31 Format tokens as an SVG graphics file. This formatter is still experimental.
32 Each line of code is a ``<text>`` element with explicit ``x`` and ``y``
33 coordinates containing ``<tspan>`` elements with the individual token styles.
34
35 By default, this formatter outputs a full SVG document including doctype
36 declaration and the ``<svg>`` root element.
37
38 .. versionadded:: 0.9
39
40 Additional options accepted:
41
42 `nowrap`
43 Don't wrap the SVG ``<text>`` elements in ``<svg><g>`` elements and
44 don't add a XML declaration and a doctype. If true, the `fontfamily`
45 and `fontsize` options are ignored. Defaults to ``False``.
46
47 `fontfamily`
48 The value to give the wrapping ``<g>`` element's ``font-family``
49 attribute, defaults to ``"monospace"``.
50
51 `fontsize`
52 The value to give the wrapping ``<g>`` element's ``font-size``
53 attribute, defaults to ``"14px"``.
54
55 `xoffset`
56 Starting offset in X direction, defaults to ``0``.
57
58 `yoffset`
59 Starting offset in Y direction, defaults to the font size if it is given
60 in pixels, or ``20`` else. (This is necessary since text coordinates
61 refer to the text baseline, not the top edge.)
62
63 `ystep`
64 Offset to add to the Y coordinate for each subsequent line. This should
65 roughly be the text size plus 5. It defaults to that value if the text
66 size is given in pixels, or ``25`` else.
67
68 `spacehack`
69 Convert spaces in the source to ``&#160;``, which are non-breaking
70 spaces. SVG provides the ``xml:space`` attribute to control how
71 whitespace inside tags is handled, in theory, the ``preserve`` value
72 could be used to keep all whitespace as-is. However, many current SVG
73 viewers don't obey that rule, so this option is provided as a workaround
74 and defaults to ``True``.
75 """
76 name = 'SVG'
77 aliases = ['svg']
78 filenames = ['*.svg']
79
80 def __init__(self, **options):
81 Formatter.__init__(self, **options)
82 self.nowrap = get_bool_opt(options, 'nowrap', False)
83 self.fontfamily = options.get('fontfamily', 'monospace')
84 self.fontsize = options.get('fontsize', '14px')
85 self.xoffset = get_int_opt(options, 'xoffset', 0)
86 fs = self.fontsize.strip()
87 if fs.endswith('px'): fs = fs[:-2].strip()
88 try:
89 int_fs = int(fs)
90 except:
91 int_fs = 20
92 self.yoffset = get_int_opt(options, 'yoffset', int_fs)
93 self.ystep = get_int_opt(options, 'ystep', int_fs + 5)
94 self.spacehack = get_bool_opt(options, 'spacehack', True)
95 self._stylecache = {}
96
97 def format_unencoded(self, tokensource, outfile):
98 """
99 Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``
100 tuples and write it into ``outfile``.
101
102 For our implementation we put all lines in their own 'line group'.
103 """
104 x = self.xoffset
105 y = self.yoffset
106 if not self.nowrap:
107 if self.encoding:
108 outfile.write('<?xml version="1.0" encoding="%s"?>\n' %
109 self.encoding)
110 else:
111 outfile.write('<?xml version="1.0"?>\n')
112 outfile.write('<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" '
113 '"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/'
114 'svg10.dtd">\n')
115 outfile.write('<svg xmlns="http://www.w3.org/2000/svg">\n')
116 outfile.write('<g font-family="%s" font-size="%s">\n' %
117 (self.fontfamily, self.fontsize))
118 outfile.write('<text x="%s" y="%s" xml:space="preserve">' % (x, y))
119 for ttype, value in tokensource:
120 style = self._get_style(ttype)
121 tspan = style and '<tspan' + style + '>' or ''
122 tspanend = tspan and '</tspan>' or ''
123 value = escape_html(value)
124 if self.spacehack:
125 value = value.expandtabs().replace(' ', '&#160;')
126 parts = value.split('\n')
127 for part in parts[:-1]:
128 outfile.write(tspan + part + tspanend)
129 y += self.ystep
130 outfile.write('</text>\n<text x="%s" y="%s" '
131 'xml:space="preserve">' % (x, y))
132 outfile.write(tspan + parts[-1] + tspanend)
133 outfile.write('</text>')
134
135 if not self.nowrap:
136 outfile.write('</g></svg>\n')
137
138 def _get_style(self, tokentype):
139 if tokentype in self._stylecache:
140 return self._stylecache[tokentype]
141 otokentype = tokentype
142 while not self.style.styles_token(tokentype):
143 tokentype = tokentype.parent
144 value = self.style.style_for_token(tokentype)
145 result = ''
146 if value['color']:
147 result = ' fill="#' + value['color'] + '"'
148 if value['bold']:
149 result += ' font-weight="bold"'
150 if value['italic']:
151 result += ' font-style="italic"'
152 self._stylecache[otokentype] = result
153 return result

eric ide

mercurial