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

goldmark.go 5.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. if len(link) > 0 && link[0] == '#' {
  72. link = []byte("#user-content-" + string(link)[1:])
  73. }
  74. v.Destination = link
  75. }
  76. return ast.WalkContinue, nil
  77. })
  78. }
  79. type prefixedIDs struct {
  80. values map[string]bool
  81. }
  82. // Generate generates a new element id.
  83. func (p *prefixedIDs) Generate(value []byte, kind ast.NodeKind) []byte {
  84. dft := []byte("id")
  85. if kind == ast.KindHeading {
  86. dft = []byte("heading")
  87. }
  88. return p.GenerateWithDefault(value, dft)
  89. }
  90. // Generate generates a new element id.
  91. func (p *prefixedIDs) GenerateWithDefault(value []byte, dft []byte) []byte {
  92. result := common.CleanValue(value)
  93. if len(result) == 0 {
  94. result = dft
  95. }
  96. if !bytes.HasPrefix(result, []byte("user-content-")) {
  97. result = append([]byte("user-content-"), result...)
  98. }
  99. if _, ok := p.values[util.BytesToReadOnlyString(result)]; !ok {
  100. p.values[util.BytesToReadOnlyString(result)] = true
  101. return result
  102. }
  103. for i := 1; ; i++ {
  104. newResult := fmt.Sprintf("%s-%d", result, i)
  105. if _, ok := p.values[newResult]; !ok {
  106. p.values[newResult] = true
  107. return []byte(newResult)
  108. }
  109. }
  110. }
  111. // Put puts a given element id to the used ids table.
  112. func (p *prefixedIDs) Put(value []byte) {
  113. p.values[util.BytesToReadOnlyString(value)] = true
  114. }
  115. func newPrefixedIDs() *prefixedIDs {
  116. return &prefixedIDs{
  117. values: map[string]bool{},
  118. }
  119. }
  120. // NewTaskCheckBoxHTMLRenderer creates a TaskCheckBoxHTMLRenderer to render tasklists
  121. // in the gitea form.
  122. func NewTaskCheckBoxHTMLRenderer(opts ...html.Option) renderer.NodeRenderer {
  123. r := &TaskCheckBoxHTMLRenderer{
  124. Config: html.NewConfig(),
  125. }
  126. for _, opt := range opts {
  127. opt.SetHTMLOption(&r.Config)
  128. }
  129. return r
  130. }
  131. // TaskCheckBoxHTMLRenderer is a renderer.NodeRenderer implementation that
  132. // renders checkboxes in list items.
  133. // Overrides the default goldmark one to present the gitea format
  134. type TaskCheckBoxHTMLRenderer struct {
  135. html.Config
  136. }
  137. // RegisterFuncs implements renderer.NodeRenderer.RegisterFuncs.
  138. func (r *TaskCheckBoxHTMLRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
  139. reg.Register(east.KindTaskCheckBox, r.renderTaskCheckBox)
  140. }
  141. func (r *TaskCheckBoxHTMLRenderer) renderTaskCheckBox(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
  142. if !entering {
  143. return ast.WalkContinue, nil
  144. }
  145. n := node.(*east.TaskCheckBox)
  146. end := ">"
  147. if r.XHTML {
  148. end = " />"
  149. }
  150. var err error
  151. if n.IsChecked {
  152. _, err = w.WriteString(`<span class="ui fitted disabled checkbox"><input type="checkbox" disabled="disabled"` + end + `<label` + end + `</span>`)
  153. } else {
  154. _, err = w.WriteString(`<span class="ui checked fitted disabled checkbox"><input type="checkbox" checked="" disabled="disabled"` + end + `<label` + end + `</span>`)
  155. }
  156. if err != nil {
  157. return ast.WalkStop, err
  158. }
  159. return ast.WalkContinue, nil
  160. }