| 1 | // Package markdown renders Markdown as HTML that is safe to show on the |
| 2 | // edge's origin. Render is a pure function from bytes to HTML: it knows |
| 3 | // nothing of the server, of git or of URLs beyond the resolver it is |
| 4 | // given. |
| 5 | // |
| 6 | // # Safety |
| 7 | // |
| 8 | // The renderer writes only its own fixed set of elements and attributes: |
| 9 | // h1 to h6 with id, p, br, em, strong, del, code, pre, blockquote, ul, ol |
| 10 | // with start, li, hr, table, thead, tbody, tr, th and td with an |
| 11 | // alignment class, and a with href, title and class. It escapes every |
| 12 | // byte of text and every attribute value it takes from the input. Raw |
| 13 | // HTML in the input, inline or block, is shown as escaped text. So no |
| 14 | // input byte reaches the output unescaped, and no input can add an |
| 15 | // element, an attribute, a script, a style or an event handler. |
| 16 | // |
| 17 | // A link's href is one of three kinds. An http or https destination that |
| 18 | // names a host, or a mailto destination, is written as given, |
| 19 | // percent-encoded where a URL needs it. A relative or fragment-only |
| 20 | // destination is what the resolver makes of it. Any other destination, |
| 21 | // such as javascript:, data:, http:x, https:// or one that holds a |
| 22 | // backslash anywhere, written as one or decoded from an escape or an |
| 23 | // entity, or one the resolver refuses, renders as the link's text with no |
| 24 | // a element. An image renders as a link to its destination, with its alt |
| 25 | // text, and never as an img element. |
| 26 | // |
| 27 | // # What it reads |
| 28 | // |
| 29 | // Render follows CommonMark's rules for the constructs it supports: ATX |
| 30 | // and setext headings, paragraphs, hard line breaks, emphasis, strong |
| 31 | // emphasis, inline code, fenced and indented code blocks, block quotes, |
| 32 | // ordered and unordered lists, thematic breaks, inline and reference |
| 33 | // links, autolinks, images, backslash escapes and entity references. It |
| 34 | // supports GitHub's strikethrough, pipe tables, task list items and bare |
| 35 | // http(s) autolinks too. Anything else, such as footnotes, math or HTML, |
| 36 | // renders as text. |
| 37 | // |
| 38 | // # Bounds |
| 39 | // |
| 40 | // The input is at most MaxInput bytes. Rendering takes time near-linear |
| 41 | // in the input, whatever it holds: no regular expression is used, and |
| 42 | // every scan that fails is remembered or bounded. Block quotes and list |
| 43 | // items nest at most MaxDepth deep, beyond which their markers render as |
| 44 | // text. Emphasis, strong emphasis, strikethrough, links, images and |
| 45 | // autolinks nest at most MaxDepth deep within a block, beyond which |
| 46 | // emphasis's delimiters render as text, and a link, an image or an |
| 47 | // autolink as its text alone. A table has at most MaxTableColumns |
| 48 | // columns, and a document's tables at most MaxTableCells cells between |
| 49 | // them; a table's rows past that render as a paragraph. |
| 50 | // |
| 51 | // The structures Render builds are bounded too, so that one render of a |
| 52 | // MaxInput document allocates less than 128 MiB in all, when |
| 53 | // Options.MaxOutput is set, as the server always sets it. A document holds |
| 54 | // at most MaxBlocks blocks, quotes, lists and items among them. A line |
| 55 | // that would add a block past that, less one kept for the rest of the |
| 56 | // input, adds none, and it and the input after it render as one block of |
| 57 | // preformatted text. Its inline content takes at most MaxInlineNodes |
| 58 | // nodes between all its blocks: the block that passes MaxInlineNodes, and |
| 59 | // every block after it, renders its text alone, escaped. Within a block |
| 60 | // at most 4,096 [ or ![ wait for their ], and a [ past that is text. |
| 61 | // |
| 62 | // A link label holds at most 999 characters. A render looks up at most |
| 63 | // 4 MiB of labels as references, so that the copies made to match them |
| 64 | // are bounded too, and a reference past that renders as text. A document |
| 65 | // with no reference definitions looks up none. |
| 66 | // |
| 67 | // The output is at most Options.MaxOutput bytes. Render stops all work |
| 68 | // once the output would pass it, and returns the document up to the last |
| 69 | // block that fit, with the blocks that hold it closed. A link reference |
| 70 | // makes its destination's href once, however often it is used, so each |
| 71 | // use costs only the output it writes. Render stops too once its context |
| 72 | // is done. |
| 73 | package markdown |
| 74 | |
| 75 | import ( |
| 76 | "bytes" |
| 77 | "context" |
| 78 | "errors" |
| 79 | "html" |
| 80 | "html/template" |
| 81 | "net/netip" |
| 82 | "strconv" |
| 83 | "strings" |
| 84 | "unicode" |
| 85 | "unicode/utf8" |
| 86 | ) |
| 87 | |
| 88 | const ( |
| 89 | // MaxInput is the largest input Render reads. |
| 90 | MaxInput = 1 << 20 |
| 91 | // MaxDepth is how deep block quotes and list items nest, and how |
| 92 | // deep emphasis, strikethrough and links nest within a block. |
| 93 | MaxDepth = 32 |
| 94 | // MaxTableColumns is the most columns a table has. A header with |
| 95 | // more is no table. |
| 96 | MaxTableColumns = 64 |
| 97 | // MaxTableCells is the most cells a document's tables hold between |
| 98 | // them, each row counted at its table's columns. |
| 99 | MaxTableCells = 100_000 |
| 100 | // maxLabel is the most characters a link label holds, as CommonMark |
| 101 | // has it. A longer one is no label. |
| 102 | maxLabel = 999 |
| 103 | // maxLabelBytes is the most bytes of labels a render looks up as |
| 104 | // references. Past it, a reference renders as text. |
| 105 | maxLabelBytes = 4 << 20 |
| 106 | // maxParens is how deeply parentheses nest in a link destination. |
| 107 | maxParens = 32 |
| 108 | // MaxBlocks is the most blocks a document holds: headings, |
| 109 | // paragraphs, quotes, lists, items, code blocks, rules and tables. |
| 110 | MaxBlocks = 1 << 16 |
| 111 | // MaxInlineNodes is the most nodes the inline content of a |
| 112 | // document's blocks takes between them: one for each run of text, |
| 113 | // code span, line break, delimiter run, bracket and autolink, and |
| 114 | // one for each emphasis or link they make. |
| 115 | MaxInlineNodes = 1 << 18 |
| 116 | // maxBrackets is the most [ and ![ that wait for their ] at once |
| 117 | // within a block. |
| 118 | maxBrackets = 4096 |
| 119 | ) |
| 120 | |
| 121 | // ErrTooLong is Render's error for an input longer than MaxInput. |
| 122 | var ErrTooLong = errors.New("markdown: the input is longer than MaxInput") |
| 123 | |
| 124 | // Options are what Render is given besides its input. |
| 125 | type Options struct { |
| 126 | // Resolve gives the href of a relative or fragment-only destination, |
| 127 | // or ok false to refuse it. A nil Resolve refuses every one. |
| 128 | Resolve func(dest string) (href string, ok bool) |
| 129 | // MaxOutput bounds the HTML Render writes. Zero means no bound. |
| 130 | MaxOutput int |
| 131 | } |
| 132 | |
| 133 | // Heading is one heading of a document. |
| 134 | type Heading struct { |
| 135 | Level int |
| 136 | Text string |
| 137 | // ID is the heading's id, empty for a heading whose text gives none. |
| 138 | ID string |
| 139 | } |
| 140 | |
| 141 | // Doc is a rendered document. |
| 142 | type Doc struct { |
| 143 | HTML template.HTML |
| 144 | Headings []Heading |
| 145 | // Truncated is set when the document is larger than MaxOutput, and |
| 146 | // HTML and Headings hold its start: the blocks that fit, whole. |
| 147 | Truncated bool |
| 148 | } |
| 149 | |
| 150 | // Render renders src. Invalid UTF-8 and NUL bytes read as U+FFFD. It |
| 151 | // fails with ctx's error once ctx is done. |
| 152 | func Render(ctx context.Context, src []byte, opt Options) (Doc, error) { |
| 153 | d, _, err := renderDoc(ctx, src, opt) |
| 154 | return d, err |
| 155 | } |
| 156 | |
| 157 | // usage is how much of each bounded structure a render took: blocks, |
| 158 | // inline nodes, the most brackets open at once in a block, and the bytes |
| 159 | // of labels looked up. |
| 160 | type usage struct{ blocks, nodes, brackets, labels int } |
| 161 | |
| 162 | func renderDoc(ctx context.Context, src []byte, opt Options) (Doc, usage, error) { |
| 163 | if len(src) > MaxInput { |
| 164 | return Doc{}, usage{}, ErrTooLong |
| 165 | } |
| 166 | text := strings.ToValidUTF8(string(src), "�") |
| 167 | text = strings.ReplaceAll(text, "\x00", "�") |
| 168 | p := &parser{ctx: ctx, refs: map[string]*linkRef{}} |
| 169 | root := p.parse(text) |
| 170 | if err := ctx.Err(); err != nil { |
| 171 | return Doc{}, usage{}, err |
| 172 | } |
| 173 | r := &renderer{ctx: ctx, opt: opt, refs: p.refs, slugs: map[string]int{}} |
| 174 | r.block(root, false) |
| 175 | if r.err != nil { |
| 176 | return Doc{}, usage{}, r.err |
| 177 | } |
| 178 | u := usage{blocks: p.blocks, nodes: r.nodes, brackets: r.brackets, labels: r.labels} |
| 179 | return Doc{HTML: template.HTML(r.out.String()), Headings: r.headings, Truncated: r.truncated}, u, nil |
| 180 | } |
| 181 | |
| 182 | // Slug is GitHub's id for a heading's text: the text in lower case, less |
| 183 | // every character that is not a letter, a digit, a space, a hyphen or an |
| 184 | // underscore, with each space made a hyphen. A document numbers a slug it |
| 185 | // has given before. |
| 186 | func Slug(text string) string { |
| 187 | var b strings.Builder |
| 188 | for _, r := range strings.ToLower(text) { |
| 189 | switch { |
| 190 | case r == ' ': |
| 191 | b.WriteByte('-') |
| 192 | case r == '-' || r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r): |
| 193 | b.WriteRune(r) |
| 194 | } |
| 195 | } |
| 196 | return b.String() |
| 197 | } |
| 198 | |
| 199 | // Block structure. |
| 200 | |
| 201 | type kind int |
| 202 | |
| 203 | const ( |
| 204 | document kind = iota |
| 205 | quote |
| 206 | list |
| 207 | item |
| 208 | paragraph |
| 209 | heading |
| 210 | fenced |
| 211 | indented |
| 212 | rule |
| 213 | table |
| 214 | ) |
| 215 | |
| 216 | type block struct { |
| 217 | kind kind |
| 218 | parent *block |
| 219 | children []*block |
| 220 | open bool |
| 221 | lines []string |
| 222 | // lastBlank is set when the block's last line was blank. |
| 223 | lastBlank, checked bool |
| 224 | |
| 225 | level int // a heading's level |
| 226 | |
| 227 | // A list's or item's marker: its character, an ordered list's start, |
| 228 | // and an item's content column. |
| 229 | ordered bool |
| 230 | marker byte |
| 231 | start int |
| 232 | indent int |
| 233 | tight bool |
| 234 | // emptyStart is set on an item whose first line held its marker alone. |
| 235 | emptyStart bool |
| 236 | startLine int |
| 237 | |
| 238 | // A fenced block's fence and info word, and the indent it strips. |
| 239 | fence string |
| 240 | info string |
| 241 | fenceCols int |
| 242 | |
| 243 | // A table's alignment by column, and its rows of cells. |
| 244 | align []byte |
| 245 | rows [][]string |
| 246 | } |
| 247 | |
| 248 | // linkRef is a link reference definition: its destination and title, |
| 249 | // and the start tag of a link to it once a use has made it, or ok false |
| 250 | // once one has found it renders as text. |
| 251 | type linkRef struct { |
| 252 | dest, title string |
| 253 | tag string |
| 254 | made, ok bool |
| 255 | } |
| 256 | |
| 257 | type parser struct { |
| 258 | ctx context.Context |
| 259 | refs map[string]*linkRef |
| 260 | root *block |
| 261 | tip *block |
| 262 | lineNo int |
| 263 | // The line being read, the byte the parser is at, and whether the |
| 264 | // rest of the line is blank. |
| 265 | line string |
| 266 | pos int |
| 267 | blank bool |
| 268 | indent int |
| 269 | next int // the first non-space byte at or after pos |
| 270 | // cells is how many cells the document's tables hold so far, and |
| 271 | // blocks how many blocks it holds. full is set once a line would add |
| 272 | // a block past MaxBlocks less one, the one kept for the input from |
| 273 | // that line on, and added the blocks the line has added so far. |
| 274 | cells, blocks int |
| 275 | full bool |
| 276 | added []*block |
| 277 | } |
| 278 | |
| 279 | func (p *parser) parse(text string) *block { |
| 280 | p.root = &block{kind: document, open: true} |
| 281 | p.tip = p.root |
| 282 | rest := "" |
| 283 | for len(text) > 0 { |
| 284 | at := text |
| 285 | end, skip := len(text), 0 |
| 286 | if i := strings.IndexAny(text, "\r\n"); i >= 0 { |
| 287 | end, skip = i, 1 |
| 288 | if text[i] == '\r' && i+1 < len(text) && text[i+1] == '\n' { |
| 289 | skip = 2 |
| 290 | } |
| 291 | } |
| 292 | line := text[:end] |
| 293 | text = text[end+skip:] |
| 294 | p.lineNo++ |
| 295 | if p.lineNo%1024 == 0 && p.ctx.Err() != nil { |
| 296 | return p.root |
| 297 | } |
| 298 | p.added = p.added[:0] |
| 299 | p.addLine(expandTabs(line)) |
| 300 | if p.full { |
| 301 | // The line takes back the blocks it added, and it and the |
| 302 | // input after it are preformatted text. |
| 303 | for i := len(p.added) - 1; i >= 0; i-- { |
| 304 | b := p.added[i] |
| 305 | if ch := b.parent.children; len(ch) > 0 && ch[len(ch)-1] == b { |
| 306 | b.parent.children = ch[:len(ch)-1] |
| 307 | p.blocks-- |
| 308 | } |
| 309 | } |
| 310 | rest = strings.TrimRight(at, "\r\n") |
| 311 | break |
| 312 | } |
| 313 | } |
| 314 | for p.tip != nil { |
| 315 | p.close(p.tip) |
| 316 | } |
| 317 | if rest != "" { |
| 318 | p.root.children = append(p.root.children, &block{kind: indented, parent: p.root, lines: []string{rest}}) |
| 319 | p.blocks++ |
| 320 | } |
| 321 | return p.root |
| 322 | } |
| 323 | |
| 324 | // expandTabs is line with each tab made the spaces to the next tab stop |
| 325 | // of four columns. |
| 326 | func expandTabs(line string) string { |
| 327 | if strings.IndexByte(line, '\t') < 0 { |
| 328 | return line |
| 329 | } |
| 330 | var b strings.Builder |
| 331 | col := 0 |
| 332 | for _, r := range line { |
| 333 | if r == '\t' { |
| 334 | n := 4 - col%4 |
| 335 | b.WriteString(" "[:n]) |
| 336 | col += n |
| 337 | continue |
| 338 | } |
| 339 | b.WriteRune(r) |
| 340 | col++ |
| 341 | } |
| 342 | return b.String() |
| 343 | } |
| 344 | |
| 345 | func (p *parser) findNext() { |
| 346 | i := p.pos |
| 347 | for i < len(p.line) && p.line[i] == ' ' { |
| 348 | i++ |
| 349 | } |
| 350 | p.next, p.indent, p.blank = i, i-p.pos, i == len(p.line) |
| 351 | } |
| 352 | |
| 353 | func (p *parser) advance(n int) { p.pos += n; p.findNext() } |
| 354 | |
| 355 | // consume ends the line: a leaf took the rest of it. |
| 356 | func (p *parser) consume() { p.pos = len(p.line); p.findNext() } |
| 357 | |
| 358 | // depth is how many quotes and items hold b. |
| 359 | func depth(b *block) int { |
| 360 | n := 0 |
| 361 | for ; b != nil; b = b.parent { |
| 362 | if b.kind == quote || b.kind == item { |
| 363 | n++ |
| 364 | } |
| 365 | } |
| 366 | return n |
| 367 | } |
| 368 | |
| 369 | func (p *parser) addLine(line string) { |
| 370 | p.line, p.pos = line, 0 |
| 371 | p.findNext() |
| 372 | // Match the open containers. |
| 373 | c := p.root |
| 374 | allMatched := true |
| 375 | for { |
| 376 | last := lastOpen(c) |
| 377 | if last == nil { |
| 378 | break |
| 379 | } |
| 380 | ok, done := p.continues(last) |
| 381 | if done { |
| 382 | return // a closing fence: the line is consumed |
| 383 | } |
| 384 | if !ok { |
| 385 | allMatched = false |
| 386 | break |
| 387 | } |
| 388 | c = last |
| 389 | } |
| 390 | unmatchedFrom := c // the deepest container matched |
| 391 | |
| 392 | // Open new blocks, unless c takes lines as they are. Every leaf a |
| 393 | // line opens consumes the line. |
| 394 | startedNew := false |
| 395 | for c.kind != fenced && c.kind != indented && !p.blank { |
| 396 | if p.indent >= 4 { |
| 397 | if p.tip.kind == paragraph || p.tip.kind == table { |
| 398 | break // indented code interrupts no paragraph |
| 399 | } |
| 400 | p.advance(4) |
| 401 | p.closeUnmatched(unmatchedFrom, &allMatched) |
| 402 | c = p.add(c, &block{kind: indented}) |
| 403 | if p.full { |
| 404 | return |
| 405 | } |
| 406 | startedNew = true |
| 407 | break |
| 408 | } |
| 409 | nb, ok := p.start(c, unmatchedFrom, &allMatched) |
| 410 | if p.full { |
| 411 | return |
| 412 | } |
| 413 | if !ok { |
| 414 | break |
| 415 | } |
| 416 | startedNew, c = true, nb |
| 417 | if c.kind != quote && c.kind != item { |
| 418 | for b := c; b != nil; b = b.parent { |
| 419 | b.lastBlank = false |
| 420 | } |
| 421 | return |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | // The rest of the line is text. |
| 426 | if !startedNew && !allMatched && p.tip.kind == paragraph && !p.blank { |
| 427 | p.tip.lines = appendLine(p.tip.lines, p.line[p.next:]) // a lazy continuation |
| 428 | return |
| 429 | } |
| 430 | p.closeUnmatched(unmatchedFrom, &allMatched) |
| 431 | if p.blank && len(c.children) > 0 { |
| 432 | c.children[len(c.children)-1].lastBlank = true |
| 433 | } |
| 434 | lb := p.blank && !(c.kind == quote || c.kind == fenced || |
| 435 | c.kind == item && len(c.children) == 0 && c.startLine == p.lineNo) |
| 436 | for b := c; b != nil; b = b.parent { |
| 437 | b.lastBlank = lb |
| 438 | } |
| 439 | switch c.kind { |
| 440 | case fenced: |
| 441 | n := 0 |
| 442 | for n < c.fenceCols && p.pos+n < len(p.line) && p.line[p.pos+n] == ' ' { |
| 443 | n++ |
| 444 | } |
| 445 | c.lines = appendLine(c.lines, p.line[p.pos+n:]) |
| 446 | case indented: |
| 447 | if p.blank { |
| 448 | if p.pos+4 <= len(p.line) { |
| 449 | c.lines = appendLine(c.lines, p.line[p.pos+4:]) |
| 450 | } else { |
| 451 | c.lines = appendLine(c.lines, "") |
| 452 | } |
| 453 | } else { |
| 454 | c.lines = appendLine(c.lines, p.line[p.pos:]) |
| 455 | } |
| 456 | case paragraph: |
| 457 | c.lines = appendLine(c.lines, p.line[p.next:]) |
| 458 | case table: |
| 459 | if p.cells+len(c.align) > MaxTableCells { |
| 460 | // The document's tables are full: the rest of this one is a |
| 461 | // paragraph. |
| 462 | p.close(c) |
| 463 | np := p.add(c.parent, &block{kind: paragraph}) |
| 464 | np.lines = append(np.lines, p.line[p.next:]) |
| 465 | break |
| 466 | } |
| 467 | p.cells += len(c.align) |
| 468 | c.rows = append(c.rows, splitRow(p.line[p.next:], len(c.align))) |
| 469 | default: |
| 470 | if !p.blank { |
| 471 | np := p.add(c, &block{kind: paragraph}) |
| 472 | np.lines = append(np.lines, p.line[p.next:]) |
| 473 | } |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | // appendLine appends l to a block's lines, doubling their capacity as |
| 478 | // they grow, so a block of n lines allocates room for at most 4n. |
| 479 | func appendLine(lines []string, l string) []string { |
| 480 | if len(lines) == cap(lines) { |
| 481 | lines = append(make([]string, 0, max(4, 2*cap(lines))), lines...) |
| 482 | } |
| 483 | return append(lines, l) |
| 484 | } |
| 485 | |
| 486 | // lastOpen is c's last child when it is open. |
| 487 | func lastOpen(c *block) *block { |
| 488 | if n := len(c.children); n > 0 && c.children[n-1].open { |
| 489 | return c.children[n-1] |
| 490 | } |
| 491 | return nil |
| 492 | } |
| 493 | |
| 494 | // continues matches the start of the line to b, an open block, and |
| 495 | // consumes what b's continuation takes. done is set when the line closed |
| 496 | // b and holds nothing else. |
| 497 | func (p *parser) continues(b *block) (ok, done bool) { |
| 498 | switch b.kind { |
| 499 | case quote: |
| 500 | if !p.blank && p.indent < 4 && p.line[p.next] == '>' { |
| 501 | p.advance(p.next - p.pos + 1) |
| 502 | if p.pos < len(p.line) && p.line[p.pos] == ' ' { |
| 503 | p.advance(1) |
| 504 | } |
| 505 | return true, false |
| 506 | } |
| 507 | return false, false |
| 508 | case item: |
| 509 | if p.blank { |
| 510 | if len(b.children) == 0 { |
| 511 | return false, false |
| 512 | } |
| 513 | p.advance(p.next - p.pos) |
| 514 | return true, false |
| 515 | } |
| 516 | if p.indent >= b.indent { |
| 517 | p.advance(b.indent) |
| 518 | return true, false |
| 519 | } |
| 520 | return false, false |
| 521 | case list: |
| 522 | return true, false |
| 523 | case fenced: |
| 524 | if p.indent < 4 && !p.blank { |
| 525 | rest := p.line[p.next:] |
| 526 | n := run(rest, b.fence[0]) |
| 527 | if n >= len(b.fence) && strings.TrimRight(rest[n:], " ") == "" { |
| 528 | p.close(b) |
| 529 | return false, true |
| 530 | } |
| 531 | } |
| 532 | return true, false |
| 533 | case indented: |
| 534 | if p.indent >= 4 { |
| 535 | p.advance(4) |
| 536 | return true, false |
| 537 | } |
| 538 | if p.blank { |
| 539 | return true, false |
| 540 | } |
| 541 | return false, false |
| 542 | case paragraph, table: |
| 543 | return !p.blank, false |
| 544 | } |
| 545 | return false, false |
| 546 | } |
| 547 | |
| 548 | // closeUnmatched closes the open blocks below from, once a line has |
| 549 | // opened something new or ended the lazy continuation. |
| 550 | func (p *parser) closeUnmatched(from *block, allMatched *bool) { |
| 551 | if *allMatched { |
| 552 | return |
| 553 | } |
| 554 | for p.tip != from { |
| 555 | p.close(p.tip) |
| 556 | } |
| 557 | *allMatched = true |
| 558 | } |
| 559 | |
| 560 | // room reports whether the document has room for another block, with |
| 561 | // one kept for the input past MaxBlocks. When it has none, it sets full. |
| 562 | func (p *parser) room() bool { |
| 563 | if p.blocks >= MaxBlocks-1 { |
| 564 | p.full = true |
| 565 | } |
| 566 | return !p.full |
| 567 | } |
| 568 | |
| 569 | // add adds b as the last child of c, closing what c cannot hold. When the |
| 570 | // document has no room, it adds nothing and gives b, in no tree. |
| 571 | func (p *parser) add(c *block, b *block) *block { |
| 572 | if !p.room() { |
| 573 | return b |
| 574 | } |
| 575 | for !canHold(c.kind, b.kind) { |
| 576 | p.close(c) |
| 577 | c = c.parent |
| 578 | } |
| 579 | b.parent, b.open, b.startLine = c, true, p.lineNo |
| 580 | c.children = append(c.children, b) |
| 581 | p.blocks++ |
| 582 | p.added = append(p.added, b) |
| 583 | p.tip = b |
| 584 | return b |
| 585 | } |
| 586 | |
| 587 | func canHold(parent, child kind) bool { |
| 588 | switch parent { |
| 589 | case document, quote, item: |
| 590 | return child != item |
| 591 | case list: |
| 592 | return child == item |
| 593 | } |
| 594 | return false |
| 595 | } |
| 596 | |
| 597 | func (p *parser) close(b *block) { |
| 598 | if !b.open { |
| 599 | return |
| 600 | } |
| 601 | // Close the blocks b holds first. |
| 602 | for p.tip != b && p.tip != nil { |
| 603 | p.close(p.tip) |
| 604 | } |
| 605 | b.open = false |
| 606 | p.tip = b.parent |
| 607 | switch b.kind { |
| 608 | case paragraph: |
| 609 | p.definitions(b) |
| 610 | case indented: |
| 611 | for len(b.lines) > 0 && strings.TrimLeft(b.lines[len(b.lines)-1], " ") == "" { |
| 612 | b.lines = b.lines[:len(b.lines)-1] |
| 613 | } |
| 614 | case list: |
| 615 | b.tight = true |
| 616 | for i, it := range b.children { |
| 617 | last := i == len(b.children)-1 |
| 618 | if endsBlank(it) && !last { |
| 619 | b.tight = false |
| 620 | break |
| 621 | } |
| 622 | for j, sub := range it.children { |
| 623 | if endsBlank(sub) && (!last || j < len(it.children)-1) { |
| 624 | b.tight = false |
| 625 | break |
| 626 | } |
| 627 | } |
| 628 | if !b.tight { |
| 629 | break |
| 630 | } |
| 631 | } |
| 632 | } |
| 633 | if b.kind == paragraph && len(b.lines) == 0 && b.parent != nil { |
| 634 | ch := b.parent.children |
| 635 | if ch[len(ch)-1] == b { |
| 636 | b.parent.children = ch[:len(ch)-1] |
| 637 | } |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | func endsBlank(b *block) bool { |
| 642 | for b != nil { |
| 643 | if b.lastBlank { |
| 644 | return true |
| 645 | } |
| 646 | if !b.checked && (b.kind == list || b.kind == item) && len(b.children) > 0 { |
| 647 | b.checked = true |
| 648 | b = b.children[len(b.children)-1] |
| 649 | continue |
| 650 | } |
| 651 | b.checked = true |
| 652 | break |
| 653 | } |
| 654 | return false |
| 655 | } |
| 656 | |
| 657 | // start tries to open a block at the parser's position, in container c. |
| 658 | func (p *parser) start(c, unmatchedFrom *block, allMatched *bool) (*block, bool) { |
| 659 | if p.blank || p.indent >= 4 { |
| 660 | return nil, false |
| 661 | } |
| 662 | rest := p.line[p.next:] |
| 663 | ch := rest[0] |
| 664 | nested := depth(c) < MaxDepth |
| 665 | switch { |
| 666 | case ch == '>' && nested: |
| 667 | p.advance(p.next - p.pos + 1) |
| 668 | if p.pos < len(p.line) && p.line[p.pos] == ' ' { |
| 669 | p.advance(1) |
| 670 | } |
| 671 | p.closeUnmatched(unmatchedFrom, allMatched) |
| 672 | return p.add(c, &block{kind: quote}), true |
| 673 | case ch == '#': |
| 674 | if level, text, ok := atx(rest); ok { |
| 675 | p.closeUnmatched(unmatchedFrom, allMatched) |
| 676 | b := p.add(c, &block{kind: heading, level: level}) |
| 677 | b.lines = []string{text} |
| 678 | p.consume() |
| 679 | p.close(b) |
| 680 | return b, true |
| 681 | } |
| 682 | case ch == '`' || ch == '~': |
| 683 | n := run(rest, ch) |
| 684 | info := rest[n:] |
| 685 | if n >= 3 && !(ch == '`' && strings.IndexByte(info, '`') >= 0) { |
| 686 | p.closeUnmatched(unmatchedFrom, allMatched) |
| 687 | b := p.add(c, &block{kind: fenced, fence: rest[:n], fenceCols: p.indent}) |
| 688 | if f := strings.Fields(info); len(f) > 0 { |
| 689 | b.info = unescapeText(f[0]) |
| 690 | } |
| 691 | p.consume() |
| 692 | return b, true |
| 693 | } |
| 694 | } |
| 695 | // A paragraph's last line may turn out to be a setext heading or a |
| 696 | // table's header. A table has at most MaxTableColumns columns, and |
| 697 | // starts only while the document's tables have room for its header. |
| 698 | if c.kind == paragraph { |
| 699 | if align, ok := delimiterRow(rest); ok && len(c.lines) > 0 && |
| 700 | len(align) <= MaxTableColumns && p.cells+len(align) <= MaxTableCells { |
| 701 | header := c.lines[len(c.lines)-1] |
| 702 | if cells := splitRow(header, -1); len(cells) == len(align) { |
| 703 | if !p.room() { |
| 704 | return nil, false // before the header leaves the paragraph |
| 705 | } |
| 706 | p.closeUnmatched(unmatchedFrom, allMatched) |
| 707 | c.lines = c.lines[:len(c.lines)-1] |
| 708 | parent := c.parent |
| 709 | p.close(c) |
| 710 | t := p.add(parent, &block{kind: table, align: align}) |
| 711 | t.rows = [][]string{cells} |
| 712 | p.cells += len(align) |
| 713 | p.consume() |
| 714 | return t, true |
| 715 | } |
| 716 | } |
| 717 | if ch == '=' || ch == '-' { |
| 718 | n := run(rest, ch) |
| 719 | if strings.TrimRight(rest[n:], " ") == "" { |
| 720 | p.closeUnmatched(unmatchedFrom, allMatched) |
| 721 | level := 1 |
| 722 | if ch == '-' { |
| 723 | level = 2 |
| 724 | } |
| 725 | p.definitions(c) |
| 726 | if len(c.lines) > 0 { |
| 727 | c.kind, c.level = heading, level |
| 728 | c.lines = []string{strings.Join(c.lines, "\n")} |
| 729 | p.close(c) |
| 730 | p.consume() |
| 731 | return c, true |
| 732 | } |
| 733 | } |
| 734 | } |
| 735 | } |
| 736 | if thematic(rest) { |
| 737 | p.closeUnmatched(unmatchedFrom, allMatched) |
| 738 | b := p.add(c, &block{kind: rule}) |
| 739 | p.consume() |
| 740 | p.close(b) |
| 741 | return b, true |
| 742 | } |
| 743 | if !nested { |
| 744 | return nil, false |
| 745 | } |
| 746 | return p.listItem(c, unmatchedFrom, allMatched) |
| 747 | } |
| 748 | |
| 749 | func (p *parser) listItem(c, unmatchedFrom *block, allMatched *bool) (*block, bool) { |
| 750 | rest := p.line[p.next:] |
| 751 | var marker byte |
| 752 | ordered, start, n := false, 0, 0 |
| 753 | switch rest[0] { |
| 754 | case '-', '+', '*': |
| 755 | marker, n = rest[0], 1 |
| 756 | default: |
| 757 | for n < len(rest) && n < 9 && rest[n] >= '0' && rest[n] <= '9' { |
| 758 | n++ |
| 759 | } |
| 760 | if n == 0 || n >= len(rest) || rest[n] != '.' && rest[n] != ')' { |
| 761 | return nil, false |
| 762 | } |
| 763 | start, _ = strconv.Atoi(rest[:n]) |
| 764 | ordered, marker = true, rest[n] |
| 765 | n++ |
| 766 | } |
| 767 | if n < len(rest) && rest[n] != ' ' { |
| 768 | return nil, false |
| 769 | } |
| 770 | after := rest[n:] |
| 771 | empty := strings.TrimLeft(after, " ") == "" |
| 772 | if c.kind == paragraph && (empty || ordered && start != 1) { |
| 773 | return nil, false // neither interrupts a paragraph |
| 774 | } |
| 775 | spaces := len(after) - len(strings.TrimLeft(after, " ")) |
| 776 | width := n + spaces |
| 777 | if empty || spaces >= 5 { |
| 778 | width = n + 1 |
| 779 | } |
| 780 | indent := p.indent + width |
| 781 | p.closeUnmatched(unmatchedFrom, allMatched) |
| 782 | p.advance(p.next - p.pos + min(width, len(rest))) |
| 783 | if c.kind != list || c.ordered != ordered || c.marker != marker { |
| 784 | c = p.add(c, &block{kind: list, ordered: ordered, marker: marker, start: start}) |
| 785 | } |
| 786 | it := p.add(c, &block{kind: item, indent: indent, emptyStart: empty}) |
| 787 | return it, true |
| 788 | } |
| 789 | |
| 790 | // run is how many bytes of c s starts with. |
| 791 | func run(s string, c byte) int { |
| 792 | n := 0 |
| 793 | for n < len(s) && s[n] == c { |
| 794 | n++ |
| 795 | } |
| 796 | return n |
| 797 | } |
| 798 | |
| 799 | // atx reads an ATX heading: one to six #, then a space or the line's end. |
| 800 | func atx(s string) (level int, text string, ok bool) { |
| 801 | level = run(s, '#') |
| 802 | if level > 6 || level < len(s) && s[level] != ' ' { |
| 803 | return 0, "", false |
| 804 | } |
| 805 | text = strings.Trim(s[level:], " ") |
| 806 | // A closing sequence of # goes, when a space precedes it. |
| 807 | if t := strings.TrimRight(text, "#"); len(t) < len(text) { |
| 808 | if t == "" { |
| 809 | text = "" |
| 810 | } else if strings.HasSuffix(t, " ") { |
| 811 | text = strings.TrimRight(t, " ") |
| 812 | } |
| 813 | } |
| 814 | return level, text, true |
| 815 | } |
| 816 | |
| 817 | // thematic reads a thematic break: three or more of *, - or _, alone with |
| 818 | // spaces. |
| 819 | func thematic(s string) bool { |
| 820 | c, n := s[0], 0 |
| 821 | if c != '*' && c != '-' && c != '_' { |
| 822 | return false |
| 823 | } |
| 824 | for i := 0; i < len(s); i++ { |
| 825 | switch s[i] { |
| 826 | case c: |
| 827 | n++ |
| 828 | case ' ': |
| 829 | default: |
| 830 | return false |
| 831 | } |
| 832 | } |
| 833 | return n >= 3 |
| 834 | } |
| 835 | |
| 836 | // delimiterRow reads a table's delimiter row: cells of hyphens, each with |
| 837 | // an optional colon either side, between pipes. It holds a pipe, so a |
| 838 | // line of hyphens alone stays a setext underline or a break. A row of |
| 839 | // more than MaxTableColumns cells is none, and is not split. |
| 840 | func delimiterRow(s string) (align []byte, ok bool) { |
| 841 | if n := strings.Count(s, "|"); n == 0 || n > MaxTableColumns+1 { |
| 842 | return nil, false |
| 843 | } |
| 844 | for _, cell := range splitRow(s, -1) { |
| 845 | cell = strings.TrimSpace(cell) |
| 846 | left, right := strings.HasPrefix(cell, ":"), strings.HasSuffix(cell, ":") |
| 847 | dashes := strings.TrimSuffix(strings.TrimPrefix(cell, ":"), ":") |
| 848 | if dashes == "" || strings.Trim(dashes, "-") != "" { |
| 849 | return nil, false |
| 850 | } |
| 851 | a := byte(0) |
| 852 | switch { |
| 853 | case left && right: |
| 854 | a = 'c' |
| 855 | case left: |
| 856 | a = 'l' |
| 857 | case right: |
| 858 | a = 'r' |
| 859 | } |
| 860 | align = append(align, a) |
| 861 | } |
| 862 | return align, len(align) > 0 |
| 863 | } |
| 864 | |
| 865 | // splitRow is a table row's cells, split at each pipe no backslash |
| 866 | // escapes, less the pipes that open and close the row. A row of a table |
| 867 | // with n columns has n cells, the missing ones empty. n < 0 keeps them |
| 868 | // all. |
| 869 | func splitRow(s string, n int) []string { |
| 870 | s = strings.Trim(s, " ") |
| 871 | if strings.HasPrefix(s, "|") { |
| 872 | s = s[1:] |
| 873 | } |
| 874 | if strings.HasSuffix(s, "|") && !strings.HasSuffix(s, `\|`) { |
| 875 | s = s[:len(s)-1] |
| 876 | } |
| 877 | var cells []string |
| 878 | start := 0 |
| 879 | for i := 0; i < len(s); i++ { |
| 880 | switch s[i] { |
| 881 | case '\\': |
| 882 | i++ |
| 883 | case '|': |
| 884 | cells = append(cells, s[start:i]) |
| 885 | start = i + 1 |
| 886 | } |
| 887 | if n >= 0 && len(cells) > n { |
| 888 | break |
| 889 | } |
| 890 | } |
| 891 | cells = append(cells, s[start:]) |
| 892 | for i := range cells { |
| 893 | cells[i] = strings.ReplaceAll(strings.TrimSpace(cells[i]), `\|`, "|") |
| 894 | } |
| 895 | if n >= 0 { |
| 896 | for len(cells) < n { |
| 897 | cells = append(cells, "") |
| 898 | } |
| 899 | cells = cells[:n] |
| 900 | } |
| 901 | return cells |
| 902 | } |
| 903 | |
| 904 | // definitions takes the link reference definitions that open a |
| 905 | // paragraph out of it. |
| 906 | func (p *parser) definitions(b *block) { |
| 907 | text := strings.Join(b.lines, "\n") |
| 908 | took := false |
| 909 | for strings.HasPrefix(text, "[") { |
| 910 | label, dest, title, n, ok := definition(text) |
| 911 | if !ok { |
| 912 | break |
| 913 | } |
| 914 | if key := normalizeLabel(label); key != "" { |
| 915 | if _, seen := p.refs[key]; !seen { |
| 916 | p.refs[key] = &linkRef{dest: dest, title: title} |
| 917 | } |
| 918 | } |
| 919 | text, took = text[n:], true |
| 920 | } |
| 921 | if took { |
| 922 | if strings.TrimSpace(text) == "" { |
| 923 | b.lines = nil |
| 924 | } else { |
| 925 | b.lines = strings.Split(text, "\n") |
| 926 | } |
| 927 | } |
| 928 | } |
| 929 | |
| 930 | // definition reads one link reference definition from the start of s. |
| 931 | func definition(s string) (label, dest, title string, n int, ok bool) { |
| 932 | label, i, ok := scanLabel(s, 0) |
| 933 | if !ok || i >= len(s) || s[i] != ':' || strings.HasPrefix(label, "^") { |
| 934 | return "", "", "", 0, false |
| 935 | } |
| 936 | i = skipSpace(s, i+1, true) |
| 937 | dest, j, ok := scanDest(s, i) |
| 938 | if !ok || j == i && !strings.HasPrefix(s[i:], "<>") { |
| 939 | return "", "", "", 0, false |
| 940 | } |
| 941 | // A title, separated from the destination by whitespace, and then |
| 942 | // nothing else on its line. |
| 943 | k := skipSpace(s, j, true) |
| 944 | if k > j { |
| 945 | if t, e, ok := scanTitle(s, k); ok { |
| 946 | if end := lineEnd(s, e); end >= 0 { |
| 947 | return label, dest, t, end, true |
| 948 | } |
| 949 | } |
| 950 | } |
| 951 | if end := lineEnd(s, j); end >= 0 { |
| 952 | return label, dest, "", end, true |
| 953 | } |
| 954 | return "", "", "", 0, false |
| 955 | } |
| 956 | |
| 957 | // lineEnd is where the line after i ends, past its line ending, when the |
| 958 | // rest of it is blank, and -1 when it is not. |
| 959 | func lineEnd(s string, i int) int { |
| 960 | for i < len(s) && s[i] == ' ' { |
| 961 | i++ |
| 962 | } |
| 963 | switch { |
| 964 | case i == len(s): |
| 965 | return i |
| 966 | case s[i] == '\n': |
| 967 | return i + 1 |
| 968 | } |
| 969 | return -1 |
| 970 | } |
| 971 | |
| 972 | // skipSpace skips spaces, and at most one line ending when newline is set. |
| 973 | func skipSpace(s string, i int, newline bool) int { |
| 974 | for i < len(s) && s[i] == ' ' { |
| 975 | i++ |
| 976 | } |
| 977 | if newline && i < len(s) && s[i] == '\n' { |
| 978 | i++ |
| 979 | for i < len(s) && s[i] == ' ' { |
| 980 | i++ |
| 981 | } |
| 982 | } |
| 983 | return i |
| 984 | } |
| 985 | |
| 986 | // scanLabel reads a link label, [ to ], from s[i]: at most maxLabel |
| 987 | // characters, with no unescaped bracket inside and something not blank. |
| 988 | func scanLabel(s string, i int) (label string, end int, ok bool) { |
| 989 | if i >= len(s) || s[i] != '[' { |
| 990 | return "", 0, false |
| 991 | } |
| 992 | // A character takes at most 4 bytes. |
| 993 | for j := i + 1; j < len(s) && j-i-1 <= 4*maxLabel; j++ { |
| 994 | switch s[j] { |
| 995 | case '\\': |
| 996 | j++ |
| 997 | case '[': |
| 998 | return "", 0, false |
| 999 | case ']': |
| 1000 | label = s[i+1 : j] |
| 1001 | return label, j + 1, strings.TrimSpace(label) != "" && utf8.RuneCountInString(label) <= maxLabel |
| 1002 | } |
| 1003 | } |
| 1004 | return "", 0, false |
| 1005 | } |
| 1006 | |
| 1007 | // normalizeLabel is the key a label matches by: case folded, with its |
| 1008 | // whitespace collapsed. It copies s at most three times, whatever s holds. |
| 1009 | func normalizeLabel(s string) string { |
| 1010 | var b strings.Builder |
| 1011 | b.Grow(len(s)) |
| 1012 | space := false |
| 1013 | for _, c := range s { |
| 1014 | if unicode.IsSpace(c) { |
| 1015 | space = b.Len() > 0 |
| 1016 | continue |
| 1017 | } |
| 1018 | if space { |
| 1019 | b.WriteByte(' ') |
| 1020 | space = false |
| 1021 | } |
| 1022 | b.WriteRune(c) |
| 1023 | } |
| 1024 | return strings.ToLower(strings.ToUpper(b.String())) |
| 1025 | } |
| 1026 | |
| 1027 | // scanDest reads a link destination from s[i]: <…> on one line, or text |
| 1028 | // with no space or control character and balanced parentheses. |
| 1029 | func scanDest(s string, i int) (dest string, end int, ok bool) { |
| 1030 | if i < len(s) && s[i] == '<' { |
| 1031 | for j := i + 1; j < len(s); j++ { |
| 1032 | switch s[j] { |
| 1033 | case '\\': |
| 1034 | j++ |
| 1035 | case '\n', '<': |
| 1036 | return "", 0, false |
| 1037 | case '>': |
| 1038 | return unescapeText(s[i+1 : j]), j + 1, true |
| 1039 | } |
| 1040 | } |
| 1041 | return "", 0, false |
| 1042 | } |
| 1043 | depth, j := 0, i |
| 1044 | for ; j < len(s); j++ { |
| 1045 | c := s[j] |
| 1046 | if c == '\\' && j+1 < len(s) && isPunct(s[j+1]) { |
| 1047 | j++ |
| 1048 | continue |
| 1049 | } |
| 1050 | if c <= ' ' || c == 0x7f { |
| 1051 | break |
| 1052 | } |
| 1053 | if c == '(' { |
| 1054 | if depth++; depth > maxParens { |
| 1055 | return "", 0, false |
| 1056 | } |
| 1057 | } |
| 1058 | if c == ')' { |
| 1059 | if depth == 0 { |
| 1060 | break |
| 1061 | } |
| 1062 | depth-- |
| 1063 | } |
| 1064 | } |
| 1065 | if depth != 0 { |
| 1066 | return "", 0, false |
| 1067 | } |
| 1068 | return unescapeText(s[i:j]), j, true |
| 1069 | } |
| 1070 | |
| 1071 | // scanTitle reads a link title from s[i]: in double or single quotes, or |
| 1072 | // in parentheses, with no blank line inside. |
| 1073 | func scanTitle(s string, i int) (title string, end int, ok bool) { |
| 1074 | if i >= len(s) { |
| 1075 | return "", 0, false |
| 1076 | } |
| 1077 | open := s[i] |
| 1078 | closer := open |
| 1079 | switch open { |
| 1080 | case '"', '\'': |
| 1081 | case '(': |
| 1082 | closer = ')' |
| 1083 | default: |
| 1084 | return "", 0, false |
| 1085 | } |
| 1086 | for j := i + 1; j < len(s); j++ { |
| 1087 | switch c := s[j]; { |
| 1088 | case c == '\\': |
| 1089 | j++ |
| 1090 | case c == closer: |
| 1091 | return unescapeText(s[i+1 : j]), j + 1, true |
| 1092 | case c == '(' && open == '(': |
| 1093 | return "", 0, false |
| 1094 | case c == '\n' && j+1 < len(s) && strings.TrimLeft(s[j+1:lineEndAt(s, j+1)], " ") == "": |
| 1095 | return "", 0, false |
| 1096 | } |
| 1097 | } |
| 1098 | return "", 0, false |
| 1099 | } |
| 1100 | |
| 1101 | func lineEndAt(s string, i int) int { |
| 1102 | if k := strings.IndexByte(s[i:], '\n'); k >= 0 { |
| 1103 | return i + k |
| 1104 | } |
| 1105 | return len(s) |
| 1106 | } |
| 1107 | |
| 1108 | func isPunct(c byte) bool { |
| 1109 | return c >= '!' && c <= '/' || c >= ':' && c <= '@' || c >= '[' && c <= '`' || c >= '{' && c <= '~' |
| 1110 | } |
| 1111 | |
| 1112 | // unescapeText decodes s's backslash escapes and entity references. |
| 1113 | func unescapeText(s string) string { |
| 1114 | if strings.IndexAny(s, `\&`) < 0 { |
| 1115 | return s |
| 1116 | } |
| 1117 | var b strings.Builder |
| 1118 | for i := 0; i < len(s); i++ { |
| 1119 | switch c := s[i]; { |
| 1120 | case c == '\\' && i+1 < len(s) && isPunct(s[i+1]): |
| 1121 | b.WriteByte(s[i+1]) |
| 1122 | i++ |
| 1123 | case c == '&': |
| 1124 | if text, n := entity(s[i:]); n > 0 { |
| 1125 | b.WriteString(text) |
| 1126 | i += n - 1 |
| 1127 | } else { |
| 1128 | b.WriteByte(c) |
| 1129 | } |
| 1130 | default: |
| 1131 | b.WriteByte(c) |
| 1132 | } |
| 1133 | } |
| 1134 | return b.String() |
| 1135 | } |
| 1136 | |
| 1137 | // entity reads an entity reference at the start of s, and gives what it |
| 1138 | // stands for and its length. n is 0 when s starts with none. |
| 1139 | func entity(s string) (text string, n int) { |
| 1140 | if len(s) < 3 || s[0] != '&' { |
| 1141 | return "", 0 |
| 1142 | } |
| 1143 | end := strings.IndexByte(s[:min(len(s), 40)], ';') |
| 1144 | if end < 2 { |
| 1145 | return "", 0 |
| 1146 | } |
| 1147 | name := s[1:end] |
| 1148 | if name[0] == '#' { |
| 1149 | digits, base := name[1:], 10 |
| 1150 | if len(digits) > 0 && (digits[0] == 'x' || digits[0] == 'X') { |
| 1151 | digits, base = digits[1:], 16 |
| 1152 | } |
| 1153 | if len(digits) == 0 || base == 10 && len(digits) > 7 || base == 16 && len(digits) > 6 { |
| 1154 | return "", 0 |
| 1155 | } |
| 1156 | v, err := strconv.ParseUint(digits, base, 32) |
| 1157 | if err != nil { |
| 1158 | return "", 0 |
| 1159 | } |
| 1160 | r := rune(v) |
| 1161 | if r == 0 || !utf8.ValidRune(r) { |
| 1162 | r = utf8.RuneError |
| 1163 | } |
| 1164 | return string(r), end + 1 |
| 1165 | } |
| 1166 | for i := 0; i < len(name); i++ { |
| 1167 | c := name[i] |
| 1168 | if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || i > 0 && c >= '0' && c <= '9') { |
| 1169 | return "", 0 |
| 1170 | } |
| 1171 | } |
| 1172 | // html knows every named entity. A name it decodes only in part, |
| 1173 | // as a legacy name followed by more, leaves at least two more |
| 1174 | // characters, and a whole one stands for one or two. |
| 1175 | ref := s[:end+1] |
| 1176 | if d := html.UnescapeString(ref); d != ref && utf8.RuneCountInString(d) <= 2 { |
| 1177 | return d, end + 1 |
| 1178 | } |
| 1179 | return "", 0 |
| 1180 | } |
| 1181 | |
| 1182 | // Rendering. |
| 1183 | |
| 1184 | type renderer struct { |
| 1185 | ctx context.Context |
| 1186 | opt Options |
| 1187 | refs map[string]*linkRef |
| 1188 | out bytes.Buffer |
| 1189 | headings []Heading |
| 1190 | slugs map[string]int |
| 1191 | // open closes the blocks open now, innermost first. mark is where the |
| 1192 | // output ended when the last block ended, and marked and headings |
| 1193 | // what was open and how many headings there were then. |
| 1194 | open *closer |
| 1195 | mark int |
| 1196 | marked *closer |
| 1197 | headingN int |
| 1198 | // stopped is set once the output would pass MaxOutput, when |
| 1199 | // truncated is set too, or once ctx is done, when err is its error. |
| 1200 | // Nothing more is parsed or written once it is set. |
| 1201 | stopped, truncated bool |
| 1202 | err error |
| 1203 | steps int |
| 1204 | // nodes is how many inline nodes the document's blocks have taken, |
| 1205 | // and brackets the most that waited for their ] at once. full is set |
| 1206 | // once nodes passes MaxInlineNodes: from then on, a block's inline |
| 1207 | // content renders as its text alone. |
| 1208 | nodes, brackets int |
| 1209 | full bool |
| 1210 | // labels is how many bytes of labels the document's references have |
| 1211 | // looked up, at most maxLabelBytes. |
| 1212 | labels int |
| 1213 | } |
| 1214 | |
| 1215 | // closer is the end tag of an open block, and n the bytes of it and of |
| 1216 | // every closer after it. |
| 1217 | type closer struct { |
| 1218 | tags string |
| 1219 | n int |
| 1220 | next *closer |
| 1221 | } |
| 1222 | |
| 1223 | func (c *closer) size() int { |
| 1224 | if c == nil { |
| 1225 | return 0 |
| 1226 | } |
| 1227 | return c.n |
| 1228 | } |
| 1229 | |
| 1230 | // fits reports whether n more bytes of output fit within MaxOutput, with |
| 1231 | // room left to close the blocks open now. When they do not, it truncates |
| 1232 | // the output. |
| 1233 | func (r *renderer) fits(n int) bool { |
| 1234 | if r.stopped { |
| 1235 | return false |
| 1236 | } |
| 1237 | if r.opt.MaxOutput > 0 && r.out.Len()+n+r.open.size() > r.opt.MaxOutput { |
| 1238 | r.truncate() |
| 1239 | return false |
| 1240 | } |
| 1241 | return true |
| 1242 | } |
| 1243 | |
| 1244 | // truncate cuts the output back to the last block that ended, closes |
| 1245 | // the blocks open then, and stops rendering. |
| 1246 | func (r *renderer) truncate() { |
| 1247 | r.stopped, r.truncated = true, true |
| 1248 | r.out.Truncate(r.mark) |
| 1249 | for c := r.marked; c != nil; c = c.next { |
| 1250 | r.out.WriteString(c.tags) |
| 1251 | } |
| 1252 | r.headings = r.headings[:r.headingN] |
| 1253 | } |
| 1254 | |
| 1255 | // done stops rendering, and is true, once ctx is done. It looks at ctx |
| 1256 | // once in every 256 calls. |
| 1257 | func (r *renderer) done() bool { |
| 1258 | if r.stopped { |
| 1259 | return true |
| 1260 | } |
| 1261 | if r.steps++; r.steps%256 == 0 && r.ctx.Err() != nil { |
| 1262 | r.stopped, r.err = true, r.ctx.Err() |
| 1263 | } |
| 1264 | return r.stopped |
| 1265 | } |
| 1266 | |
| 1267 | func (r *renderer) raw(s string) { |
| 1268 | if r.fits(len(s)) { |
| 1269 | r.out.WriteString(s) |
| 1270 | } |
| 1271 | } |
| 1272 | |
| 1273 | // text writes s escaped. Escaping makes nothing shorter, so s that does |
| 1274 | // not fit is never escaped. |
| 1275 | func (r *renderer) text(s string) { |
| 1276 | if r.fits(len(s)) { |
| 1277 | r.raw(escape(s)) |
| 1278 | } |
| 1279 | } |
| 1280 | |
| 1281 | func escape(s string) string { return html.EscapeString(s) } |
| 1282 | |
| 1283 | // enter writes a container's start tag, and holds its end tag until |
| 1284 | // leave writes it. |
| 1285 | func (r *renderer) enter(start, end string) { |
| 1286 | if r.fits(len(start) + len(end)) { |
| 1287 | r.out.WriteString(start) |
| 1288 | r.open = &closer{tags: end, n: len(end) + r.open.size(), next: r.open} |
| 1289 | } |
| 1290 | } |
| 1291 | |
| 1292 | func (r *renderer) leave() { |
| 1293 | if r.stopped { |
| 1294 | return |
| 1295 | } |
| 1296 | c := r.open |
| 1297 | r.open = c.next |
| 1298 | r.out.WriteString(c.tags) // counted since enter |
| 1299 | r.ended() |
| 1300 | } |
| 1301 | |
| 1302 | // ended marks a block's end: the output is whole up to here, once the |
| 1303 | // blocks open now are closed. |
| 1304 | func (r *renderer) ended() { |
| 1305 | if !r.stopped { |
| 1306 | r.mark, r.marked, r.headingN = r.out.Len(), r.open, len(r.headings) |
| 1307 | } |
| 1308 | } |
| 1309 | |
| 1310 | func (r *renderer) block(b *block, tight bool) { |
| 1311 | if r.done() { |
| 1312 | return |
| 1313 | } |
| 1314 | switch b.kind { |
| 1315 | case document: |
| 1316 | for _, c := range b.children { |
| 1317 | r.block(c, false) |
| 1318 | } |
| 1319 | return |
| 1320 | case quote: |
| 1321 | r.enter("<blockquote>\n", "</blockquote>\n") |
| 1322 | for _, c := range b.children { |
| 1323 | r.block(c, false) |
| 1324 | } |
| 1325 | r.leave() |
| 1326 | return |
| 1327 | case list: |
| 1328 | switch { |
| 1329 | case !b.ordered: |
| 1330 | r.enter("<ul>\n", "</ul>\n") |
| 1331 | case b.start != 1: |
| 1332 | r.enter(`<ol start="`+strconv.Itoa(b.start)+`">`+"\n", "</ol>\n") |
| 1333 | default: |
| 1334 | r.enter("<ol>\n", "</ol>\n") |
| 1335 | } |
| 1336 | for _, c := range b.children { |
| 1337 | r.block(c, b.tight) |
| 1338 | } |
| 1339 | r.leave() |
| 1340 | return |
| 1341 | case item: |
| 1342 | r.enter("<li>", "</li>\n") |
| 1343 | for i, c := range b.children { |
| 1344 | if i == 0 && c.kind == paragraph { |
| 1345 | c.lines = taskBox(c.lines) |
| 1346 | } |
| 1347 | if tight && c.kind == paragraph { |
| 1348 | r.inline(strings.Join(c.lines, "\n"), nil) |
| 1349 | } else { |
| 1350 | if i == 0 { |
| 1351 | r.raw("\n") |
| 1352 | } |
| 1353 | r.block(c, tight) |
| 1354 | } |
| 1355 | } |
| 1356 | r.leave() |
| 1357 | return |
| 1358 | case paragraph: |
| 1359 | r.raw("<p>") |
| 1360 | r.inline(strings.Join(b.lines, "\n"), nil) |
| 1361 | r.raw("</p>\n") |
| 1362 | case heading: |
| 1363 | var plain strings.Builder |
| 1364 | at := r.out.Len() |
| 1365 | r.inline(strings.Join(b.lines, "\n"), &plain) |
| 1366 | if r.stopped { |
| 1367 | return |
| 1368 | } |
| 1369 | body := string(r.out.Bytes()[at:]) |
| 1370 | r.out.Truncate(at) |
| 1371 | // A heading whose text gives no slug, such as # !!!, has no id |
| 1372 | // and no self-link. |
| 1373 | h := Heading{Level: b.level, Text: plain.String(), ID: r.slug(plain.String())} |
| 1374 | tag := "h" + strconv.Itoa(b.level) |
| 1375 | if h.ID == "" { |
| 1376 | r.raw("<" + tag + ">" + body + "</" + tag + ">\n") |
| 1377 | } else { |
| 1378 | r.raw("<" + tag + ` id="` + escape(h.ID) + `">` + body + ` <a class="anchor" href="#` + |
| 1379 | escape(fragment(h.ID)) + `">#</a></` + tag + ">\n") |
| 1380 | } |
| 1381 | if !r.stopped { |
| 1382 | r.headings = append(r.headings, h) |
| 1383 | } |
| 1384 | case fenced, indented: |
| 1385 | if b.info != "" { |
| 1386 | r.raw(`<pre><code class="language-` + escape(b.info) + `">`) |
| 1387 | } else { |
| 1388 | r.raw("<pre><code>") |
| 1389 | } |
| 1390 | for _, l := range b.lines { |
| 1391 | r.text(l) |
| 1392 | r.raw("\n") |
| 1393 | } |
| 1394 | r.raw("</code></pre>\n") |
| 1395 | case rule: |
| 1396 | r.raw("<hr>\n") |
| 1397 | case table: |
| 1398 | r.raw("<table>\n<thead>\n") |
| 1399 | for i, row := range b.rows { |
| 1400 | if i == 1 { |
| 1401 | r.raw("<tbody>\n") |
| 1402 | } |
| 1403 | cell := "td" |
| 1404 | if i == 0 { |
| 1405 | cell = "th" |
| 1406 | } |
| 1407 | r.raw("<tr>") |
| 1408 | for j, c := range row { |
| 1409 | switch b.align[j] { |
| 1410 | case 'l': |
| 1411 | r.raw("<" + cell + ` class="left">`) |
| 1412 | case 'c': |
| 1413 | r.raw("<" + cell + ` class="center">`) |
| 1414 | case 'r': |
| 1415 | r.raw("<" + cell + ` class="right">`) |
| 1416 | default: |
| 1417 | r.raw("<" + cell + ">") |
| 1418 | } |
| 1419 | r.inline(c, nil) |
| 1420 | r.raw("</" + cell + ">") |
| 1421 | } |
| 1422 | r.raw("</tr>\n") |
| 1423 | if i == 0 { |
| 1424 | r.raw("</thead>\n") |
| 1425 | } |
| 1426 | if r.stopped { |
| 1427 | return |
| 1428 | } |
| 1429 | } |
| 1430 | if len(b.rows) > 1 { |
| 1431 | r.raw("</tbody>\n") |
| 1432 | } |
| 1433 | r.raw("</table>\n") |
| 1434 | } |
| 1435 | r.ended() |
| 1436 | } |
| 1437 | |
| 1438 | // taskBox shows a task list item's box as text: ☐ for [ ] and ☑ for [x]. |
| 1439 | func taskBox(lines []string) []string { |
| 1440 | if len(lines) == 0 { |
| 1441 | return lines |
| 1442 | } |
| 1443 | l := lines[0] |
| 1444 | if len(l) >= 3 && l[0] == '[' && l[2] == ']' && (len(l) == 3 || l[3] == ' ') { |
| 1445 | box := "" |
| 1446 | switch l[1] { |
| 1447 | case ' ': |
| 1448 | box = "☐" |
| 1449 | case 'x', 'X': |
| 1450 | box = "☑" |
| 1451 | } |
| 1452 | if box != "" { |
| 1453 | out := append([]string{box + l[3:]}, lines[1:]...) |
| 1454 | return out |
| 1455 | } |
| 1456 | } |
| 1457 | return lines |
| 1458 | } |
| 1459 | |
| 1460 | // slug is a heading's id: its Slug, numbered when the document gave it |
| 1461 | // before. |
| 1462 | func (r *renderer) slug(text string) string { |
| 1463 | base := Slug(text) |
| 1464 | if base == "" { |
| 1465 | return "" |
| 1466 | } |
| 1467 | id := base |
| 1468 | for { |
| 1469 | if _, seen := r.slugs[id]; !seen { |
| 1470 | break |
| 1471 | } |
| 1472 | r.slugs[base]++ |
| 1473 | id = base + "-" + strconv.Itoa(r.slugs[base]) |
| 1474 | } |
| 1475 | r.slugs[id] = 0 |
| 1476 | return id |
| 1477 | } |
| 1478 | |
| 1479 | // fragment is a heading's id as a URL fragment. |
| 1480 | func fragment(id string) string { return normalizeURL(id) } |
| 1481 | |
| 1482 | // normalizeURL percent-encodes what a URL may not hold as it is, and |
| 1483 | // keeps a percent-encoding already there. |
| 1484 | func normalizeURL(s string) string { |
| 1485 | const hex = "0123456789ABCDEF" |
| 1486 | var b strings.Builder |
| 1487 | for i := 0; i < len(s); i++ { |
| 1488 | c := s[i] |
| 1489 | switch { |
| 1490 | case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', |
| 1491 | strings.IndexByte("-._~:/?#@!$&'()*+,;=", c) >= 0: |
| 1492 | b.WriteByte(c) |
| 1493 | case c == '%' && i+2 < len(s) && isHex(s[i+1]) && isHex(s[i+2]): |
| 1494 | b.WriteByte(c) |
| 1495 | default: |
| 1496 | b.WriteByte('%') |
| 1497 | b.WriteByte(hex[c>>4]) |
| 1498 | b.WriteByte(hex[c&15]) |
| 1499 | } |
| 1500 | } |
| 1501 | return b.String() |
| 1502 | } |
| 1503 | |
| 1504 | func isHex(c byte) bool { return c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F' } |
| 1505 | |
| 1506 | // href is where a link's destination goes, or ok false for one that |
| 1507 | // renders as text. dest is decoded already, so a control character or a |
| 1508 | // backslash in it was one in the input or was written as an escape or an |
| 1509 | // entity. A browser may read a backslash as a slash, so no destination |
| 1510 | // with one is safe to resolve or to write. |
| 1511 | func (r *renderer) href(dest string) (string, bool) { |
| 1512 | for i := 0; i < len(dest); i++ { |
| 1513 | if c := dest[i]; c < ' ' || c == 0x7f || c == '\\' { |
| 1514 | return "", false |
| 1515 | } |
| 1516 | } |
| 1517 | switch scheme, rest, kind := schemeOf(dest); kind { |
| 1518 | case relative: |
| 1519 | if dest == "" || r.opt.Resolve == nil { |
| 1520 | return "", false |
| 1521 | } |
| 1522 | return r.opt.Resolve(dest) |
| 1523 | case absolute: |
| 1524 | switch strings.ToLower(scheme) { |
| 1525 | case "http", "https": |
| 1526 | // Only with a host: http:x is relative to the page, and |
| 1527 | // https:// names none. An IPv6 address keeps its brackets. |
| 1528 | if before, host, after, ok := splitHost(rest); ok { |
| 1529 | if host[0] == '[' { |
| 1530 | return normalizeURL(scheme+":"+before) + host + normalizeURL(after), true |
| 1531 | } |
| 1532 | return normalizeURL(dest), true |
| 1533 | } |
| 1534 | case "mailto": |
| 1535 | return normalizeURL(dest), true |
| 1536 | } |
| 1537 | } |
| 1538 | return "", false |
| 1539 | } |
| 1540 | |
| 1541 | // The kinds of destination schemeOf tells apart. |
| 1542 | const ( |
| 1543 | relative = iota |
| 1544 | absolute |
| 1545 | refused |
| 1546 | ) |
| 1547 | |
| 1548 | // schemeOf reads the start of dest, up to its first /, ? or #. When that |
| 1549 | // is a scheme, a letter then letters, digits, +, - or ., followed by a |
| 1550 | // colon, dest is absolute, and schemeOf gives the scheme and what |
| 1551 | // follows its colon. When it holds no colon, dest is relative. Any other |
| 1552 | // dest is refused: a colon there that follows no scheme makes no |
| 1553 | // relative reference. |
| 1554 | func schemeOf(dest string) (scheme, rest string, kind int) { |
| 1555 | for i := 0; i < len(dest); i++ { |
| 1556 | switch c := dest[i]; { |
| 1557 | case c == ':': |
| 1558 | if !isScheme(dest[:i]) { |
| 1559 | return "", "", refused |
| 1560 | } |
| 1561 | return dest[:i], dest[i+1:], absolute |
| 1562 | case c == '/' || c == '?' || c == '#': |
| 1563 | return "", "", relative |
| 1564 | } |
| 1565 | } |
| 1566 | return "", "", relative |
| 1567 | } |
| 1568 | |
| 1569 | // splitHost splits rest, what follows an http or https scheme's colon, |
| 1570 | // at the host its authority names: what comes before the host, the host, |
| 1571 | // and what follows it. ok is false unless rest starts with // and an |
| 1572 | // authority whose host is not empty once its user and its port are taken |
| 1573 | // off. A host in brackets is an IPv6 address, and ok is false unless |
| 1574 | // netip parses it as one, and only a port of one to five digits, or none, |
| 1575 | // follows it. |
| 1576 | func splitHost(rest string) (before, host, after string, ok bool) { |
| 1577 | if !strings.HasPrefix(rest, "//") { |
| 1578 | return "", "", "", false |
| 1579 | } |
| 1580 | end := len(rest) |
| 1581 | if i := strings.IndexAny(rest[2:], "/?#"); i >= 0 { |
| 1582 | end = 2 + i |
| 1583 | } |
| 1584 | start := 2 |
| 1585 | if i := strings.LastIndexByte(rest[:end], '@'); i >= 0 { |
| 1586 | start = i + 1 |
| 1587 | } |
| 1588 | hostPort := rest[start:end] |
| 1589 | if strings.HasPrefix(hostPort, "[") { |
| 1590 | i := strings.IndexByte(hostPort, ']') |
| 1591 | if i < 2 { |
| 1592 | return "", "", "", false |
| 1593 | } |
| 1594 | if a, err := netip.ParseAddr(hostPort[1:i]); err != nil || !a.Is6() { |
| 1595 | return "", "", "", false |
| 1596 | } |
| 1597 | if port := hostPort[i+1:]; port != "" && !isPort(port) { |
| 1598 | return "", "", "", false |
| 1599 | } |
| 1600 | host = hostPort[:i+1] |
| 1601 | } else if host, _, _ = strings.Cut(hostPort, ":"); host == "" { |
| 1602 | return "", "", "", false |
| 1603 | } |
| 1604 | return rest[:start], host, rest[start+len(host):], true |
| 1605 | } |
| 1606 | |
| 1607 | // isPort reports whether s is a colon and then one to five digits. |
| 1608 | func isPort(s string) bool { |
| 1609 | if len(s) < 2 || len(s) > 6 || s[0] != ':' { |
| 1610 | return false |
| 1611 | } |
| 1612 | for i := 1; i < len(s); i++ { |
| 1613 | if !isDigit(s[i]) { |
| 1614 | return false |
| 1615 | } |
| 1616 | } |
| 1617 | return true |
| 1618 | } |
| 1619 | |
| 1620 | func isScheme(s string) bool { |
| 1621 | if s == "" || !isAlpha(s[0]) { |
| 1622 | return false |
| 1623 | } |
| 1624 | for i := 1; i < len(s); i++ { |
| 1625 | if c := s[i]; !(isAlpha(c) || isDigit(c) || c == '+' || c == '-' || c == '.') { |
| 1626 | return false |
| 1627 | } |
| 1628 | } |
| 1629 | return true |
| 1630 | } |