1
# -*- coding: utf-8 -*-
3
pygments.formatters.rtf
4
~~~~~~~~~~~~~~~~~~~~~~~
6
A formatter that generates RTF files.
8
:copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS.
9
:license: BSD, see LICENSE for details.
12
from pygments.formatter import Formatter
15
__all__ = ['RtfFormatter']
18
class RtfFormatter(Formatter):
20
Format tokens as RTF markup. This formatter automatically outputs full RTF
21
documents with color information and other useful stuff. Perfect for Copy and
22
Paste into Microsoft® Word® documents.
24
*New in Pygments 0.6.*
26
Additional options accepted:
29
The style to use, can be a string or a Style subclass (default:
33
The used font famliy, for example ``Bitstream Vera Sans``. Defaults to
34
some generic font which is supposed to have fixed width.
42
def __init__(self, **options):
44
Additional options accepted:
47
Name of the font used. Could for example be ``'Courier New'``
48
to further specify the default which is ``'\fmodern'``. The RTF
49
specification claims that ``\fmodern`` are "Fixed-pitch serif
50
and sans serif fonts". Hope every RTF implementation thinks
51
the same about modern...
53
Formatter.__init__(self, **options)
54
self.fontface = options.get('fontface') or ''
56
def _escape(self, text):
57
return text.replace('\\', '\\\\') \
58
.replace('{', '\\{') \
61
def _escape_text(self, text):
62
# empty strings, should give a small performance improvment
67
text = self._escape(text)
68
if self.encoding in ('utf-8', 'utf-16', 'utf-32'):
69
encoding = 'iso-8859-15'
71
encoding = self.encoding or 'iso-8859-15'
76
ansic = c.encode(encoding, 'ignore') or '?'
78
ansic = '\\\'%x' % ord(ansic)
81
buf.append(r'\ud{\u%d%s}' % (ord(c), ansic))
85
return ''.join(buf).replace('\n', '\\par\n')
87
def format_unencoded(self, tokensource, outfile):
89
outfile.write(r'{\rtf1\ansi\deff0'
90
r'{\fonttbl{\f0\fmodern\fprq1\fcharset0%s;}}'
91
r'{\colortbl;' % (self.fontface and
92
' ' + self._escape(self.fontface) or
95
# convert colors and save them in a mapping to access them later.
98
for _, style in self.style:
99
for color in style['color'], style['bgcolor'], style['border']:
100
if color and color not in color_mapping:
101
color_mapping[color] = offset
102
outfile.write(r'\red%d\green%d\blue%d;' % (
108
outfile.write(r'}\f0')
111
for ttype, value in tokensource:
112
while not self.style.styles_token(ttype) and ttype.parent:
114
style = self.style.style_for_token(ttype)
117
buf.append(r'\cb%d' % color_mapping[style['bgcolor']])
119
buf.append(r'\cf%d' % color_mapping[style['color']])
124
if style['underline']:
127
buf.append(r'\chbrdr\chcfpat%d' %
128
color_mapping[style['border']])
131
outfile.write('{%s ' % start)
132
outfile.write(self._escape_text(value))