package chatmarkdown import ( "bytes" "regexp" "sort" "strings" "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/text" "github.com/yuin/goldmark/util" ) // A draft is a reply still arriving, rendered by Render's own walk over // the same parse. What the next characters could still change is left // out until they come: // // - a last line that is only a list marker, a heading's hashes, a fence // or a rule on its way ("-", "2.", "##", "``") waits for more of its // line; // - in the paragraph still open at the end, an emphasis opener or a // backtick with no closer yet is not shown, so its words are plain // text until it closes, and a link on its way shows only its words; // - an open code fence is an open code block, as goldmark parses it. // // Everything else is Render's: the same parser, the same escaping, the // same links. // parse is goldmark's default parser with its emphasis and code span // parsers watched: what each returns is noted in seen, so a draft // can find the openers left without a closer. Watching changes nothing // they parse, and Render and RenderDraft share it. func parse(source []byte) (ast.Node, *seen) { inline := parser.DefaultInlineParsers() for i, p := range inline { if ip, ok := p.Value.(parser.InlineParser); ok && bytes.ContainsAny(ip.Trigger(), "*_`") { inline[i] = util.Prioritized(watched{ip}, p.Priority) } } blocks := parser.DefaultBlockParsers() for i, b := range blocks { if bp, ok := b.Value.(parser.BlockParser); ok && bytes.ContainsAny(bp.Trigger(), "`") { blocks[i] = util.Prioritized(fence{bp}, b.Priority) } } p := parser.NewParser(parser.WithBlockParsers(blocks...), parser.WithInlineParsers(inline...), parser.WithParagraphTransformers(parser.DefaultParagraphTransformers()...), ) s := &seen{} pc := parser.NewContext() pc.Set(seenKey, s) return p.Parse(text.NewReader(source), parser.WithContext(pc)), s } var seenKey = parser.NewContextKey() type seen struct{ found []ast.Node } type watched struct{ parser.InlineParser } func (w watched) Parse(parent ast.Node, block text.Reader, pc parser.Context) ast.Node { n := w.InlineParser.Parse(parent, block, pc) if s, ok := pc.Get(seenKey).(*seen); ok && n != nil { s.found = append(s.found, n) } return n } // fence is goldmark's fenced code parser, watched: a fence that meets its // closing line is noted in seen, so a draft knows which fence is still // open. Watching changes nothing it parses. type fence struct{ parser.BlockParser } func (f fence) Continue(b ast.Node, reader text.Reader, pc parser.Context) parser.State { st := f.BlockParser.Continue(b, reader, pc) if s, ok := pc.Get(seenKey).(*seen); ok && st&parser.Close != 0 { s.found = append(s.found, b) } return st } // closed is whether a fence met its closing line. func (s *seen) closed(v *ast.FencedCodeBlock) bool { for _, f := range s.found { if f == v { return true } } return false } // markerOnly is a last line with nothing yet but the start of a block: // a bullet or a number, hashes, a quote, a fence, a rule or an underline, // perhaps with the opener of its first words ("- **"). var markerOnly = regexp.MustCompile("^[ \t]*(?:[-+*>]|[0-9]{1,9}[.)]?|#{1,6}|[`~]+|[-=_* \t]+)?[ \t]*[*_`]*$") // fenceLine is a last line that opens a fence, perhaps in a quote or a // list item: its label is still arriving, and the box it opens waits for // the whole line so its label and its wrapping are settled when it shows. var fenceLine = regexp.MustCompile("^[ \t>]*(?:(?:[-+*]|[0-9]{1,9}[.)])[ \t]+)?(?:```|~~~)[^\n]*$") // steady holds back a last line that is only a block's marker, or a // fence's opening line. func steady(body string) string { i := strings.LastIndexByte(body, '\n') + 1 if markerOnly.MatchString(body[i:]) || fenceLine.MatchString(body[i:]) { return body[:i] } return body } // openLink is a link on its way at the end of a line: its "[" (or "!["), // its words, and its "]" or "](" with as much of the destination as has // come. Brackets in a code span are not a link (no backtick inside). var openLink = regexp.MustCompile("(!?\\[)[^\\[\\]\n`]*(\\](?:\\([^()\\s]*)?)?$") // unclosed is what a draft leaves out of the paragraph still open at the // end: openers without a closer and the brackets of a link on its way. func unclosed(root ast.Node, source []byte, s *seen) spans { from := openFrom(root, source) if from < 0 { return nil } var out spans for _, n := range s.found { switch v := n.(type) { case *parser.Delimiter: // What is left of a run that can open: "**Yes" and " *it", // not "2 * 3" (which cannot open) or "it*" (which closes); // and a run at the very end, which can be either once the // next character comes. opens := v.CanOpen && (!v.CanClose || v.OriginalLength >= 2) || v.Segment.Stop == len(source) if v.Length > 0 && opens && v.Segment.Start >= from { out = append(out, v.Segment) } case *ast.Text: // The code span parser returns its backticks as text when no // closing run follows. if v.Segment.Start >= from { out = append(out, v.Segment) } } } line := bytes.LastIndexByte(source, '\n') + 1 if line < from { line = from } if m := openLink.FindSubmatchIndex(source[line:]); m != nil && (line+m[2] == 0 || source[line+m[2]-1] != '\\') { out = append(out, text.NewSegment(line+m[2], line+m[3])) if m[4] >= 0 { out = append(out, text.NewSegment(line+m[4], line+m[5])) } } sort.Slice(out, func(i, j int) bool { return out[i].Start < out[j].Start }) return out } // openFrom is where the paragraph (or heading) still open at the end of // the source starts, or -1 when the source ends in anything else or the // last paragraph has ended: a blank line after it, or a heading's line // break. Openers before it were never closed and show as the finished // message shows them. func openFrom(root ast.Node, source []byte) int { n := root for n.LastChild() != nil && n.LastChild().Type() == ast.TypeBlock { n = n.LastChild() } switch n.(type) { case *ast.Paragraph, *ast.TextBlock, *ast.Heading: default: return -1 } lines := n.Lines() if lines.Len() == 0 { return -1 } breaks := bytes.Count(source[lines.At(lines.Len()-1).Stop:], []byte("\n")) if _, heading := n.(*ast.Heading); heading && breaks > 0 || breaks > 1 { return -1 } return lines.At(0).Start } // spans are source ranges a draft leaves out of its text, in order. type spans []text.Segment // value is a text segment's source without the ranges left out. func (h spans) value(source []byte, s text.Segment) []byte { if len(h) == 0 { return s.Value(source) } var out []byte at := s.Start for _, x := range h { if x.Stop <= at || x.Start >= s.Stop { continue } if x.Start > at { out = append(out, source[at:x.Start]...) } at = x.Stop } if at < s.Stop { out = append(out, source[at:s.Stop]...) } return out }