markup.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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] == '(' || m[0] == '[' {
  85. // ignore leading space, opening parentheses, or opening square brackets
  86. m = m[1:]
  87. }
  88. var link string
  89. if metas == nil {
  90. link = fmt.Sprintf(`<a href="%s/issues/%s">%s</a>`, urlPrefix, m[1:], m)
  91. } else {
  92. // Support for external issue tracker
  93. if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC {
  94. metas["index"] = string(m)
  95. } else {
  96. metas["index"] = string(m[1:])
  97. }
  98. link = fmt.Sprintf(`<a href="%s">%s</a>`, com.Expand(metas["format"], metas), m)
  99. }
  100. rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
  101. }
  102. return rawBytes
  103. }
  104. // Note: this section is for purpose of increase performance and
  105. // reduce memory allocation at runtime since they are constant literals.
  106. var pound = []byte("#")
  107. // RenderCrossReferenceIssueIndexPattern renders issue indexes from other repositories to corresponding links.
  108. func RenderCrossReferenceIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  109. ms := CrossReferenceIssueNumericPattern.FindAll(rawBytes, -1)
  110. for _, m := range ms {
  111. if m[0] == ' ' || m[0] == '(' {
  112. m = m[1:] // ignore leading space or opening parentheses
  113. }
  114. delimIdx := bytes.Index(m, pound)
  115. repo := string(m[:delimIdx])
  116. index := string(m[delimIdx+1:])
  117. link := fmt.Sprintf(`<a href="%s%s/issues/%s">%s</a>`, setting.AppURL, repo, index, m)
  118. rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
  119. }
  120. return rawBytes
  121. }
  122. // RenderSha1CurrentPattern renders SHA1 strings to corresponding links that assumes in the same repository.
  123. func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
  124. return []byte(Sha1CurrentPattern.ReplaceAllStringFunc(string(rawBytes[:]), func(m string) string {
  125. if com.StrTo(m).MustInt() > 0 {
  126. return m
  127. }
  128. return fmt.Sprintf(`<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, tool.ShortSHA1(string(m)))
  129. }))
  130. }
  131. // RenderSpecialLink renders mentions, indexes and SHA1 strings to corresponding links.
  132. func RenderSpecialLink(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  133. ms := MentionPattern.FindAll(rawBytes, -1)
  134. for _, m := range ms {
  135. m = m[bytes.Index(m, []byte("@")):]
  136. rawBytes = bytes.Replace(rawBytes, m,
  137. []byte(fmt.Sprintf(`<a href="%s/%s">%s</a>`, setting.AppSubURL, m[1:], m)), -1)
  138. }
  139. rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix, metas)
  140. rawBytes = RenderCrossReferenceIssueIndexPattern(rawBytes, urlPrefix, metas)
  141. rawBytes = RenderSha1CurrentPattern(rawBytes, urlPrefix)
  142. return rawBytes
  143. }
  144. var (
  145. leftAngleBracket = []byte("</")
  146. rightAngleBracket = []byte(">")
  147. )
  148. var noEndTags = []string{"input", "br", "hr", "img"}
  149. // wrapImgWithLink warps link to standalone <img> tags.
  150. func wrapImgWithLink(urlPrefix string, buf *bytes.Buffer, token html.Token) {
  151. // Extract "src" and "alt" attributes
  152. var src, alt string
  153. for i := range token.Attr {
  154. switch token.Attr[i].Key {
  155. case "src":
  156. src = token.Attr[i].Val
  157. case "alt":
  158. alt = token.Attr[i].Val
  159. }
  160. }
  161. // Skip in case the "src" is empty
  162. if len(src) == 0 {
  163. buf.WriteString(token.String())
  164. return
  165. }
  166. // Prepend repository base URL for internal links
  167. needPrepend := !isLink([]byte(src))
  168. if needPrepend {
  169. urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
  170. if src[0] != '/' {
  171. urlPrefix += "/"
  172. }
  173. }
  174. buf.WriteString(`<a href="`)
  175. if needPrepend {
  176. buf.WriteString(urlPrefix)
  177. buf.WriteString(src)
  178. } else {
  179. buf.WriteString(src)
  180. }
  181. buf.WriteString(`">`)
  182. if needPrepend {
  183. src = strings.Replace(urlPrefix+string(src), " ", "%20", -1)
  184. buf.WriteString(`<img src="`)
  185. buf.WriteString(src)
  186. buf.WriteString(`"`)
  187. if len(alt) > 0 {
  188. buf.WriteString(` alt="`)
  189. buf.WriteString(alt)
  190. buf.WriteString(`"`)
  191. }
  192. buf.WriteString(`>`)
  193. } else {
  194. buf.WriteString(token.String())
  195. }
  196. buf.WriteString(`</a>`)
  197. }
  198. // postProcessHTML treats different types of HTML differently,
  199. // and only renders special links for plain text blocks.
  200. func postProcessHTML(rawHTML []byte, urlPrefix string, metas map[string]string) []byte {
  201. startTags := make([]string, 0, 5)
  202. buf := bytes.NewBuffer(nil)
  203. tokenizer := html.NewTokenizer(bytes.NewReader(rawHTML))
  204. OUTER_LOOP:
  205. for html.ErrorToken != tokenizer.Next() {
  206. token := tokenizer.Token()
  207. switch token.Type {
  208. case html.TextToken:
  209. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix, metas))
  210. case html.StartTagToken:
  211. tagName := token.Data
  212. if tagName == "img" {
  213. wrapImgWithLink(urlPrefix, buf, token)
  214. continue OUTER_LOOP
  215. }
  216. buf.WriteString(token.String())
  217. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  218. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  219. stackNum := 1
  220. for html.ErrorToken != tokenizer.Next() {
  221. token = tokenizer.Token()
  222. // Copy the token to the output verbatim
  223. buf.WriteString(token.String())
  224. // Stack number doesn't increate for tags without end tags.
  225. if token.Type == html.StartTagToken && !com.IsSliceContainsStr(noEndTags, token.Data) {
  226. stackNum++
  227. }
  228. // If this is the close tag to the outer-most, we are done
  229. if token.Type == html.EndTagToken {
  230. stackNum--
  231. if stackNum <= 0 && strings.EqualFold(tagName, token.Data) {
  232. break
  233. }
  234. }
  235. }
  236. continue OUTER_LOOP
  237. }
  238. if !com.IsSliceContainsStr(noEndTags, tagName) {
  239. startTags = append(startTags, tagName)
  240. }
  241. case html.EndTagToken:
  242. if len(startTags) == 0 {
  243. buf.WriteString(token.String())
  244. break
  245. }
  246. buf.Write(leftAngleBracket)
  247. buf.WriteString(startTags[len(startTags)-1])
  248. buf.Write(rightAngleBracket)
  249. startTags = startTags[:len(startTags)-1]
  250. default:
  251. buf.WriteString(token.String())
  252. }
  253. }
  254. if io.EOF == tokenizer.Err() {
  255. return buf.Bytes()
  256. }
  257. // If we are not at the end of the input, then some other parsing error has occurred,
  258. // so return the input verbatim.
  259. return rawHTML
  260. }
  261. type Type string
  262. const (
  263. UNRECOGNIZED Type = "unrecognized"
  264. MARKDOWN Type = "markdown"
  265. ORG_MODE Type = "orgmode"
  266. IPYTHON_NOTEBOOK Type = "ipynb"
  267. )
  268. // Detect returns best guess of a markup type based on file name.
  269. func Detect(filename string) Type {
  270. switch {
  271. case IsMarkdownFile(filename):
  272. return MARKDOWN
  273. case IsOrgModeFile(filename):
  274. return ORG_MODE
  275. case IsIPythonNotebook(filename):
  276. return IPYTHON_NOTEBOOK
  277. default:
  278. return UNRECOGNIZED
  279. }
  280. }
  281. // Render takes a string or []byte and renders to HTML in given type of syntax with special links.
  282. func Render(typ Type, input interface{}, urlPrefix string, metas map[string]string) []byte {
  283. var rawBytes []byte
  284. switch v := input.(type) {
  285. case []byte:
  286. rawBytes = v
  287. case string:
  288. rawBytes = []byte(v)
  289. default:
  290. panic(fmt.Sprintf("unrecognized input content type: %T", input))
  291. }
  292. urlPrefix = strings.TrimRight(strings.Replace(urlPrefix, " ", "%20", -1), "/")
  293. var rawHTML []byte
  294. switch typ {
  295. case MARKDOWN:
  296. rawHTML = RawMarkdown(rawBytes, urlPrefix)
  297. case ORG_MODE:
  298. rawHTML = RawOrgMode(rawBytes, urlPrefix)
  299. default:
  300. return rawBytes // Do nothing if syntax type is not recognized
  301. }
  302. rawHTML = postProcessHTML(rawHTML, urlPrefix, metas)
  303. return SanitizeBytes(rawHTML)
  304. }