memos/plugin/gomark/parser/bold.go

61 lines
1.3 KiB
Go
Raw Normal View History

2023-05-23 20:49:32 +08:00
package parser
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"
2023-05-23 20:49:32 +08:00
"github.com/usememos/memos/plugin/gomark/parser/tokenizer"
)
2023-12-12 23:24:02 +08:00
type BoldParser struct{}
func NewBoldParser() InlineParser {
2023-12-13 21:00:13 +08:00
return &BoldParser{}
2023-05-23 20:49:32 +08:00
}
2023-12-12 23:24:02 +08:00
func (*BoldParser) Match(tokens []*tokenizer.Token) (int, bool) {
2023-05-23 20:49:32 +08:00
if len(tokens) < 5 {
2023-12-12 23:24:02 +08:00
return 0, false
2023-05-23 20:49:32 +08:00
}
prefixTokens := tokens[:2]
if prefixTokens[0].Type != prefixTokens[1].Type {
2023-12-12 23:24:02 +08:00
return 0, false
2023-05-23 20:49:32 +08:00
}
prefixTokenType := prefixTokens[0].Type
2023-12-13 21:00:13 +08:00
if prefixTokenType != tokenizer.Asterisk && prefixTokenType != tokenizer.Underline {
2023-12-12 23:24:02 +08:00
return 0, false
}
2023-05-23 20:49:32 +08:00
cursor, matched := 2, false
2023-05-23 20:49:32 +08:00
for ; cursor < len(tokens)-1; cursor++ {
token, nextToken := tokens[cursor], tokens[cursor+1]
if token.Type == tokenizer.Newline || nextToken.Type == tokenizer.Newline {
2023-12-12 23:24:02 +08:00
return 0, false
2023-05-23 20:49:32 +08:00
}
if token.Type == prefixTokenType && nextToken.Type == prefixTokenType {
matched = true
2023-05-23 20:49:32 +08:00
break
}
}
if !matched {
2023-12-12 23:24:02 +08:00
return 0, false
}
return cursor + 2, true
}
2023-12-13 23:50:05 +08:00
func (p *BoldParser) 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-05-23 20:49:32 +08:00
}
2023-12-12 23:24:02 +08:00
prefixTokenType := tokens[0].Type
contentTokens := tokens[2 : size-2]
return &ast.Bold{
Symbol: prefixTokenType,
Content: tokenizer.Stringify(contentTokens),
2023-12-13 23:50:05 +08:00
}, nil
2023-05-23 20:49:32 +08:00
}