markup.go 10 KB

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