1package parser
2
3import (
4 "github.com/yuin/goldmark/ast"
5 "github.com/yuin/goldmark/text"
6 "github.com/yuin/goldmark/util"
7)
8
9type listItemParser struct {
10}
11
12var defaultListItemParser = &listItemParser{}
13
14// NewListItemParser returns a new BlockParser that
15// parses list items.
16func NewListItemParser() BlockParser {
17 return defaultListItemParser
18}
19
20func (b *listItemParser) Trigger() []byte {
21 return []byte{'-', '+', '*', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
22}
23
24func (b *listItemParser) Open(parent ast.Node, reader text.Reader, pc Context) (ast.Node, State) {
25 list, lok := parent.(*ast.List)
26 if !lok { // list item must be a child of a list
27 return nil, NoChildren
28 }
29 offset := lastOffset(list)
30 line, _ := reader.PeekLine()
31 match, typ := matchesListItem(line, false)
32 if typ == notList {
33 return nil, NoChildren
34 }
35 if match[1]-offset > 3 {
36 return nil, NoChildren
37 }
38
39 pc.Set(emptyListItemWithBlankLines, nil)
40
41 itemOffset := calcListOffset(line, match)
42 node := ast.NewListItem(match[3] + itemOffset)
43 if match[4] < 0 || util.IsBlank(line[match[4]:match[5]]) {
44 return node, NoChildren
45 }
46
47 pos, padding := util.IndentPosition(line[match[4]:], match[4], itemOffset)
48 child := match[3] + pos
49 reader.AdvanceAndSetPadding(child, padding)
50 return node, HasChildren
51}
52
53func (b *listItemParser) Continue(node ast.Node, reader text.Reader, pc Context) State {
54 line, _ := reader.PeekLine()
55 if util.IsBlank(line) {
56 reader.Advance(len(line) - 1)
57 return Continue | HasChildren
58 }
59
60 offset := lastOffset(node.Parent())
61 isEmpty := node.ChildCount() == 0 && pc.Get(emptyListItemWithBlankLines) != nil
62 indent, _ := util.IndentWidth(line, reader.LineOffset())
63 if (isEmpty || indent < offset) && indent < 4 {
64 _, typ := matchesListItem(line, true)
65 // new list item found
66 if typ != notList {
67 pc.Set(skipListParserKey, listItemFlagValue)
68 return Close
69 }
70 if !isEmpty {
71 return Close
72 }
73 }
74 pos, padding := util.IndentPosition(line, reader.LineOffset(), offset)
75 reader.AdvanceAndSetPadding(pos, padding)
76
77 return Continue | HasChildren
78}
79
80func (b *listItemParser) Close(node ast.Node, reader text.Reader, pc Context) {
81 // nothing to do
82}
83
84func (b *listItemParser) CanInterruptParagraph() bool {
85 return true
86}
87
88func (b *listItemParser) CanAcceptIndentedLine() bool {
89 return false
90}