aboutsummaryrefslogtreecommitdiffstats
path: root/screenplain/richstring.py
blob: 92b9bddbd59546ca6719887696fe635b79002de9 (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
# Copyright (c) 2011 Martin Vilcans
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license.php

import re
import cgi

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


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

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

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

    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 starts 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):
        return ''.join(seg.to_html() for seg in self.segments)

    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.styles
            ) or 'plain',
            self.text
        )

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

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

    def to_html(self):
        ordered_styles = list(self.styles)
        return (
            ''.join(style.start_html for style in ordered_styles) +
            cgi.escape(self.text).encode('ascii', 'xmlcharrefreplace') +
            ''.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 = styles

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

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

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


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')
    """
    source = Bold.parse_re.sub(
        Bold.start_magic + r'\1' + Bold.end_magic, source
    )
    source = Italic.parse_re.sub(
        Italic.start_magic + r'\1' + Italic.end_magic, source
    )
    source = Underline.parse_re.sub(
        Underline.start_magic + r'\1' + Underline.end_magic, 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)
        if magic == Bold.start_magic:
            styles.add(Bold)
        elif magic == Bold.end_magic:
            styles.remove(Bold)
        elif magic == Italic.start_magic:
            styles.add(Italic)
        elif magic == Italic.end_magic:
            styles.remove(Italic)
        elif magic == Underline.start_magic:
            styles.add(Underline)
        elif magic == Underline.end_magic:
            styles.remove(Underline)
    append(pos, len(source))

    return RichString(*segments)