oficina / mapa Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package markup is Mapa's Markdown: the block model of spec §3.2, the
2// links in a body, and a renderer that never passes a person's markup
3// through. It is a deliberate subset, not CommonMark: paragraphs, headings,
4// list items, quotes, code fences and rules, with emphasis, inline code,
5// [[links]] and web links inside them. No raw HTML is ever rendered.
6//
7// The subset is ours for two reasons. A block here is exactly §3.2's
8// block (a paragraph, a list item, a heading or a code fence), which the
9// three-way merge, backlink context and ^id markers all need. And S10's
10// `page` payload (§7.3) is typed blocks with typed spans, which this
11// parser already produces.
12package markup
13
14import (
15 "regexp"
16 "strings"
17)
18
19// Kinds of block.
20const (
21 Paragraph = "paragraph"
22 Heading = "heading"
23 Item = "item"
24 Code = "code"
25 Quote = "quote"
26 Rule = "rule"
27)
28
29// Block is one block of a body: its kind, and its source exactly as
30// typed, so a body can be put back together from its blocks.
31type Block struct {
32 Kind string
33 // Source is the block's lines, joined with "\n", untouched.
34 Source string
35 // Level is a heading's level, or a list item's nesting depth.
36 Level int
37 // Ordered marks a numbered list item.
38 Ordered bool
39 // Marker is the block's ^id, when it has one (§3.2).
40 Marker string
41 // Start and End are the block's byte offsets in the normalised body:
42 // body[Start:End] == Source.
43 Start, End int
44 // Column is, for a block inside a column layout and for that
45 // column's own fences, the column it belongs to, 1 to 4; 0 anywhere
46 // else (columns and icons spec §1.4). It is a position, derived:
47 // the merge never compares it.
48 Column int
49}
50
51var (
52 headingLine = regexp.MustCompile(`^(#{1,6})[ \t]+\S`)
53 itemLine = regexp.MustCompile(`^([ \t]*)([-*+]|[0-9]{1,9}[.)])[ \t]+`)
54 fenceLine = regexp.MustCompile("^ {0,3}(```|~~~)")
55 ruleLine = regexp.MustCompile(`^ {0,3}(?:(?:-[ \t]*){3,}|` +
56 `(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})$`)
57 markerTail = regexp.MustCompile(`[ \t]\^([A-Za-z0-9-]{1,40})[ \t]*$`)
58)
59
60// Parse splits a body into its blocks. Blank lines separate blocks and
61// belong to none; everything else belongs to exactly one.
62func Parse(body string) []Block {
63 lines := strings.Split(normalise(body), "\n")
64 offsets := make([]int, len(lines)+1)
65 for index, line := range lines {
66 offsets[index+1] = offsets[index] + len(line) + 1
67 }
68 return parseLines(lines, offsets, 0, len(lines), layouts(lines))
69}
70
71// parseLines parses lines[from:to], every offset the body's own. found
72// is the whole column layouts, by their opener's line; a column's own
73// lines are parsed with none (no nesting).
74func parseLines(lines []string, offsets []int, from, to int,
75 found map[int]layout) []Block {
76 view := lines[:to]
77 var blocks []Block
78 for index := from; index < to; {
79 if strings.TrimSpace(view[index]) == "" {
80 index++
81 continue
82 }
83 if whole, ok := found[index]; ok {
84 blocks = append(blocks, parseLayout(lines, offsets, whole)...)
85 index = whole.close + 1
86 continue
87 }
88 block, next := parseBlock(view, index)
89 block.Marker = marker(block)
90 block.Start = offsets[index]
91 block.End = block.Start + len(block.Source)
92 blocks = append(blocks, block)
93 index = next
94 }
95 return blocks
96}
97
98// normalise is the one line-ending rule: a body is stored with "\n".
99func normalise(body string) string {
100 return strings.ReplaceAll(strings.ReplaceAll(body, "\r\n", "\n"),
101 "\r", "\n")
102}
103
104// Normalise is normalise, for callers outside the package.
105func Normalise(body string) string { return normalise(body) }
106
107func parseBlock(lines []string, start int) (Block, int) {
108 line := lines[start]
109 switch {
110 case fenceLine.MatchString(line):
111 return parseFence(lines, start)
112 case headingLine.MatchString(line):
113 level := len(headingLine.FindStringSubmatch(line)[1])
114 return Block{Kind: Heading, Source: line, Level: level}, start + 1
115 case ruleLine.MatchString(line):
116 return Block{Kind: Rule, Source: line}, start + 1
117 case itemLine.MatchString(line):
118 return parseItem(lines, start)
119 case strings.HasPrefix(strings.TrimLeft(line, " "), ">"):
120 return parseRun(lines, start, Quote, isQuoteLine)
121 }
122 return parseRun(lines, start, Paragraph, continuesParagraph)
123}
124
125func parseFence(lines []string, start int) (Block, int) {
126 fence := fenceLine.FindStringSubmatch(lines[start])[1]
127 end := start + 1
128 for end < len(lines) &&
129 !ClosesFence(lines[end], fence) {
130 end++
131 }
132 if end < len(lines) {
133 end++ // the closing fence belongs to the block
134 }
135 source := strings.Join(lines[start:end], "\n")
136 return Block{Kind: Code, Source: source}, end
137}
138
139func parseItem(lines []string, start int) (Block, int) {
140 match := itemLine.FindStringSubmatch(lines[start])
141 indent := strings.ReplaceAll(match[1], "\t", " ")
142 block := Block{Kind: Item, Level: len(indent) / 2,
143 Ordered: !strings.ContainsAny(match[2], "-*+")}
144 end := start + 1
145 for end < len(lines) && continuesParagraph(lines[end]) {
146 end++
147 }
148 block.Source = strings.Join(lines[start:end], "\n")
149 return block, end
150}
151
152// parseRun is a block made of consecutive lines that keep going.
153func parseRun(lines []string, start int, kind string,
154 keeps func(string) bool) (Block, int) {
155 end := start + 1
156 for end < len(lines) && keeps(lines[end]) {
157 end++
158 }
159 return Block{Kind: kind, Source: strings.Join(lines[start:end], "\n")},
160 end
161}
162
163func isQuoteLine(line string) bool {
164 return strings.HasPrefix(strings.TrimLeft(line, " "), ">")
165}
166
167// continuesParagraph is a non-blank line that does not start a block of
168// another kind.
169func continuesParagraph(line string) bool {
170 return strings.TrimSpace(line) != "" && !startsBlock(line)
171}
172
173func startsBlock(line string) bool {
174 return fenceLine.MatchString(line) || headingLine.MatchString(line) ||
175 ruleLine.MatchString(line) || itemLine.MatchString(line) ||
176 isQuoteLine(line)
177}
178
179// marker is a block's ^id: the last thing on its last line. A code block
180// never has one; its text is code.
181func marker(block Block) string {
182 if block.Kind == Code || block.Kind == Rule || IsFence(block.Kind) {
183 return ""
184 }
185 last := block.Source[strings.LastIndex(block.Source, "\n")+1:]
186 if match := markerTail.FindStringSubmatch(last); match != nil {
187 return match[1]
188 }
189 return ""
190}
191
192// Join puts blocks back together: a blank line between blocks, except
193// between two list items, which stay a tight list, and inside a column
194// layout's fences (seam).
195func Join(blocks []Block) string {
196 var out strings.Builder
197 for index, block := range blocks {
198 if index > 0 {
199 out.WriteString(seam(blocks[index-1], block))
200 }
201 out.WriteString(block.Source)
202 }
203 return out.String()
204}
205
206// seam is Join's bytes between two neighbours. Fences are written as
207// columns and icons spec §1.4 says: one newline after a column's opener
208// (and between an empty column's two fences), a blank line everywhere
209// else, before a column's closer included, so no reader's lazy
210// continuation can carry a line into it.
211func seam(before, after Block) string {
212 switch {
213 case before.Kind == Column:
214 return "\n"
215 case before.Kind == Item && after.Kind == Item:
216 return "\n"
217 }
218 return "\n\n"
219}
220
221// Plain is a block's words without its syntax: the list marker, heading
222// hashes, quote marks and ^id. Backlink context and search read it.
223func Plain(block Block) string {
224 text := block.Source
225 if IsFence(block.Kind) {
226 // A fence holds no words (columns and icons spec §1.4).
227 return ""
228 }
229 switch block.Kind {
230 case Code:
231 return codeText(text)
232 case Heading:
233 text = strings.TrimLeft(text, "# \t")
234 case Item:
235 text = itemLine.ReplaceAllString(text, "")
236 case Quote:
237 text = quoteText(text)
238 }
239 if block.Marker != "" {
240 text = markerTail.ReplaceAllString(text, "")
241 }
242 return text
243}
244
245func codeText(source string) string {
246 lines := strings.Split(source, "\n")
247 if len(lines) <= 1 {
248 return ""
249 }
250 if fenceLine.MatchString(lines[len(lines)-1]) {
251 lines = lines[:len(lines)-1]
252 }
253 return strings.Join(lines[1:], "\n")
254}
255
256func quoteText(source string) string {
257 lines := strings.Split(source, "\n")
258 for index, line := range lines {
259 line = strings.TrimPrefix(strings.TrimLeft(line, " "), ">")
260 lines[index] = strings.TrimPrefix(line, " ")
261 }
262 return strings.Join(lines, "\n")
263}
264
265// Replace swaps blocks' sources in body, leaving every other byte as it
266// was: the blank lines between blocks, and the blocks not named. change
267// maps a block's index to its new source; "" removes the block's text.
268func Replace(body string, blocks []Block, change map[int]string) string {
269 body = normalise(body)
270 var out strings.Builder
271 cursor := 0
272 for index, block := range blocks {
273 replacement, ok := change[index]
274 if !ok {
275 continue
276 }
277 out.WriteString(body[cursor:block.Start])
278 out.WriteString(replacement)
279 cursor = block.End
280 }
281 out.WriteString(body[cursor:])
282 return out.String()
283}
284