markup.go 10 KB

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