link.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package parser
  2. import "github.com/usememos/memos/plugin/gomark/parser/tokenizer"
  3. type LinkParser struct {
  4. ContentTokens []*tokenizer.Token
  5. URL string
  6. }
  7. func NewLinkParser() *LinkParser {
  8. return &LinkParser{}
  9. }
  10. func (*LinkParser) Match(tokens []*tokenizer.Token) *LinkParser {
  11. if len(tokens) < 4 {
  12. return nil
  13. }
  14. if tokens[0].Type != tokenizer.LeftSquareBracket {
  15. return nil
  16. }
  17. cursor, contentTokens := 1, []*tokenizer.Token{}
  18. for ; cursor < len(tokens)-2; cursor++ {
  19. if tokens[cursor].Type == tokenizer.Newline {
  20. return nil
  21. }
  22. if tokens[cursor].Type == tokenizer.RightSquareBracket {
  23. break
  24. }
  25. contentTokens = append(contentTokens, tokens[cursor])
  26. }
  27. if tokens[cursor+1].Type != tokenizer.LeftParenthesis {
  28. return nil
  29. }
  30. matched, url := false, ""
  31. for _, token := range tokens[cursor+2:] {
  32. if token.Type == tokenizer.Newline || token.Type == tokenizer.Space {
  33. return nil
  34. }
  35. if token.Type == tokenizer.RightParenthesis {
  36. matched = true
  37. break
  38. }
  39. url += token.Value
  40. }
  41. if !matched || url == "" {
  42. return nil
  43. }
  44. if len(contentTokens) == 0 {
  45. contentTokens = append(contentTokens, &tokenizer.Token{
  46. Type: tokenizer.Text,
  47. Value: url,
  48. })
  49. }
  50. return &LinkParser{
  51. ContentTokens: contentTokens,
  52. URL: url,
  53. }
  54. }