memos/plugin/gomark/parser/embedded_content.go

44 lines
1.4 KiB
Go
Raw Normal View History

2024-01-20 01:56:10 +08:00
package parser
import (
"github.com/usememos/memos/plugin/gomark/ast"
"github.com/usememos/memos/plugin/gomark/parser/tokenizer"
)
type EmbeddedContentParser struct{}
func NewEmbeddedContentParser() *EmbeddedContentParser {
return &EmbeddedContentParser{}
}
2024-01-23 21:27:05 +08:00
func (*EmbeddedContentParser) Match(tokens []*tokenizer.Token) (ast.Node, int) {
2024-01-23 21:23:40 +08:00
matchedTokens := tokenizer.GetFirstLine(tokens)
if len(matchedTokens) < 6 {
2024-01-23 21:23:40 +08:00
return nil, 0
2024-01-20 01:56:10 +08:00
}
2024-01-23 21:23:40 +08:00
if matchedTokens[0].Type != tokenizer.ExclamationMark || matchedTokens[1].Type != tokenizer.LeftSquareBracket || matchedTokens[2].Type != tokenizer.LeftSquareBracket {
return nil, 0
2024-01-20 01:56:10 +08:00
}
matched := false
2024-01-23 21:23:40 +08:00
for index, token := range matchedTokens[:len(matchedTokens)-1] {
if token.Type == tokenizer.RightSquareBracket && matchedTokens[index+1].Type == tokenizer.RightSquareBracket && index+1 == len(matchedTokens)-1 {
2024-01-20 01:56:10 +08:00
matched = true
break
}
}
if !matched {
2024-01-23 21:23:40 +08:00
return nil, 0
2024-01-20 01:56:10 +08:00
}
2024-01-23 21:23:40 +08:00
contentTokens := matchedTokens[3 : len(matchedTokens)-2]
resourceName, params := tokenizer.Stringify(contentTokens), ""
questionMarkIndex := tokenizer.FindUnescaped(contentTokens, tokenizer.QuestionMark)
if questionMarkIndex > 0 {
resourceName, params = tokenizer.Stringify(contentTokens[:questionMarkIndex]), tokenizer.Stringify(contentTokens[questionMarkIndex+1:])
2024-01-20 01:56:10 +08:00
}
return &ast.EmbeddedContent{
ResourceName: resourceName,
Params: params,
2024-01-23 21:23:40 +08:00
}, len(matchedTokens)
2024-01-20 01:56:10 +08:00
}