aboutsummaryrefslogtreecommitdiffstats
path: root/screenplain/richstring.py
blob: 1859e12ef44835f1a7d264268ae7818503f8a7bb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# Copyright (c) 2011 Martin Vilcans
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license.php

import re
import six

try:
    from html import escape as html_escape
except ImportError:
    from cgi import escape as html_escape

_magic_re = re.compile(u'[\ue700-\ue705]')


def _escape(s):
    """Replaces special HTML characters like <
    and non-ascii characters with ampersand escapes.

    """
    encoded = html_escape(s, quote=False).encode('ascii', 'xmlcharrefreplace')
    # In Py3, encoded is bytes type, so convert it to a string
    return encoded.decode('ascii')


class RichString(object):
    """A sequence of segments where each segment can have its own style."""

    def __init__(self, *segments):
        self.segments = segments

    def __repr__(self):
        if not self.segments:
            return "empty_string"
        return ' + '.join(repr(s) for s in self.segments)

    def __unicode__(self):
        return ''.join(six.text_type(s) for s in self.segments)

    def __str__(self):
        return self.__unicode__()

    def startswith(self, string):
        """Checks if the first segment in this string starts with a
        specific string.

        """
        if '' == string:
            return True
        if not self.segments:
            return False
        return self.segments[0].text.startswith(string)

    def endswith(self, string):
        """Checks if the last segment in this string ends with a
        specific string.

        """
        if '' == string:
            return True
        if not self.segments:
            return False
        return self.segments[-1].text.endswith(string)

    def to_html(self):
        html = ''.join(seg.to_html() for seg in self.segments)
        if html.startswith(' '):
            return '&nbsp;' + html[1:]
        else:
            return html

    def __eq__(self, other):
        return (
            type(self) == type(other) and
            self.segments == other.segments
        )

    def __ne__(self, other):
        return (
            type(self) != type(other) or
            self.segments != other.segments
        )

    def __add__(self, other):
        if hasattr(other, 'segments'):
            return RichString(*(self.segments + other.segments))
        else:
            raise ValueError('Concatenating requires RichString')


class Segment(object):
    """A piece of a rich string. Has a set of styles."""

    def __init__(self, text, styles):
        """
        Creates a segment with a set of styles.
        text is the raw text string, and
        styles is a set of Style subclasses.
        """
        self.styles = set(styles)
        self.text = text

    def __repr__(self):
        return '(%s)(%r)' % (
            '+'.join(
                style.name() for style in self.get_ordered_styles()
            ) or 'plain',
            self.text
        )

    def __unicode__(self):
        return self.text

    def __str__(self):
        return self.text

    def __eq__(self, other):
        return (
            isinstance(other, Segment) and
            self.text == other.text and self.styles == other.styles
        )

    def __ne__(self, other):
        return (
            not isinstance(other, Segment) or
            self.text != other.text or self.styles != other.styles
        )

    def get_ordered_styles(self):
        """Get the styles in this segment in a deterministic order."""
        return [style for style in all_styles if style in self.styles]

    def to_html(self):
        ordered_styles = self.get_ordered_styles()
        return (
            ''.join(style.start_html for style in ordered_styles) +
            re.sub(
                '  +',  # at least two spaces
                lambda m: '&nbsp;' * (len(m.group(0)) - 1) + ' ',
                _escape(self.text),
            ) +
            ''.join(style.end_html for style in reversed(ordered_styles))
        )


class Style(object):
    """Abstract base class for styles"""

    start_magic = ''
    end_magic = ''
    start_html = ''
    end_html = ''

    @classmethod
    def name(cls):
        return cls.__name__.lower()


class Italic(Style):

    parse_re = re.compile(
        # one star
        r'\*'
        # anything but a space, then text
        r'([^\s].*?)'
        # finishing with one star
        r'\*'
        # must not be followed by star
        r'(?!\*)'
    )

    start_magic = u'\ue700'
    end_magic = u'\ue701'

    start_html = '<em>'
    end_html = '</em>'


class Bold(Style):

    parse_re = re.compile(
        # two stars
        r'\*\*'
        # must not be followed by space
        r'(?=\S)'
        # inside text
        r'(.+?[*_]*)'
        # finishing with two stars
        r'(?<=\S)\*\*'
    )

    start_magic = u'\ue702'
    end_magic = u'\ue703'

    start_html = '<strong>'
    end_html = '</strong>'


class Underline(Style):

    parse_re = re.compile(
        # underline
        r'_'
        # must not be followed by space
        r'(?=\S)'
        # inside text
        r'([^_]+)'
        # finishing with underline
        r'(?<=\S)_'
    )

    start_magic = u'\ue704'
    end_magic = u'\ue705'

    start_html = '<u>'  # TODO: use an actual html5 tag
    end_html = '</u>'


class _CreateStyledString(object):
    """Function object that creates a RichString object
    with a single segment with a specified style.
    """
    def __init__(self, styles):
        self.styles = set(styles)

    def __call__(self, text):
        return RichString(Segment(text, self.styles))

    def __add__(self, other):
        return _CreateStyledString(self.styles.union(other.styles))

plain = _CreateStyledString(())
bold = _CreateStyledString((Bold,))
italic = _CreateStyledString((Italic,))
underline = _CreateStyledString((Underline,))

empty_string = RichString()

# A special unicode character to use for a literal '*'
literal_star = u'\ue706'

# All styles. Note: order matters! This is the order they are parsed.
all_styles = (Bold, Italic, Underline)


def _unescape(source):
    r"""Converts backslash-escaped stars in a string to the magic
    "literal star" character.

    >>> _unescape(r'\*hello\*')
    u'\ue706hello\ue706'

    """
    return source.replace('\\*', literal_star)


def _demagic_literals(text):
    r"""Converts "literal star" characters to actual stars: "*"

    >>> _demagic_literals(u'\ue706hello\ue706')
    u'*hello*'
    """
    return text.replace(literal_star, '*')


def parse_emphasis(source):
    """Parses emphasis markers like * and ** in a string
    and returns a RichString object.

    >>> parse_emphasis(u'**hello**')
    (bold)(u'hello')
    >>> parse_emphasis(u'plain')
    (plain)(u'plain')
    >>> parse_emphasis(u'**hello** there')
    (bold)(u'hello') + (plain)(u' there')
    """

    # Convert escaped characters to magic characters so they aren't parsed
    # as emphasis.
    source = _unescape(source)

    for style in all_styles:
        source = style.parse_re.sub(
            style.start_magic + r'\1' + style.end_magic, source
        )

    # Convert magic characters back, so they are printable again.
    source = _demagic_literals(source)

    styles = set()
    segments = []
    pos = 0

    def append(pos, end):
        if(pos == end):
            return
        text = source[pos:end]
        segments.append(Segment(text, styles))

    for match in _magic_re.finditer(source):
        end = match.start()
        append(pos, end)
        pos = end + 1
        magic = match.group(0)
        for style in all_styles:
            if magic == style.start_magic:
                styles.add(style)
            elif magic == style.end_magic:
                styles.remove(style)
    append(pos, len(source))

    return RichString(*segments)