heading.go 939 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package parser
  2. import (
  3. "github.com/usememos/memos/plugin/gomark/parser/tokenizer"
  4. )
  5. type HeadingParser struct {
  6. Level int
  7. ContentTokens []*tokenizer.Token
  8. }
  9. func NewHeadingParser() *HeadingParser {
  10. return &HeadingParser{}
  11. }
  12. func (*HeadingParser) Match(tokens []*tokenizer.Token) *HeadingParser {
  13. cursor := 0
  14. for _, token := range tokens {
  15. if token.Type == tokenizer.Hash {
  16. cursor++
  17. } else {
  18. break
  19. }
  20. }
  21. if len(tokens) <= cursor+1 {
  22. return nil
  23. }
  24. if tokens[cursor].Type != tokenizer.Space {
  25. return nil
  26. }
  27. level := cursor
  28. if level == 0 || level > 6 {
  29. return nil
  30. }
  31. cursor++
  32. contentTokens := []*tokenizer.Token{}
  33. for _, token := range tokens[cursor:] {
  34. if token.Type == tokenizer.Newline {
  35. break
  36. }
  37. contentTokens = append(contentTokens, token)
  38. cursor++
  39. }
  40. if len(contentTokens) == 0 {
  41. return nil
  42. }
  43. return &HeadingParser{
  44. Level: level,
  45. ContentTokens: contentTokens,
  46. }
  47. }