memos/plugin/gomark/parser/blockquote.go

53 lines
1.1 KiB
Go
Raw Normal View History

2023-12-13 21:00:13 +08:00
package parser
import (
2023-12-13 23:50:05 +08:00
"errors"
2023-12-13 21:00:13 +08:00
"github.com/usememos/memos/plugin/gomark/ast"
"github.com/usememos/memos/plugin/gomark/parser/tokenizer"
)
type BlockquoteParser struct{}
func NewBlockquoteParser() *BlockquoteParser {
return &BlockquoteParser{}
}
func (*BlockquoteParser) Match(tokens []*tokenizer.Token) (int, bool) {
if len(tokens) < 4 {
return 0, false
}
if tokens[0].Type != tokenizer.GreaterThan || tokens[1].Type != tokenizer.Space {
return 0, false
}
contentTokens := []*tokenizer.Token{}
for _, token := range tokens[2:] {
2023-12-13 23:50:05 +08:00
contentTokens = append(contentTokens, token)
2023-12-13 21:00:13 +08:00
if token.Type == tokenizer.Newline {
break
}
}
if len(contentTokens) == 0 {
return 0, false
}
return len(contentTokens) + 2, true
}
2023-12-13 23:50:05 +08:00
func (p *BlockquoteParser) Parse(tokens []*tokenizer.Token) (ast.Node, error) {
2023-12-13 21:00:13 +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-13 21:00:13 +08:00
}
contentTokens := tokens[2:size]
2023-12-13 23:50:05 +08:00
blockquote := &ast.Blockquote{}
children, err := ParseInline(blockquote, contentTokens)
if err != nil {
return nil, err
2023-12-13 21:00:13 +08:00
}
2023-12-13 23:50:05 +08:00
blockquote.Children = children
return blockquote, nil
2023-12-13 21:00:13 +08:00
}