markup.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. // Copyright 2017 The Gogs 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 markup
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "regexp"
  10. "strings"
  11. "github.com/Unknwon/com"
  12. "golang.org/x/net/html"
  13. "github.com/gogits/gogs/pkg/setting"
  14. "github.com/gogits/gogs/pkg/tool"
  15. )
  16. // IsReadmeFile reports whether name looks like a README file based on its extension.
  17. func IsReadmeFile(name string) bool {
  18. return strings.HasPrefix(strings.ToLower(name), "readme")
  19. }
  20. // IsIPythonNotebook reports whether name looks like a IPython notebook based on its extension.
  21. func IsIPythonNotebook(name string) bool {
  22. return strings.HasSuffix(name, ".ipynb")
  23. }
  24. const (
  25. ISSUE_NAME_STYLE_NUMERIC = "numeric"
  26. ISSUE_NAME_STYLE_ALPHANUMERIC = "alphanumeric"
  27. )
  28. var (
  29. // MentionPattern matches string that mentions someone, e.g. @Unknwon
  30. MentionPattern = regexp.MustCompile(`(\s|^|\W)@[0-9a-zA-Z-_\.]+`)
  31. // CommitPattern matches link to certain commit with or without trailing hash,
  32. // e.g. https://try.gogs.io/gogs/gogs/commit/d8a994ef243349f321568f9e36d5c3f444b99cae#diff-2
  33. CommitPattern = regexp.MustCompile(`(\s|^)https?.*commit/[0-9a-zA-Z]+(#+[0-9a-zA-Z-]*)?`)
  34. // IssueFullPattern matches link to an issue with or without trailing hash,
  35. // e.g. https://try.gogs.io/gogs/gogs/issues/4#issue-685
  36. IssueFullPattern = regexp.MustCompile(`(\s|^)https?.*issues/[0-9]+(#+[0-9a-zA-Z-]*)?`)
  37. // IssueNumericPattern matches string that references to a numeric issue, e.g. #1287
  38. IssueNumericPattern = regexp.MustCompile(`( |^|\()#[0-9]+\b`)
  39. // IssueAlphanumericPattern matches string that references to an alphanumeric issue, e.g. ABC-1234
  40. IssueAlphanumericPattern = regexp.MustCompile(`( |^|\()[A-Z]{1,10}-[1-9][0-9]*\b`)
  41. // CrossReferenceIssueNumericPattern matches string that references a numeric issue in a difference repository
  42. // e.g. gogits/gogs#12345
  43. CrossReferenceIssueNumericPattern = regexp.MustCompile(`( |^)[0-9a-zA-Z-_\.]+/[0-9a-zA-Z-_\.]+#[0-9]+\b`)
  44. // Sha1CurrentPattern matches string that represents a commit SHA, e.g. d8a994ef243349f321568f9e36d5c3f444b99cae
  45. // FIXME: this pattern matches pure numbers as well, right now we do a hack to check in RenderSha1CurrentPattern
  46. // by converting string to a number.
  47. Sha1CurrentPattern = regexp.MustCompile(`\b[0-9a-f]{40}\b`)
  48. )
  49. // FindAllMentions matches mention patterns in given content
  50. // and returns a list of found user names without @ prefix.
  51. func FindAllMentions(content string) []string {
  52. mentions := MentionPattern.FindAllString(content, -1)
  53. for i := range mentions {
  54. mentions[i] = mentions[i][strings.Index(mentions[i], "@")+1:] // Strip @ character
  55. }
  56. return mentions
  57. }
  58. // cutoutVerbosePrefix cutouts URL prefix including sub-path to
  59. // return a clean unified string of request URL path.
  60. func cutoutVerbosePrefix(prefix string) string {
  61. if len(prefix) == 0 || prefix[0] != '/' {
  62. return prefix
  63. }
  64. count := 0
  65. for i := 0; i < len(prefix); i++ {
  66. if prefix[i] == '/' {
  67. count++
  68. }
  69. if count >= 3+setting.AppSubURLDepth {
  70. return prefix[:i]
  71. }
  72. }
  73. return prefix
  74. }
  75. // RenderIssueIndexPattern renders issue indexes to corresponding links.
  76. func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  77. urlPrefix = cutoutVerbosePrefix(urlPrefix)
  78. pattern := IssueNumericPattern
  79. if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC {
  80. pattern = IssueAlphanumericPattern
  81. }
  82. ms := pattern.FindAll(rawBytes, -1)
  83. for _, m := range ms {
  84. if m[0] == ' ' || m[0] == '(' {
  85. m = m[1:] // ignore leading space or opening parentheses
  86. }
  87. var link string
  88. if metas == nil {
  89. link = fmt.Sprintf(`<a href="%s/issues/%s">%s</a>`, urlPrefix, m[1:], m)
  90. } else {
  91. // Support for external issue tracker
  92. if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC {
  93. metas["index"] = string(m)
  94. } else {
  95. metas["index"] = string(m[1:])
  96. }
  97. link = fmt.Sprintf(`<a href="%s">%s</a>`, com.Expand(metas["format"], metas), m)
  98. }
  99. rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
  100. }
  101. return rawBytes
  102. }
  103. // Note: this section is for purpose of increase performance and
  104. // reduce memory allocation at runtime since they are constant literals.
  105. var pound = []byte("#")
  106. // RenderCrossReferenceIssueIndexPattern renders issue indexes from other repositories to corresponding links.
  107. func RenderCrossReferenceIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  108. ms := CrossReferenceIssueNumericPattern.FindAll(rawBytes, -1)
  109. for _, m := range ms {
  110. if m[0] == ' ' || m[0] == '(' {
  111. m = m[1:] // ignore leading space or opening parentheses
  112. }
  113. delimIdx := bytes.Index(m, pound)
  114. repo := string(m[:delimIdx])
  115. index := string(m[delimIdx+1:])
  116. link := fmt.Sprintf(`<a href="%s%s/issues/%s">%s</a>`, setting.AppURL, repo, index, m)
  117. rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
  118. }
  119. return rawBytes
  120. }
  121. // RenderSha1CurrentPattern renders SHA1 strings to corresponding links that assumes in the same repository.
  122. func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
  123. return []byte(Sha1CurrentPattern.ReplaceAllStringFunc(string(rawBytes[:]), func(m string) string {
  124. if com.StrTo(m).MustInt() > 0 {
  125. return m
  126. }
  127. return fmt.Sprintf(`<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, tool.ShortSHA1(string(m)))
  128. }))
  129. }
  130. // RenderSpecialLink renders mentions, indexes and SHA1 strings to corresponding links.
  131. func RenderSpecialLink(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  132. ms := MentionPattern.FindAll(rawBytes, -1)
  133. for _, m := range ms {
  134. m = m[bytes.Index(m, []byte("@")):]
  135. rawBytes = bytes.Replace(rawBytes, m,
  136. []byte(fmt.Sprintf(`<a href="%s/%s">%s</a>`, setting.AppSubURL, m[1:], m)), -1)
  137. }
  138. rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix, metas)
  139. rawBytes = RenderCrossReferenceIssueIndexPattern(rawBytes, urlPrefix, metas)
  140. rawBytes = RenderSha1CurrentPattern(rawBytes, urlPrefix)
  141. return rawBytes
  142. }
  143. var (
  144. leftAngleBracket = []byte("</")
  145. rightAngleBracket = []byte(">")
  146. )
  147. var noEndTags = []string{"input", "br", "hr", "img"}
  148. // wrapImgWithLink warps link to standalone <img> tags.
  149. func wrapImgWithLink(urlPrefix string, buf *bytes.Buffer, token html.Token) {
  150. // Extract "src" and "alt" attributes
  151. var src, alt string
  152. for i := range token.Attr {
  153. switch token.Attr[i].Key {
  154. case "src":
  155. src = token.Attr[i].Val
  156. case "alt":
  157. alt = token.Attr[i].Val
  158. }
  159. }
  160. // Skip in case the "src" is empty
  161. if len(src) == 0 {
  162. buf.WriteString(token.String())
  163. return
  164. }
  165. // Prepend repository base URL for internal links
  166. needPrepend := !isLink([]byte(src))
  167. if needPrepend {
  168. urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
  169. if src[0] != '/' {
  170. urlPrefix += "/"
  171. }
  172. }
  173. buf.WriteString(`<a href="`)
  174. if needPrepend {
  175. buf.WriteString(urlPrefix)
  176. buf.WriteString(src)
  177. } else {
  178. buf.WriteString(src)
  179. }
  180. buf.WriteString(`">`)
  181. if needPrepend {
  182. src = strings.Replace(urlPrefix+string(src), " ", "%20", -1)
  183. buf.WriteString(`<img src="`)
  184. buf.WriteString(src)
  185. buf.WriteString(`"`)
  186. if len(alt) > 0 {
  187. buf.WriteString(` alt="`)
  188. buf.WriteString(alt)
  189. buf.WriteString(`"`)
  190. }
  191. buf.WriteString(`>`)
  192. } else {
  193. buf.WriteString(token.String())
  194. }
  195. buf.WriteString(`</a>`)
  196. }
  197. // postProcessHTML treats different types of HTML differently,
  198. // and only renders special links for plain text blocks.
  199. func postProcessHTML(rawHTML []byte, urlPrefix string, metas map[string]string) []byte {
  200. startTags := make([]string, 0, 5)
  201. buf := bytes.NewBuffer(nil)
  202. tokenizer := html.NewTokenizer(bytes.NewReader(rawHTML))
  203. OUTER_LOOP:
  204. for html.ErrorToken != tokenizer.Next() {
  205. token := tokenizer.Token()
  206. switch token.Type {
  207. case html.TextToken:
  208. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix, metas))
  209. case html.StartTagToken:
  210. tagName := token.Data
  211. if tagName == "img" {
  212. wrapImgWithLink(urlPrefix, buf, token)
  213. continue OUTER_LOOP
  214. }
  215. buf.WriteString(token.String())
  216. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  217. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  218. stackNum := 1
  219. for html.ErrorToken != tokenizer.Next() {
  220. token = tokenizer.Token()
  221. // Copy the token to the output verbatim
  222. buf.WriteString(token.String())
  223. // Stack number doesn't increate for tags without end tags.
  224. if token.Type == html.StartTagToken && !com.IsSliceContainsStr(noEndTags, token.Data) {
  225. stackNum++
  226. }
  227. // If this is the close tag to the outer-most, we are done
  228. if token.Type == html.EndTagToken {
  229. stackNum--
  230. if stackNum <= 0 && strings.EqualFold(tagName, token.Data) {
  231. break
  232. }
  233. }
  234. }
  235. continue OUTER_LOOP
  236. }
  237. if !com.IsSliceContainsStr(noEndTags, tagName) {
  238. startTags = append(startTags, tagName)
  239. }
  240. case html.EndTagToken:
  241. if len(startTags) == 0 {
  242. buf.WriteString(token.String())
  243. break
  244. }
  245. buf.Write(leftAngleBracket)
  246. buf.WriteString(startTags[len(startTags)-1])
  247. buf.Write(rightAngleBracket)
  248. startTags = startTags[:len(startTags)-1]
  249. default:
  250. buf.WriteString(token.String())
  251. }
  252. }
  253. if io.EOF == tokenizer.Err() {
  254. return buf.Bytes()
  255. }
  256. // If we are not at the end of the input, then some other parsing error has occurred,
  257. // so return the input verbatim.
  258. return rawHTML
  259. }
  260. type Type string
  261. const (
  262. UNRECOGNIZED Type = "unrecognized"
  263. MARKDOWN Type = "markdown"
  264. ORG_MODE Type = "orgmode"
  265. )
  266. // Render takes a string or []byte and renders to HTML in given type of syntax with special links.
  267. func Render(typ Type, input interface{}, urlPrefix string, metas map[string]string) []byte {
  268. var rawBytes []byte
  269. switch v := input.(type) {
  270. case []byte:
  271. rawBytes = v
  272. case string:
  273. rawBytes = []byte(v)
  274. default:
  275. panic(fmt.Sprintf("unrecognized input content type: %T", input))
  276. }
  277. urlPrefix = strings.TrimRight(strings.Replace(urlPrefix, " ", "%20", -1), "/")
  278. var rawHTML []byte
  279. switch typ {
  280. case MARKDOWN:
  281. rawHTML = RawMarkdown(rawBytes, urlPrefix)
  282. case ORG_MODE:
  283. default:
  284. return rawBytes // Do nothing if syntax type is not recognized
  285. }
  286. rawHTML = postProcessHTML(rawHTML, urlPrefix, metas)
  287. return SanitizeBytes(rawHTML)
  288. }