summaryrefslogtreecommitdiffstats
path: root/gitsrht/annotations.py
blob: d8a6f12774a6ff83afc6d2446695e1508a828d0a (plain)
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
from pygments.formatter import Formatter
from pygments.token import Token, STANDARD_TYPES
from pygments.util import string_types, iteritems
from srht.markdown import markdown
from urllib.parse import urlparse

_escape_html_table = {
    ord('&'): u'&',
    ord('<'): u'&lt;',
    ord('>'): u'&gt;',
    ord('"'): u'&quot;',
    ord("'"): u'&#39;',
}

def escape_html(text, table=_escape_html_table):
    return text.translate(table)

def _get_ttype_class(ttype):
    fname = STANDARD_TYPES.get(ttype)
    if fname:
        return fname
    aname = ''
    while fname is None:
        aname = '-' + ttype[-1] + aname
        ttype = ttype.parent
        fname = STANDARD_TYPES.get(ttype)
    return fname + aname

# Fork of the pygments HtmlFormatter (BSD licensed)
# The main difference is that it relies on AnnotatedFormatter to escape the
# HTML tags in the source. Other features we don't use are removed to keep it
# slim.
class _BaseFormatter(Formatter):
    def __init__(self):
        super().__init__()
        self._create_stylesheet()

    def get_style_defs(self, arg=None):
        """
        Return CSS style definitions for the classes produced by the current
        highlighting style. ``arg`` can be a string or list of selectors to
        insert before the token type classes.
        """
        if arg is None:
            arg = ".highlight"
        if isinstance(arg, string_types):
            args = [arg]
        else:
            args = list(arg)

        def prefix(cls):
            if cls:
                cls = '.' + cls
            tmp = []
            for arg in args:
                tmp.append((arg and arg + ' ' or '') + cls)
            return ', '.join(tmp)

        styles = [(level, ttype, cls, style)
                  for cls, (style, ttype, level) in iteritems(self.class2style)
                  if cls and style]
        styles.sort()
        lines = ['%s { %s } /* %s */' % (prefix(cls), style, repr(ttype)[6:])
                 for (level, ttype, cls, style) in styles]
        return '\n'.join(lines)

    def _get_css_class(self, ttype):
        """Return the css class of this token type prefixed with
        the classprefix option."""
        ttypeclass = _get_ttype_class(ttype)
        if ttypeclass:
            return ttypeclass
        return ''

    def _get_css_classes(self, ttype):
        """Return the css classes of this token type prefixed with
        the classprefix option."""
        cls = self._get_css_class(ttype)
        while ttype not in STANDARD_TYPES:
            ttype = ttype.parent
            cls = self._get_css_class(ttype) + ' ' + cls
        return cls

    def _create_stylesheet(self):
        t2c = self.ttype2class = {Token: ''}
        c2s = self.class2style = {}
        for ttype, ndef in self.style:
            name = self._get_css_class(ttype)
            style = ''
            if ndef['color']:
                style += 'color: #%s; ' % ndef['color']
            if ndef['bold']:
                style += 'font-weight: bold; '
            if ndef['italic']:
                style += 'font-style: italic; '
            if ndef['underline']:
                style += 'text-decoration: underline; '
            if ndef['bgcolor']:
                style += 'background-color: #%s; ' % ndef['bgcolor']
            if ndef['border']:
                style += 'border: 1px solid #%s; ' % ndef['border']
            if style:
                t2c[ttype] = name
                # save len(ttype) to enable ordering the styles by
                # hierarchy (necessary for CSS cascading rules!)
                c2s[name] = (style[:-2], ttype, len(ttype))

    def _format_lines(self, tokensource):
        lsep = "\n"
        # for <span style=""> lookup only
        getcls = self.ttype2class.get
        c2s = self.class2style

        lspan = ''
        line = []
        for ttype, value in tokensource:
            cls = self._get_css_classes(ttype)
            cspan = cls and '<span class="%s">' % cls or ''

            parts = value.split('\n')

            # for all but the last line
            for part in parts[:-1]:
                if line:
                    if lspan != cspan:
                        line.extend(((lspan and '</span>'), cspan, part,
                                     (cspan and '</span>'), lsep))
                    else:  # both are the same
                        line.extend((part, (lspan and '</span>'), lsep))
                    yield 1, ''.join(line)
                    line = []
                elif part:
                    yield 1, ''.join((cspan, part, (cspan and '</span>'), lsep))
                else:
                    yield 1, lsep
            # for the last line
            if line and parts[-1]:
                if lspan != cspan:
                    line.extend(((lspan and '</span>'), cspan, parts[-1]))
                    lspan = cspan
                else:
                    line.append(parts[-1])
            elif parts[-1]:
                line = [cspan, parts[-1]]
                lspan = cspan
            # else we neither have to open a new span nor set lspan

        if line:
            line.extend(((lspan and '</span>'), lsep))
            yield 1, ''.join(line)

    def _wrap_div(self, inner):
        yield 0, f"<div class='highlight'>"
        for tup in inner:
            yield tup
        yield 0, '</div>\n'

    def _wrap_pre(self, inner):
        yield 0, '<pre><span></span>'
        for tup in inner:
            yield tup
        yield 0, '</pre>'

    def wrap(self, source, outfile):
        """
        Wrap the ``source``, which is a generator yielding
        individual lines, in custom generators. See docstring
        for `format`. Can be overridden.
        """
        return self._wrap_div(self._wrap_pre(source))

    def format_unencoded(self, tokensource, outfile):
        source = self._format_lines(tokensource)
        source = self.wrap(source, outfile)
        for t, piece in source:
            outfile.write(piece)

def validate_annotation(valid, anno):
    valid.expect("type" in anno, "'type' is required")
    if not valid.ok:
        return
    valid.expect(anno["type"] in ["link", "markdown"],
            f"'{anno['type']} is not a valid annotation type'")
    if anno["type"] == "link":
        for field in ["lineno", "colno", "len"]:
            valid.expect(field in anno, "f'{field}' is required")
            valid.expect(field not in anno or isinstance(anno[field], int),
                    "f'{field}' must be an integer")
        valid.expect("to" in anno, "'to' is required")
        valid.expect("title" not in anno or isinstance(anno["title"], str),
                "'title' must be a string")
        valid.expect("color" not in anno or isinstance(anno["color"], str),
                "'color' must be a string")
        if "color" in anno and anno["color"] != "transparent":
            valid.expect("color" not in anno or len(anno["color"]) == 7,
                    "'color' must be a 7 digit string or 'transparent'")
            valid.expect("color" not in anno or not any(
                c for c in anno["color"].lower() if c not in "#0123456789abcdef"),
                    "'color' must be in hexadecimal or 'transparent'")
    elif anno["type"] == "markdown":
        for field in ["lineno"]:
            valid.expect(field in anno, "f'{field}' is required")
            valid.expect(field not in anno or isinstance(anno[field], int),
                    "f'{field}' must be an integer")
        for field in ["title", "content"]:
            valid.expect(field in anno, "f'{field}' is required")
            valid.expect(field not in anno or isinstance(anno[field], str),
                    "f'{field}' must be a string")

class AnnotatedFormatter(_BaseFormatter):
    def __init__(self, get_annos, link_prefix):
        super().__init__()
        self.get_annos = get_annos
        self.link_prefix = link_prefix

    @property
    def annos(self):
        if hasattr(self, "_annos"):
            return self._annos
        self._annos = dict()
        for anno in (self.get_annos() or list()):
            lineno = int(anno["lineno"])
            self._annos.setdefault(lineno, list())
            self._annos[lineno].append(anno)
            self._annos[lineno] = sorted(self._annos[lineno],
                    key=lambda anno: anno.get("from", -1))
        return self._annos

    def _annotate_token(self, token, colno, annos):
        # TODO: Extend this to support >1 anno per token
        for anno in annos:
            if anno["type"] == "link":
                start = anno["colno"] - 1
                end = anno["colno"] + anno["len"] - 1
                target = anno["to"]
                title = anno.get("title", "")
                color = anno.get("color", None)
                url = urlparse(target)
                if url.scheme == "":
                    target = self.link_prefix + "/" + target
                if start <= colno < end:
                    if color is not None:
                        return (f"<a class='annotation' title='{title}' " +
                            f"href='{escape_html(target)}' " +
                            f"rel='nofollow noopener' " +
                            f"style='background-color: {color}' " +
                            f">{escape_html(token)}</a>""")
                    else:
                        return (f"<a class='annotation' title='{title}' " +
                            f"href='{escape_html(target)}' " +
                            f"rel='nofollow noopener' " +
                            f">{escape_html(token)}</a>""")
            elif anno["type"] == "markdown":
                if "\n" not in token:
                    continue
                title = anno["title"]
                content = anno["content"]
                content = markdown(content, baselevel=6,
                        link_prefix=self.link_prefix)