gitea源码

math.go 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package math
  4. import (
  5. "code.gitea.io/gitea/modules/markup/internal"
  6. giteaUtil "code.gitea.io/gitea/modules/util"
  7. "github.com/yuin/goldmark"
  8. "github.com/yuin/goldmark/parser"
  9. "github.com/yuin/goldmark/renderer"
  10. "github.com/yuin/goldmark/util"
  11. )
  12. type Options struct {
  13. Enabled bool
  14. ParseInlineDollar bool // inline $$ xxx $$ text
  15. ParseInlineParentheses bool // inline \( xxx \) text
  16. ParseBlockDollar bool // block $$ multiple-line $$ text
  17. ParseBlockSquareBrackets bool // block \[ multiple-line \] text
  18. }
  19. // Extension is a math extension
  20. type Extension struct {
  21. renderInternal *internal.RenderInternal
  22. options Options
  23. }
  24. // NewExtension creates a new math extension with the provided options
  25. func NewExtension(renderInternal *internal.RenderInternal, opts ...Options) *Extension {
  26. opt := giteaUtil.OptionalArg(opts)
  27. r := &Extension{
  28. renderInternal: renderInternal,
  29. options: opt,
  30. }
  31. return r
  32. }
  33. // Extend extends goldmark with our parsers and renderers
  34. func (e *Extension) Extend(m goldmark.Markdown) {
  35. if !e.options.Enabled {
  36. return
  37. }
  38. var inlines []util.PrioritizedValue
  39. if e.options.ParseInlineParentheses {
  40. inlines = append(inlines, util.Prioritized(NewInlineParenthesesParser(), 501))
  41. }
  42. inlines = append(inlines, util.Prioritized(NewInlineDollarParser(e.options.ParseInlineDollar), 502))
  43. m.Parser().AddOptions(parser.WithInlineParsers(inlines...))
  44. m.Parser().AddOptions(parser.WithBlockParsers(
  45. util.Prioritized(NewBlockParser(e.options.ParseBlockDollar, e.options.ParseBlockSquareBrackets), 701),
  46. ))
  47. m.Renderer().AddOptions(renderer.WithNodeRenderers(
  48. util.Prioritized(NewBlockRenderer(e.renderInternal), 501),
  49. util.Prioritized(NewInlineRenderer(e.renderInternal), 502),
  50. ))
  51. }