oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1package notionmd
2
3import (
4 "sort"
5 "strings"
6)
7
8// Edits to a line's literal text, made in one pass (Fable M2). Each
9// neutralising rule finds every place it applies in one scan of the
10// written line, then the line is rebuilt once: rescanning or re-cutting
11// the line per change was quadratic, and worse, in literal [ and ].
12
13// change is one edit at a byte offset of a line's written text: text
14// inserted there, or, with replace, the one byte there replaced.
15type change struct {
16 at int
17 text string
18 replace bool
19}
20
21// apply makes every change to each's literal parts. An insertion at the
22// seam before a generated part is a literal of its own, as insert's is.
23func apply(each line, changes []change) line {
24 if len(changes) == 0 {
25 return each
26 }
27 sort.SliceStable(changes, func(left, right int) bool {
28 return changes[left].at < changes[right].at
29 })
30 var out line
31 offset, next := 0, 0
32 for _, piece := range each {
33 end := offset + len(piece.source())
34 if piece.kind != literal {
35 var before strings.Builder
36 for ; next < len(changes) && changes[next].at <= offset; next++ {
37 before.WriteString(changes[next].text)
38 }
39 if before.Len() > 0 {
40 out = append(out, lit(before.String()))
41 }
42 out = append(out, piece)
43 offset = end
44 continue
45 }
46 piece.text, next = editText(piece.text, offset, end, changes, next)
47 out = append(out, piece)
48 offset = end
49 }
50 if next < len(changes) {
51 var after strings.Builder
52 for ; next < len(changes); next++ {
53 after.WriteString(changes[next].text)
54 }
55 out = append(out, lit(after.String()))
56 }
57 return mergeLiterals(out)
58}
59
60// editText applies the changes that fall in one literal, which covers
61// offsets start to end of the line, and answers the next change's index.
62func editText(text string, start, end int, changes []change,
63 next int) (string, int) {
64 var out strings.Builder
65 cursor := 0
66 for ; next < len(changes); next++ {
67 edit := changes[next]
68 if edit.at > end || (edit.replace && edit.at >= end) {
69 break
70 }
71 at := edit.at - start
72 out.WriteString(text[cursor:at])
73 out.WriteString(edit.text)
74 cursor = at
75 if edit.replace {
76 cursor++
77 }
78 }
79 out.WriteString(text[cursor:])
80 return out.String(), next
81}
82