markup.go 11 KB

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