memos/plugin/gomark/parser/paragraph.go

49 lines
1 KiB
Go
Raw Normal View History

package parser
2023-12-12 23:24:02 +08:00
import (
2023-12-13 23:50:05 +08:00
"errors"
2023-12-12 23:24:02 +08:00
"github.com/usememos/memos/plugin/gomark/ast"
"github.com/usememos/memos/plugin/gomark/parser/tokenizer"
)
type ParagraphParser struct {
ContentTokens []*tokenizer.Token
}
func NewParagraphParser() *ParagraphParser {
2023-12-13 21:00:13 +08:00
return &ParagraphParser{}
}
2023-12-12 23:24:02 +08:00
func (*ParagraphParser) Match(tokens []*tokenizer.Token) (int, bool) {
contentTokens := []*tokenizer.Token{}
2023-12-14 00:04:20 +08:00
for _, token := range tokens {
if token.Type == tokenizer.Newline {
break
}
2023-12-28 22:35:39 +08:00
contentTokens = append(contentTokens, token)
}
if len(contentTokens) == 0 {
2023-12-12 23:24:02 +08:00
return 0, false
}
2023-12-14 00:04:20 +08:00
if len(contentTokens) == 1 && contentTokens[0].Type == tokenizer.Newline {
return 0, false
}
2023-12-12 23:24:02 +08:00
return len(contentTokens), true
}
2023-12-13 23:50:05 +08:00
func (p *ParagraphParser) Parse(tokens []*tokenizer.Token) (ast.Node, error) {
2023-12-12 23:24:02 +08:00
size, ok := p.Match(tokens)
if size == 0 || !ok {
2023-12-13 23:50:05 +08:00
return nil, errors.New("not matched")
}
2023-12-12 23:24:02 +08:00
2023-12-28 22:35:39 +08:00
children, err := ParseInline(tokens[:size])
2023-12-13 23:50:05 +08:00
if err != nil {
return nil, err
2023-12-13 09:06:47 +08:00
}
2023-12-14 00:24:41 +08:00
return &ast.Paragraph{
Children: children,
}, nil
}