memos/plugin/gomark/parser/link.go

73 lines
1.6 KiB
Go
Raw Normal View History

package parser
2023-12-13 21:00:13 +08:00
import (
"github.com/usememos/memos/plugin/gomark/ast"
"github.com/usememos/memos/plugin/gomark/parser/tokenizer"
)
2023-12-13 21:00:13 +08:00
type LinkParser struct{}
func NewLinkParser() *LinkParser {
return &LinkParser{}
}
2023-12-13 21:00:13 +08:00
func (*LinkParser) Match(tokens []*tokenizer.Token) (int, bool) {
if len(tokens) < 5 {
return 0, false
}
if tokens[0].Type != tokenizer.LeftSquareBracket {
2023-12-13 21:00:13 +08:00
return 0, false
}
2023-12-13 21:00:13 +08:00
textTokens := []*tokenizer.Token{}
for _, token := range tokens[1:] {
if token.Type == tokenizer.Newline {
return 0, false
}
2023-12-13 21:00:13 +08:00
if token.Type == tokenizer.RightSquareBracket {
break
}
2023-12-13 21:00:13 +08:00
textTokens = append(textTokens, token)
}
2023-12-13 21:00:13 +08:00
if len(textTokens)+4 >= len(tokens) {
return 0, false
}
if tokens[2+len(textTokens)].Type != tokenizer.LeftParenthesis {
return 0, false
}
2023-12-13 21:00:13 +08:00
urlTokens := []*tokenizer.Token{}
for _, token := range tokens[3+len(textTokens):] {
if token.Type == tokenizer.Newline || token.Type == tokenizer.Space {
2023-12-13 21:00:13 +08:00
return 0, false
}
if token.Type == tokenizer.RightParenthesis {
break
}
2023-12-13 21:00:13 +08:00
urlTokens = append(urlTokens, token)
}
if 4+len(urlTokens)+len(textTokens) > len(tokens) {
return 0, false
}
2023-12-13 21:00:13 +08:00
return 4 + len(urlTokens) + len(textTokens), true
}
func (p *LinkParser) Parse(tokens []*tokenizer.Token) ast.Node {
size, ok := p.Match(tokens)
if size == 0 || !ok {
return nil
}
2023-12-13 21:00:13 +08:00
textTokens := []*tokenizer.Token{}
for _, token := range tokens[1:] {
if token.Type == tokenizer.RightSquareBracket {
break
}
textTokens = append(textTokens, token)
}
2023-12-13 21:00:13 +08:00
urlTokens := tokens[2+len(textTokens)+1 : size-1]
return &ast.Link{
Text: tokenizer.Stringify(textTokens),
URL: tokenizer.Stringify(urlTokens),
}
}