2023-05-18 16:33:18 +03:00
|
|
|
package parser
|
|
|
|
|
|
|
|
import (
|
2023-05-23 14:52:31 +03:00
|
|
|
"github.com/usememos/memos/plugin/gomark/parser/tokenizer"
|
2023-05-18 16:33:18 +03:00
|
|
|
)
|
|
|
|
|
2023-05-23 15:49:32 +03:00
|
|
|
type HeadingParser struct {
|
2023-05-23 14:52:31 +03:00
|
|
|
Level int
|
|
|
|
ContentTokens []*tokenizer.Token
|
2023-05-18 16:33:18 +03:00
|
|
|
}
|
|
|
|
|
2023-05-23 15:49:32 +03:00
|
|
|
func NewHeadingParser() *HeadingParser {
|
|
|
|
return &HeadingParser{}
|
2023-05-18 16:33:18 +03:00
|
|
|
}
|
|
|
|
|
2023-05-23 15:49:32 +03:00
|
|
|
func (*HeadingParser) Match(tokens []*tokenizer.Token) *HeadingParser {
|
2023-05-23 14:52:31 +03:00
|
|
|
cursor := 0
|
|
|
|
for _, token := range tokens {
|
|
|
|
if token.Type == tokenizer.Hash {
|
|
|
|
cursor++
|
2023-05-18 16:33:18 +03:00
|
|
|
} else {
|
2023-05-23 14:52:31 +03:00
|
|
|
break
|
2023-05-18 16:33:18 +03:00
|
|
|
}
|
|
|
|
}
|
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
|
2023-05-18 16:33:18 +03:00
|
|
|
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)
|
2023-05-23 15:49:32 +03:00
|
|
|
cursor++
|
2023-05-23 14:52:31 +03:00
|
|
|
}
|
|
|
|
if len(contentTokens) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-05-23 15:49:32 +03:00
|
|
|
return &HeadingParser{
|
2023-05-23 14:52:31 +03:00
|
|
|
Level: level,
|
|
|
|
ContentTokens: contentTokens,
|
2023-05-18 16:33:18 +03:00
|
|
|
}
|
|
|
|
}
|