memos/plugin/gomark/parser/heading.go

53 lines
949 B
Go
Raw Normal View History

package parser
import (
2023-05-23 14:52:31 +03:00
"github.com/usememos/memos/plugin/gomark/parser/tokenizer"
)
type HeadingTokenizer struct {
2023-05-23 14:52:31 +03:00
Level int
ContentTokens []*tokenizer.Token
}
func NewHeadingTokenizer() *HeadingTokenizer {
return &HeadingTokenizer{}
}
2023-05-23 14:52:31 +03:00
func (*HeadingTokenizer) Match(tokens []*tokenizer.Token) *HeadingTokenizer {
cursor := 0
for _, token := range tokens {
if token.Type == tokenizer.Hash {
cursor++
} else {
2023-05-23 14:52:31 +03:00
break
}
}
2023-05-23 14:52:31 +03:00
if len(tokens) <= cursor+1 {
return nil
}
if tokens[cursor].Type != tokenizer.Space {
return nil
}
level := cursor
if level == 0 || level > 6 {
return nil
}
2023-05-23 14:52:31 +03:00
cursor++
contentTokens := []*tokenizer.Token{}
for _, token := range tokens[cursor:] {
if token.Type == tokenizer.Newline {
break
}
contentTokens = append(contentTokens, token)
}
if len(contentTokens) == 0 {
return nil
}
return &HeadingTokenizer{
Level: level,
ContentTokens: contentTokens,
}
}