You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

goldmark.go 5.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package markdown
  5. import (
  6. "bytes"
  7. "fmt"
  8. "strings"
  9. "code.gitea.io/gitea/modules/markup"
  10. "code.gitea.io/gitea/modules/markup/common"
  11. giteautil "code.gitea.io/gitea/modules/util"
  12. "github.com/yuin/goldmark/ast"
  13. east "github.com/yuin/goldmark/extension/ast"
  14. "github.com/yuin/goldmark/parser"
  15. "github.com/yuin/goldmark/renderer"
  16. "github.com/yuin/goldmark/renderer/html"
  17. "github.com/yuin/goldmark/text"
  18. "github.com/yuin/goldmark/util"
  19. )
  20. var byteMailto = []byte("mailto:")
  21. // GiteaASTTransformer is a default transformer of the goldmark tree.
  22. type GiteaASTTransformer struct{}
  23. // Transform transforms the given AST tree.
  24. func (g *GiteaASTTransformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) {
  25. _ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
  26. if !entering {
  27. return ast.WalkContinue, nil
  28. }
  29. switch v := n.(type) {
  30. case *ast.Image:
  31. // Images need two things:
  32. //
  33. // 1. Their src needs to munged to be a real value
  34. // 2. If they're not wrapped with a link they need a link wrapper
  35. // Check if the destination is a real link
  36. link := v.Destination
  37. if len(link) > 0 && !markup.IsLink(link) {
  38. prefix := pc.Get(urlPrefixKey).(string)
  39. if pc.Get(isWikiKey).(bool) {
  40. prefix = giteautil.URLJoin(prefix, "wiki", "raw")
  41. }
  42. prefix = strings.Replace(prefix, "/src/", "/media/", 1)
  43. lnk := string(link)
  44. lnk = giteautil.URLJoin(prefix, lnk)
  45. lnk = strings.Replace(lnk, " ", "+", -1)
  46. link = []byte(lnk)
  47. }
  48. v.Destination = link
  49. parent := n.Parent()
  50. // Create a link around image only if parent is not already a link
  51. if _, ok := parent.(*ast.Link); !ok && parent != nil {
  52. wrap := ast.NewLink()
  53. wrap.Destination = link
  54. wrap.Title = v.Title
  55. parent.ReplaceChild(parent, n, wrap)
  56. wrap.AppendChild(wrap, n)
  57. }
  58. case *ast.Link:
  59. // Links need their href to munged to be a real value
  60. link := v.Destination
  61. if len(link) > 0 && !markup.IsLink(link) &&
  62. link[0] != '#' && !bytes.HasPrefix(link, byteMailto) {
  63. // special case: this is not a link, a hash link or a mailto:, so it's a
  64. // relative URL
  65. lnk := string(link)
  66. if pc.Get(isWikiKey).(bool) {
  67. lnk = giteautil.URLJoin("wiki", lnk)
  68. }
  69. link = []byte(giteautil.URLJoin(pc.Get(urlPrefixKey).(string), lnk))
  70. }
  71. v.Destination = link
  72. }
  73. return ast.WalkContinue, nil
  74. })
  75. }
  76. type prefixedIDs struct {
  77. values map[string]bool
  78. }
  79. // Generate generates a new element id.
  80. func (p *prefixedIDs) Generate(value []byte, kind ast.NodeKind) []byte {
  81. dft := []byte("id")
  82. if kind == ast.KindHeading {
  83. dft = []byte("heading")
  84. }
  85. return p.GenerateWithDefault(value, dft)
  86. }
  87. // Generate generates a new element id.
  88. func (p *prefixedIDs) GenerateWithDefault(value []byte, dft []byte) []byte {
  89. result := common.CleanValue(value)
  90. if len(result) == 0 {
  91. result = dft
  92. }
  93. if !bytes.HasPrefix(result, []byte("user-content-")) {
  94. result = append([]byte("user-content-"), result...)
  95. }
  96. if _, ok := p.values[util.BytesToReadOnlyString(result)]; !ok {
  97. p.values[util.BytesToReadOnlyString(result)] = true
  98. return result
  99. }
  100. for i := 1; ; i++ {
  101. newResult := fmt.Sprintf("%s-%d", result, i)
  102. if _, ok := p.values[newResult]; !ok {
  103. p.values[newResult] = true
  104. return []byte(newResult)
  105. }
  106. }
  107. }
  108. // Put puts a given element id to the used ids table.
  109. func (p *prefixedIDs) Put(value []byte) {
  110. p.values[util.BytesToReadOnlyString(value)] = true
  111. }
  112. func newPrefixedIDs() *prefixedIDs {
  113. return &prefixedIDs{
  114. values: map[string]bool{},
  115. }
  116. }
  117. // NewTaskCheckBoxHTMLRenderer creates a TaskCheckBoxHTMLRenderer to render tasklists
  118. // in the gitea form.
  119. func NewTaskCheckBoxHTMLRenderer(opts ...html.Option) renderer.NodeRenderer {
  120. r := &TaskCheckBoxHTMLRenderer{
  121. Config: html.NewConfig(),
  122. }
  123. for _, opt := range opts {
  124. opt.SetHTMLOption(&r.Config)
  125. }
  126. return r
  127. }
  128. // TaskCheckBoxHTMLRenderer is a renderer.NodeRenderer implementation that
  129. // renders checkboxes in list items.
  130. // Overrides the default goldmark one to present the gitea format
  131. type TaskCheckBoxHTMLRenderer struct {
  132. html.Config
  133. }
  134. // RegisterFuncs implements renderer.NodeRenderer.RegisterFuncs.
  135. func (r *TaskCheckBoxHTMLRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
  136. reg.Register(east.KindTaskCheckBox, r.renderTaskCheckBox)
  137. }
  138. func (r *TaskCheckBoxHTMLRenderer) renderTaskCheckBox(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
  139. if !entering {
  140. return ast.WalkContinue, nil
  141. }
  142. n := node.(*east.TaskCheckBox)
  143. end := ">"
  144. if r.XHTML {
  145. end = " />"
  146. }
  147. var err error
  148. if n.IsChecked {
  149. _, err = w.WriteString(`<span class="ui fitted disabled checkbox"><input type="checkbox" disabled="disabled"` + end + `<label` + end + `</span>`)
  150. } else {
  151. _, err = w.WriteString(`<span class="ui checked fitted disabled checkbox"><input type="checkbox" checked="" disabled="disabled"` + end + `<label` + end + `</span>`)
  152. }
  153. if err != nil {
  154. return ast.WalkStop, err
  155. }
  156. return ast.WalkContinue, nil
  157. }