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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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
"""Trace visible prose back to the input with half-open Unicode code-point offsets."""
import re
import unicodedata
from bisect import bisect_right
from html import unescape
from html.parser import HTMLParser

from markdown_it import MarkdownIt
from markdown_it.parser_inline import ParserInline
from markdown_it.rules_inline.state_inline import StateInline

import corpus_text as corpus


class View:
    """Sparse runs (display start/end, source start/end, linear). Insertions have no run."""
    __slots__ = ("text", "runs")

    def __init__(self, text, runs=()):
        self.text, self.runs = text, runs

    @classmethod
    def original(cls, text):
        return cls(text, [(0, len(text), 0, len(text), True)] if text else [])

    def slice(self, a, b):
        if a == 0 and b == len(self.text):
            return self
        runs = []
        i = bisect_right(self.runs, a, key=lambda row: row[1])
        while i < len(self.runs):
            left, right, origin, end, linear = self.runs[i]
            if left >= b:
                break
            start, stop = max(a, left), min(b, right)
            if start < stop:
                if linear:
                    origin, end = origin + start-left, origin + stop-left
                runs.append((start-a, stop-a, origin, end, linear))
            i += 1
        return View(self.text[a:b], runs)

    def as_glyph(self, text):
        # An entity, grapheme or dash may produce several displayed characters.
        if self.text == text:
            return self
        if len(self.runs) == 1:
            a, b, s, e, _ = self.runs[0]
            if a == 0 and b == len(self.text) and text:
                return View(text, [(0, len(text), s, e, False)])
        return View(text)

    def strip(self):
        return self.slice(len(self.text)-len(self.text.lstrip()), len(self.text.rstrip()))

    def substitute(self, changes):
        parts, end = [], 0
        for a, b, replacement in changes:
            parts.extend((self.slice(end, a), replacement))
            end = b
        return join([*parts, self.slice(end, len(self.text))]) if parts else self

    def public_map(self):
        result, pos = [], 0
        for a, b, s, e, linear in self.runs:
            if pos < a:
                result.append(dict(start=pos, end=a, source_start=None, source_end=None, kind="unmapped"))
            result.append(dict(start=a, end=b, source_start=s, source_end=e,
                               kind="copy" if linear else "replacement"))
            pos = b
        if pos < len(self.text):
            result.append(dict(start=pos, end=len(self.text), source_start=None, source_end=None, kind="unmapped"))
        return result


def join(parts):
    strings, runs, pos = [], [], 0
    for part in parts:
        strings.append(part.text)
        for a, b, s, e, linear in part.runs:
            if runs and linear and runs[-1][4] and runs[-1][1] == pos+a and runs[-1][3] == s:
                runs[-1] = (runs[-1][0], pos+b, runs[-1][2], e, True)
            else:
                runs.append((pos+a, pos+b, s, e, linear))
        pos += len(part.text)
    return View("".join(strings), runs)


def _canonical(body):
    view = View.original(body)
    if not unicodedata.is_normalized("NFC", body):
        import regex
        view = view.substitute((m.start(), m.end(), view.slice(*m.span()).as_glyph(unicodedata.normalize("NFC", m[0])))
                               for m in regex.finditer(r"\X", body) if not unicodedata.is_normalized("NFC", m[0]))
    if "\r" in view.text:
        view = view.substitute((m.start(), m.end(), view.slice(*m.span()).as_glyph("\n"))
                               for m in re.finditer(r"\r\n?", view.text))
    if re.search(r"[\x00\ud800-\udfff]", view.text):
        view = view.substitute((m.start(), m.end(), View("")) for m in re.finditer(r"[\x00\ud800-\udfff]+", view.text))
    return view


class HTML(corpus._HTMLText):
    def __init__(self, view):
        HTMLParser.__init__(self, convert_charrefs=False)
        self.view = view
        self.lines = [0, *(m.end() for m in re.finditer("\n", view.text))]
        self.pieces, self.skip = [], []

    def source_offset(self):
        line, column = self.getpos()
        return self.lines[line-1] + column

    def handle_data(self, data):
        if not self.skip:
            start = self.source_offset()
            self.pieces.append(self.view.slice(start, start+len(data)))

    def handle_entityref(self, name):
        if self.skip:
            return
        a = self.source_offset()
        b = a+1+len(name)
        if self.view.text[b:b+1] == ";":
            b += 1
        part = self.view.slice(a, b)
        try:
            glyph = unescape(part.text)
        except ValueError:
            # Malformed numeric entities can exceed Python's integer conversion limit.
            return
        self.pieces.append(part.as_glyph(glyph))

    def handle_charref(self, name):
        self.handle_entityref("#"+name)

    @classmethod
    def render(cls, view, hidden=None):
        parser = cls(view)
        if hidden is not None:
            parser.skip = hidden
        parser.feed(view.text)
        parser.close()
        # The corpus parser emits paragraph separators for block/hidden tags.
        return join(p if isinstance(p, View) else View(p) for p in parser.pieces)

# markdown-it-py and markdown-it source-position adapter attribution
#
# MIT License
#
# Copyright (c) 2020 ExecutableBookProject
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Copyright (c) 2014 Vitaly Puzrin, Alex Kocharin.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

class PositionedState(StateInline):
    pending_start = None

    def pushPending(self):
        start = self.pending_start
        content = self.pending
        token = super().pushPending()
        start = self.pos - len(content) if start is None else start
        token.meta["source"] = (start, start + len(content))
        self.pending_start = None
        return token


class PositionedInline(ParserInline):
    def parse(self, src, md, env, tokens):
        state = PositionedState(src, md, env, tokens)
        self.tokenize(state)
        for rule in self.ruler2.getRules(""):
            rule(state)
        return state.tokens

    def tokenize(self, state):
        rules = self.ruler.getRules("")
        end = state.posMax
        while state.pos < end:
            start, before = state.pos, len(state.tokens)
            ok = False
            if not state.pending:
                state.pending_start = start
            if state.level < state.md.options["maxNesting"]:
                for rule in rules:
                    if rule(state, False):
                        ok = True
                        break
            if not ok:
                state.pending += state.src[state.pos]
                state.pos += 1
            marker_pos = start
            for token in state.tokens[before:]:
                if "source" in token.meta:
                    continue
                if token.type == "text" and token.content in ("*", "_", "~", "~~"):
                    token.meta["source"] = (marker_pos, marker_pos + len(token.content))
                    marker_pos += len(token.content)
                else:
                    token.meta["source"] = (start, state.pos)
            # A rule can flush pending text and start a fresh pending suffix.
            if state.pending and state.pending_start is None:
                state.pending_start = state.pos - len(state.pending)
        if state.pending:
            state.pushPending()


def parser():
    md = MarkdownIt("commonmark", {"html": True})
    md.inline = PositionedInline()
    md.inline.ruler2.disable("fragments_join")
    md.core.ruler.disable("text_join")
    md.enable(["table", "strikethrough"])
    return md


_MARKDOWN = parser()
_HTML_START = re.compile(r"^\s*(?:<!doctype\s+html\b|<html\b|<(?:article|section|main|body|head|script|style|nav|header|footer|span|em|strong|a)\b)", re.I)
_HTML_TAG = re.compile(r"<(/?)([a-z][a-z0-9:-]*)\b[^<>]*>", re.I)
_HTML_NAMES = corpus._BLOCK | corpus._SKIP | {"html", "body", "main", "header", "span", "a", "b",
                                             "strong", "em", "i", "code", "sup", "sub", "mark", "del", "small"}


def _contains_html(text):
    opened = set()
    for match in _HTML_TAG.finditer(text):
        name = match[2].lower()
        if name in {"br", "img"} or (match[1] and name in opened):
            return True
        if not match[1] and name in _HTML_NAMES:
            opened.add(name)
    return False


_MD_BLOCK = re.compile(r"(?m)^(?: {0,3}(?:={2,}|-{3,}|\*{3,}|_{3,})[ \t]*$| {0,3}\[[^\]\n]+\]:[ \t]+\S)")
# Like the corpus cleaner, ambiguous inline asterisks and underscores alone
# do not switch scientific or mathematical prose into Markdown mode.
_MD_EXTRA = re.compile(r"`[^`\n]+`|(?m:^ {0,3}~~~)")


def _inline_source(view, lines, part):
    a, b = part.map
    fragments = []
    for i, content in enumerate(part.content.splitlines(keepends=True), a):
        if i >= b:
            return View(part.content)
        lo, hi = lines[i], lines[i+1]
        line = content.removesuffix("\n")
        physical = view.text[lo:hi].removesuffix("\n")
        at = physical.find(line)
        if at < 0 or (line and physical.find(line, at+1) >= 0):
            fragments.append(View(line))
        else:
            fragments.append(view.slice(lo+at, lo+at+len(line)))
        if content.endswith("\n"):
            fragments.append(view.slice(hi-1, hi) if view.text[hi-1:hi] == "\n" else View("\n"))
    joined = join(fragments)
    return joined if joined.text == part.content else View(part.content)


def _inline(view, tokens, tags):
    out = []
    for token in tokens:
        kind = token.type
        if kind == "html_inline":
            tags.feed(token.content)
            tags.pieces.clear()
            if not tags.skip and re.fullmatch(r"<br\s*/?>", token.content, re.I):
                out.append(View("\n"))
            continue
        if tags.skip or kind not in {"text", "text_special", "code_inline", "softbreak", "hardbreak"}:
            continue
        src = view.slice(*token.meta.get("source", (0, 0)))
        value = "\n" if kind in {"softbreak", "hardbreak"} else token.content
        if not value:
            continue
        if kind == "code_inline":
            width = len(token.markup)
            src = src.slice(width, len(src.text)-width)
            src = src.substitute((m.start(), m.end(), src.slice(*m.span()).as_glyph(" "))
                                 for m in re.finditer("\n", src.text))
            if src.text.startswith(" ") and src.text.endswith(" ") and src.text.strip():
                src = src.slice(1, len(src.text)-1)
        if token.info == "entity":
            out.append(src.as_glyph(value))
        elif src.text == value:
            out.append(src)
        elif src.text.count(value) == 1:
            at = src.text.index(value)
            out.append(src.slice(at, at+len(value)))
        else:
            out.append(View(value))
    return join(out)


def _markdown(view):
    lines = [0, *(m.end() for m in re.finditer("\n", view.text)), len(view.text)]
    parts, table, previous_end = [], False, None
    tags = corpus._HTMLText()
    for token in _MARKDOWN.parse(view.text):
        if token.type in {"table_open", "table_close"}:
            table = token.type == "table_open"
        if table or token.type not in {"inline", "html_block"}:
            continue
        a, b = token.map
        if token.type == "html_block":
            body = view.slice(lines[a], lines[b])
            # Container prefixes (e.g. blockquotes) may be stripped by the parser.
            if body.text != token.content:
                body = _inline_source(view, lines, token)
            block = HTML.render(body, tags.skip)
        else:
            block = _inline(_inline_source(view, lines, token), token.children, tags)
        separator = View("\n\n")
        if previous_end is not None:
            gap = view.slice(previous_end, lines[a])
            if gap.text == "\n\n":
                separator = gap
        parts.extend((separator, block))
        if token.type == "html_block":
            parts.append(View("\n\n"))
        previous_end = lines[b] - int(view.text[lines[b]-1:lines[b]] == "\n")
    return join(parts)


def _finish(view):
    if "://" in view.text or "www." in view.text.lower():
        view = view.substitute((m.start(), m.end(), View("")) for m in corpus._URL.finditer(view.text))
    if "\n" in view.text:
        view = view.substitute((m.start(), m.end(), join((view.slice(m.start(), m.start()+1),
                                                          view.slice(m.end()-1, m.end()))))
                               for m in re.finditer(r"\n(?:[ \t]*\n)+", view.text) if m[0] != "\n\n")
    return view.strip()


def _publisher(raw, source_id):
    text = corpus.document_text(source_id, raw)
    if not text:
        return View("")
    if text == raw.strip():
        return View.original(raw).strip()
    origins = corpus.source_origins(raw, text, source_id)
    runs, i = [], 0
    while i < len(origins):
        origin = origins[i]
        if origin is None:
            i += 1
            continue
        s, e = origin
        j = i+1
        while j < len(origins) and origins[j] == origin:
            j += 1
        linear = j == i+1 and e == s+1
        if linear:
            while j < len(origins) and origins[j] == (e, e+1) and (
                    j+1 == len(origins) or origins[j+1] != origins[j]):
                j += 1
                e += 1
        runs.append((i, j, s, e, linear))
        i = j
    return View(text, runs)


def visible(raw, source_id):
    if source_id != "rendered_prose":
        # Use the same publisher-specific rules as the corpus. HTML can carry
        # precise character offsets through its parser, even for duplicate text.
        if source_id in corpus._HTML | corpus._REVIEW_HTML and "<" in raw and (
                corpus._HTML_WRAPPER.match(raw) or corpus._REVIEW_TAGS.search(raw) and source_id in corpus._REVIEW_HTML):
            html = _finish(HTML.render(_canonical(raw)))
            if html.text == corpus.document_text(source_id, raw):
                return html
        return _publisher(raw, source_id)
    view = _canonical(raw)
    markdown = corpus.content_hint(view.text) == "markdown"
    if "<" in view.text and (corpus._HTML_WRAPPER.match(view.text) and corpus._HTML_END.search(view.text)
                             or _HTML_START.match(view.text) or (not markdown and ("<!--" in view.text or _contains_html(view.text)))):
        return _finish(HTML.render(view))
    if corpus._STRUCTURE.search(view.text):
        view = view.substitute((a, b, View("\n\n")) for a, b, _ in corpus.structural_ranges(view.text))
    if corpus.content_hint(view.text) == "markdown" or _MD_EXTRA.search(view.text) or _MD_BLOCK.search(view.text):
        view = _markdown(view)
    return _finish(view)