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