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.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. link = []byte(lnk)
  46. }
  47. v.Destination = link
  48. parent := n.Parent()
  49. // Create a link around image only if parent is not already a link
  50. if _, ok := parent.(*ast.Link); !ok && parent != nil {
  51. wrap := ast.NewLink()
  52. wrap.Destination = link
  53. wrap.Title = v.Title
  54. parent.ReplaceChild(parent, n, wrap)
  55. wrap.AppendChild(wrap, n)
  56. }
  57. case *ast.Link:
  58. // Links need their href to munged to be a real value
  59. link := v.Destination
  60. if len(link) > 0 && !markup.IsLink(link) &&
  61. link[0] != '#' && !bytes.HasPrefix(link, byteMailto) {
  62. // special case: this is not a link, a hash link or a mailto:, so it's a
  63. // relative URL
  64. lnk := string(link)
  65. if pc.Get(isWikiKey).(bool) {
  66. lnk = giteautil.URLJoin("wiki", lnk)
  67. }
  68. link = []byte(giteautil.URLJoin(pc.Get(urlPrefixKey).(string), lnk))
  69. }
  70. if len(link) > 0 && link[0] == '#' {
  71. link = []byte("#user-content-" + string(link)[1:])
  72. }
  73. v.Destination = link
  74. }
  75. return ast.WalkContinue, nil
  76. })
  77. }
  78. type prefixedIDs struct {
  79. values map[string]bool
  80. }
  81. // Generate generates a new element id.
  82. func (p *prefixedIDs) Generate(value []byte, kind ast.NodeKind) []byte {
  83. dft := []byte("id")
  84. if kind == ast.KindHeading {
  85. dft = []byte("heading")
  86. }
  87. return p.GenerateWithDefault(value, dft)
  88. }
  89. // Generate generates a new element id.
  90. func (p *prefixedIDs) GenerateWithDefault(value []byte, dft []byte) []byte {
  91. result := common.CleanValue(value)
  92. if len(result) == 0 {
  93. result = dft
  94. }
  95. if !bytes.HasPrefix(result, []byte("user-content-")) {
  96. result = append([]byte("user-content-"), result...)
  97. }
  98. if _, ok := p.values[util.BytesToReadOnlyString(result)]; !ok {
  99. p.values[util.BytesToReadOnlyString(result)] = true
  100. return result
  101. }
  102. for i := 1; ; i++ {
  103. newResult := fmt.Sprintf("%s-%d", result, i)
  104. if _, ok := p.values[newResult]; !ok {
  105. p.values[newResult] = true
  106. return []byte(newResult)
  107. }
  108. }
  109. }
  110. // Put puts a given element id to the used ids table.
  111. func (p *prefixedIDs) Put(value []byte) {
  112. p.values[util.BytesToReadOnlyString(value)] = true
  113. }
  114. func newPrefixedIDs() *prefixedIDs {
  115. return &prefixedIDs{
  116. values: map[string]bool{},
  117. }
  118. }
  119. // NewTaskCheckBoxHTMLRenderer creates a TaskCheckBoxHTMLRenderer to render tasklists
  120. // in the gitea form.
  121. func NewTaskCheckBoxHTMLRenderer(opts ...html.Option) renderer.NodeRenderer {
  122. r := &TaskCheckBoxHTMLRenderer{
  123. Config: html.NewConfig(),
  124. }
  125. for _, opt := range opts {
  126. opt.SetHTMLOption(&r.Config)
  127. }
  128. return r
  129. }
  130. // TaskCheckBoxHTMLRenderer is a renderer.NodeRenderer implementation that
  131. // renders checkboxes in list items.
  132. // Overrides the default goldmark one to present the gitea format
  133. type TaskCheckBoxHTMLRenderer struct {
  134. html.Config
  135. }
  136. // RegisterFuncs implements renderer.NodeRenderer.RegisterFuncs.
  137. func (r *TaskCheckBoxHTMLRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
  138. reg.Register(east.KindTaskCheckBox, r.renderTaskCheckBox)
  139. }
  140. func (r *TaskCheckBoxHTMLRenderer) renderTaskCheckBox(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
  141. if !entering {
  142. return ast.WalkContinue, nil
  143. }
  144. n := node.(*east.TaskCheckBox)
  145. end := ">"
  146. if r.XHTML {
  147. end = " />"
  148. }
  149. var err error
  150. if n.IsChecked {
  151. _, err = w.WriteString(`<span class="ui fitted disabled checkbox"><input type="checkbox" disabled="disabled"` + end + `<label` + end + `</span>`)
  152. } else {
  153. _, err = w.WriteString(`<span class="ui checked fitted disabled checkbox"><input type="checkbox" checked="" disabled="disabled"` + end + `<label` + end + `</span>`)
  154. }
  155. if err != nil {
  156. return ast.WalkStop, err
  157. }
  158. return ast.WalkContinue, nil
  159. }