| 1 | package chatmarkdown |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "regexp" |
| 6 | "sort" |
| 7 | "strings" |
| 8 | |
| 9 | "github.com/yuin/goldmark/ast" |
| 10 | "github.com/yuin/goldmark/parser" |
| 11 | "github.com/yuin/goldmark/text" |
| 12 | "github.com/yuin/goldmark/util" |
| 13 | ) |
| 14 | |
| 15 | // A draft is a reply still arriving, rendered by Render's own walk over |
| 16 | // the same parse. What the next characters could still change is left |
| 17 | // out until they come: |
| 18 | // |
| 19 | // - a last line that is only a list marker, a heading's hashes, a fence |
| 20 | // or a rule on its way ("-", "2.", "##", "``") waits for more of its |
| 21 | // line; |
| 22 | // - in the paragraph still open at the end, an emphasis opener or a |
| 23 | // backtick with no closer yet is not shown, so its words are plain |
| 24 | // text until it closes, and a link on its way shows only its words; |
| 25 | // - an open code fence is an open code block, as goldmark parses it. |
| 26 | // |
| 27 | // Everything else is Render's: the same parser, the same escaping, the |
| 28 | // same links. |
| 29 | |
| 30 | // parse is goldmark's default parser with its emphasis and code span |
| 31 | // parsers watched: what each returns is noted in seen, so a draft |
| 32 | // can find the openers left without a closer. Watching changes nothing |
| 33 | // they parse, and Render and RenderDraft share it. |
| 34 | func parse(source []byte) (ast.Node, *seen) { |
| 35 | inline := parser.DefaultInlineParsers() |
| 36 | for i, p := range inline { |
| 37 | if ip, ok := p.Value.(parser.InlineParser); ok && bytes.ContainsAny(ip.Trigger(), "*_`") { |
| 38 | inline[i] = util.Prioritized(watched{ip}, p.Priority) |
| 39 | } |
| 40 | } |
| 41 | blocks := parser.DefaultBlockParsers() |
| 42 | for i, b := range blocks { |
| 43 | if bp, ok := b.Value.(parser.BlockParser); ok && bytes.ContainsAny(bp.Trigger(), "`") { |
| 44 | blocks[i] = util.Prioritized(fence{bp}, b.Priority) |
| 45 | } |
| 46 | } |
| 47 | p := parser.NewParser(parser.WithBlockParsers(blocks...), |
| 48 | parser.WithInlineParsers(inline...), |
| 49 | parser.WithParagraphTransformers(parser.DefaultParagraphTransformers()...), |
| 50 | ) |
| 51 | s := &seen{} |
| 52 | pc := parser.NewContext() |
| 53 | pc.Set(seenKey, s) |
| 54 | return p.Parse(text.NewReader(source), parser.WithContext(pc)), s |
| 55 | } |
| 56 | |
| 57 | var seenKey = parser.NewContextKey() |
| 58 | |
| 59 | type seen struct{ found []ast.Node } |
| 60 | |
| 61 | type watched struct{ parser.InlineParser } |
| 62 | |
| 63 | func (w watched) Parse(parent ast.Node, block text.Reader, pc parser.Context) ast.Node { |
| 64 | n := w.InlineParser.Parse(parent, block, pc) |
| 65 | if s, ok := pc.Get(seenKey).(*seen); ok && n != nil { |
| 66 | s.found = append(s.found, n) |
| 67 | } |
| 68 | return n |
| 69 | } |
| 70 | |
| 71 | // fence is goldmark's fenced code parser, watched: a fence that meets its |
| 72 | // closing line is noted in seen, so a draft knows which fence is still |
| 73 | // open. Watching changes nothing it parses. |
| 74 | type fence struct{ parser.BlockParser } |
| 75 | |
| 76 | func (f fence) Continue(b ast.Node, reader text.Reader, pc parser.Context) parser.State { |
| 77 | st := f.BlockParser.Continue(b, reader, pc) |
| 78 | if s, ok := pc.Get(seenKey).(*seen); ok && st&parser.Close != 0 { |
| 79 | s.found = append(s.found, b) |
| 80 | } |
| 81 | return st |
| 82 | } |
| 83 | |
| 84 | // closed is whether a fence met its closing line. |
| 85 | func (s *seen) closed(v *ast.FencedCodeBlock) bool { |
| 86 | for _, f := range s.found { |
| 87 | if f == v { |
| 88 | return true |
| 89 | } |
| 90 | } |
| 91 | return false |
| 92 | } |
| 93 | |
| 94 | // markerOnly is a last line with nothing yet but the start of a block: |
| 95 | // a bullet or a number, hashes, a quote, a fence, a rule or an underline, |
| 96 | // perhaps with the opener of its first words ("- **"). |
| 97 | var markerOnly = regexp.MustCompile("^[ \t]*(?:[-+*>]|[0-9]{1,9}[.)]?|#{1,6}|[`~]+|[-=_* \t]+)?[ \t]*[*_`]*$") |
| 98 | |
| 99 | // fenceLine is a last line that opens a fence, perhaps in a quote or a |
| 100 | // list item: its label is still arriving, and the box it opens waits for |
| 101 | // the whole line so its label and its wrapping are settled when it shows. |
| 102 | var fenceLine = regexp.MustCompile("^[ \t>]*(?:(?:[-+*]|[0-9]{1,9}[.)])[ \t]+)?(?:```|~~~)[^\n]*$") |
| 103 | |
| 104 | // steady holds back a last line that is only a block's marker, or a |
| 105 | // fence's opening line. |
| 106 | func steady(body string) string { |
| 107 | i := strings.LastIndexByte(body, '\n') + 1 |
| 108 | if markerOnly.MatchString(body[i:]) || fenceLine.MatchString(body[i:]) { |
| 109 | return body[:i] |
| 110 | } |
| 111 | return body |
| 112 | } |
| 113 | |
| 114 | // openLink is a link on its way at the end of a line: its "[" (or "!["), |
| 115 | // its words, and its "]" or "](" with as much of the destination as has |
| 116 | // come. Brackets in a code span are not a link (no backtick inside). |
| 117 | var openLink = regexp.MustCompile("(!?\\[)[^\\[\\]\n`]*(\\](?:\\([^()\\s]*)?)?$") |
| 118 | |
| 119 | // unclosed is what a draft leaves out of the paragraph still open at the |
| 120 | // end: openers without a closer and the brackets of a link on its way. |
| 121 | func unclosed(root ast.Node, source []byte, s *seen) spans { |
| 122 | from := openFrom(root, source) |
| 123 | if from < 0 { |
| 124 | return nil |
| 125 | } |
| 126 | var out spans |
| 127 | for _, n := range s.found { |
| 128 | switch v := n.(type) { |
| 129 | case *parser.Delimiter: |
| 130 | // What is left of a run that can open: "**Yes" and " *it", |
| 131 | // not "2 * 3" (which cannot open) or "it*" (which closes); |
| 132 | // and a run at the very end, which can be either once the |
| 133 | // next character comes. |
| 134 | opens := v.CanOpen && (!v.CanClose || v.OriginalLength >= 2) || v.Segment.Stop == len(source) |
| 135 | if v.Length > 0 && opens && v.Segment.Start >= from { |
| 136 | out = append(out, v.Segment) |
| 137 | } |
| 138 | case *ast.Text: |
| 139 | // The code span parser returns its backticks as text when no |
| 140 | // closing run follows. |
| 141 | if v.Segment.Start >= from { |
| 142 | out = append(out, v.Segment) |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | line := bytes.LastIndexByte(source, '\n') + 1 |
| 147 | if line < from { |
| 148 | line = from |
| 149 | } |
| 150 | if m := openLink.FindSubmatchIndex(source[line:]); m != nil && (line+m[2] == 0 || source[line+m[2]-1] != '\\') { |
| 151 | out = append(out, text.NewSegment(line+m[2], line+m[3])) |
| 152 | if m[4] >= 0 { |
| 153 | out = append(out, text.NewSegment(line+m[4], line+m[5])) |
| 154 | } |
| 155 | } |
| 156 | sort.Slice(out, func(i, j int) bool { return out[i].Start < out[j].Start }) |
| 157 | return out |
| 158 | } |
| 159 | |
| 160 | // openFrom is where the paragraph (or heading) still open at the end of |
| 161 | // the source starts, or -1 when the source ends in anything else or the |
| 162 | // last paragraph has ended: a blank line after it, or a heading's line |
| 163 | // break. Openers before it were never closed and show as the finished |
| 164 | // message shows them. |
| 165 | func openFrom(root ast.Node, source []byte) int { |
| 166 | n := root |
| 167 | for n.LastChild() != nil && n.LastChild().Type() == ast.TypeBlock { |
| 168 | n = n.LastChild() |
| 169 | } |
| 170 | switch n.(type) { |
| 171 | case *ast.Paragraph, *ast.TextBlock, *ast.Heading: |
| 172 | default: |
| 173 | return -1 |
| 174 | } |
| 175 | lines := n.Lines() |
| 176 | if lines.Len() == 0 { |
| 177 | return -1 |
| 178 | } |
| 179 | breaks := bytes.Count(source[lines.At(lines.Len()-1).Stop:], []byte("\n")) |
| 180 | if _, heading := n.(*ast.Heading); heading && breaks > 0 || breaks > 1 { |
| 181 | return -1 |
| 182 | } |
| 183 | return lines.At(0).Start |
| 184 | } |
| 185 | |
| 186 | // spans are source ranges a draft leaves out of its text, in order. |
| 187 | type spans []text.Segment |
| 188 | |
| 189 | // value is a text segment's source without the ranges left out. |
| 190 | func (h spans) value(source []byte, s text.Segment) []byte { |
| 191 | if len(h) == 0 { |
| 192 | return s.Value(source) |
| 193 | } |
| 194 | var out []byte |
| 195 | at := s.Start |
| 196 | for _, x := range h { |
| 197 | if x.Stop <= at || x.Start >= s.Stop { |
| 198 | continue |
| 199 | } |
| 200 | if x.Start > at { |
| 201 | out = append(out, source[at:x.Start]...) |
| 202 | } |
| 203 | at = x.Stop |
| 204 | } |
| 205 | if at < s.Stop { |
| 206 | out = append(out, source[at:s.Stop]...) |
| 207 | } |
| 208 | return out |
| 209 | } |
| 210 | |