markdown.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. // Copyright 2014 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 base
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "path"
  11. "path/filepath"
  12. "regexp"
  13. "strings"
  14. "github.com/Unknwon/com"
  15. "github.com/russross/blackfriday"
  16. "golang.org/x/net/html"
  17. "github.com/gogits/gogs/modules/setting"
  18. )
  19. func isletter(c byte) bool {
  20. return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
  21. }
  22. func isalnum(c byte) bool {
  23. return (c >= '0' && c <= '9') || isletter(c)
  24. }
  25. var validLinks = [][]byte{[]byte("http://"), []byte("https://"), []byte("ftp://"), []byte("mailto://")}
  26. func isLink(link []byte) bool {
  27. for _, prefix := range validLinks {
  28. if len(link) > len(prefix) && bytes.Equal(bytes.ToLower(link[:len(prefix)]), prefix) && isalnum(link[len(prefix)]) {
  29. return true
  30. }
  31. }
  32. return false
  33. }
  34. func IsMarkdownFile(name string) bool {
  35. name = strings.ToLower(name)
  36. switch filepath.Ext(name) {
  37. case ".md", ".markdown", ".mdown", ".mkd":
  38. return true
  39. }
  40. return false
  41. }
  42. func IsTextFile(data []byte) (string, bool) {
  43. contentType := http.DetectContentType(data)
  44. if strings.Index(contentType, "text/") != -1 {
  45. return contentType, true
  46. }
  47. return contentType, false
  48. }
  49. func IsImageFile(data []byte) (string, bool) {
  50. contentType := http.DetectContentType(data)
  51. if strings.Index(contentType, "image/") != -1 {
  52. return contentType, true
  53. }
  54. return contentType, false
  55. }
  56. // IsReadmeFile returns true if given file name suppose to be a README file.
  57. func IsReadmeFile(name string) bool {
  58. name = strings.ToLower(name)
  59. if len(name) < 6 {
  60. return false
  61. } else if len(name) == 6 {
  62. if name == "readme" {
  63. return true
  64. }
  65. return false
  66. }
  67. if name[:7] == "readme." {
  68. return true
  69. }
  70. return false
  71. }
  72. var (
  73. MentionPattern = regexp.MustCompile(`(\s|^)@[0-9a-zA-Z_\.]+`)
  74. commitPattern = regexp.MustCompile(`(\s|^)https?.*commit/[0-9a-zA-Z]+(#+[0-9a-zA-Z-]*)?`)
  75. issueFullPattern = regexp.MustCompile(`(\s|^)https?.*issues/[0-9]+(#+[0-9a-zA-Z-]*)?`)
  76. issueIndexPattern = regexp.MustCompile(`( |^|\()#[0-9]+\b`)
  77. sha1CurrentPattern = regexp.MustCompile(`\b[0-9a-f]{40}\b`)
  78. )
  79. type CustomRender struct {
  80. blackfriday.Renderer
  81. urlPrefix string
  82. }
  83. func (r *CustomRender) Link(out *bytes.Buffer, link []byte, title []byte, content []byte) {
  84. if len(link) > 0 && !isLink(link) {
  85. if link[0] == '#' {
  86. // link = append([]byte(options.urlPrefix), link...)
  87. } else {
  88. link = []byte(path.Join(r.urlPrefix, string(link)))
  89. }
  90. }
  91. r.Renderer.Link(out, link, title, content)
  92. }
  93. func (r *CustomRender) AutoLink(out *bytes.Buffer, link []byte, kind int) {
  94. if kind != 1 {
  95. r.Renderer.AutoLink(out, link, kind)
  96. return
  97. }
  98. // This method could only possibly serve one link at a time, no need to find all.
  99. m := commitPattern.Find(link)
  100. if m != nil {
  101. m = bytes.TrimSpace(m)
  102. i := strings.Index(string(m), "commit/")
  103. j := strings.Index(string(m), "#")
  104. if j == -1 {
  105. j = len(m)
  106. }
  107. out.WriteString(fmt.Sprintf(` <code><a href="%s">%s</a></code>`, m, ShortSha(string(m[i+7:j]))))
  108. return
  109. }
  110. m = issueFullPattern.Find(link)
  111. if m != nil {
  112. m = bytes.TrimSpace(m)
  113. i := strings.Index(string(m), "issues/")
  114. j := strings.Index(string(m), "#")
  115. if j == -1 {
  116. j = len(m)
  117. }
  118. out.WriteString(fmt.Sprintf(` <a href="%s">#%s</a>`, m, ShortSha(string(m[i+7:j]))))
  119. return
  120. }
  121. r.Renderer.AutoLink(out, link, kind)
  122. }
  123. var (
  124. svgSuffix = []byte(".svg")
  125. svgSuffixWithMark = []byte(".svg?")
  126. )
  127. func (r *CustomRender) Image(out *bytes.Buffer, link []byte, title []byte, alt []byte) {
  128. prefix := strings.Replace(r.urlPrefix, "/src/", "/raw/", 1)
  129. if len(link) > 0 {
  130. if isLink(link) {
  131. // External link with .svg suffix usually means CI status.
  132. if bytes.HasSuffix(link, svgSuffix) || bytes.Contains(link, svgSuffixWithMark) {
  133. r.Renderer.Image(out, link, title, alt)
  134. return
  135. }
  136. } else {
  137. if link[0] != '/' {
  138. prefix += "/"
  139. }
  140. link = []byte(prefix + string(link))
  141. }
  142. }
  143. out.WriteString(`<a href="`)
  144. out.Write(link)
  145. out.WriteString(`">`)
  146. r.Renderer.Image(out, link, title, alt)
  147. out.WriteString("</a>")
  148. }
  149. func cutoutVerbosePrefix(prefix string) string {
  150. count := 0
  151. for i := 0; i < len(prefix); i++ {
  152. if prefix[i] == '/' {
  153. count++
  154. }
  155. if count >= 3 {
  156. return prefix[:i]
  157. }
  158. }
  159. return prefix
  160. }
  161. func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  162. urlPrefix = cutoutVerbosePrefix(urlPrefix)
  163. ms := issueIndexPattern.FindAll(rawBytes, -1)
  164. for _, m := range ms {
  165. var space string
  166. m2 := m
  167. if m2[0] != '#' {
  168. space = string(m2[0])
  169. m2 = m2[1:]
  170. }
  171. if metas == nil {
  172. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(`%s<a href="%s/issues/%s">%s</a>`,
  173. space, urlPrefix, m2[1:], m2)), 1)
  174. } else {
  175. // Support for external issue tracker
  176. metas["index"] = string(m2[1:])
  177. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(`%s<a href="%s">%s</a>`,
  178. space, com.Expand(metas["format"], metas), m2)), 1)
  179. }
  180. }
  181. return rawBytes
  182. }
  183. func RenderSpecialLink(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  184. ms := MentionPattern.FindAll(rawBytes, -1)
  185. for _, m := range ms {
  186. m = bytes.TrimSpace(m)
  187. rawBytes = bytes.Replace(rawBytes, m,
  188. []byte(fmt.Sprintf(`<a href="%s/%s">%s</a>`, setting.AppSubUrl, m[1:], m)), -1)
  189. }
  190. rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix, metas)
  191. rawBytes = RenderSha1CurrentPattern(rawBytes, urlPrefix)
  192. return rawBytes
  193. }
  194. func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
  195. ms := sha1CurrentPattern.FindAll(rawBytes, -1)
  196. for _, m := range ms {
  197. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
  198. `<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, ShortSha(string(m)))), -1)
  199. }
  200. return rawBytes
  201. }
  202. func RenderRawMarkdown(body []byte, urlPrefix string) []byte {
  203. htmlFlags := 0
  204. htmlFlags |= blackfriday.HTML_SKIP_STYLE
  205. htmlFlags |= blackfriday.HTML_OMIT_CONTENTS
  206. renderer := &CustomRender{
  207. Renderer: blackfriday.HtmlRenderer(htmlFlags, "", ""),
  208. urlPrefix: urlPrefix,
  209. }
  210. // set up the parser
  211. extensions := 0
  212. extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
  213. extensions |= blackfriday.EXTENSION_TABLES
  214. extensions |= blackfriday.EXTENSION_FENCED_CODE
  215. extensions |= blackfriday.EXTENSION_AUTOLINK
  216. extensions |= blackfriday.EXTENSION_STRIKETHROUGH
  217. extensions |= blackfriday.EXTENSION_SPACE_HEADERS
  218. extensions |= blackfriday.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK
  219. if setting.Markdown.EnableHardLineBreak {
  220. extensions |= blackfriday.EXTENSION_HARD_LINE_BREAK
  221. }
  222. body = blackfriday.Markdown(body, renderer, extensions)
  223. return body
  224. }
  225. var (
  226. leftAngleBracket = []byte("</")
  227. rightAngleBracket = []byte(">")
  228. )
  229. var noEndTags = []string{"img", "input", "br", "hr"}
  230. // PostProcessMarkdown treats different types of HTML differently,
  231. // and only renders special links for plain text blocks.
  232. func PostProcessMarkdown(rawHtml []byte, urlPrefix string, metas map[string]string) []byte {
  233. startTags := make([]string, 0, 5)
  234. var buf bytes.Buffer
  235. tokenizer := html.NewTokenizer(bytes.NewReader(rawHtml))
  236. OUTER_LOOP:
  237. for html.ErrorToken != tokenizer.Next() {
  238. token := tokenizer.Token()
  239. switch token.Type {
  240. case html.TextToken:
  241. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix, metas))
  242. case html.StartTagToken:
  243. buf.WriteString(token.String())
  244. tagName := token.Data
  245. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  246. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  247. stackNum := 1
  248. for html.ErrorToken != tokenizer.Next() {
  249. token = tokenizer.Token()
  250. // Copy the token to the output verbatim
  251. buf.WriteString(token.String())
  252. if token.Type == html.StartTagToken {
  253. stackNum++
  254. }
  255. // If this is the close tag to the outer-most, we are done
  256. if token.Type == html.EndTagToken && strings.EqualFold(tagName, token.Data) {
  257. stackNum--
  258. if stackNum == 0 {
  259. break
  260. }
  261. }
  262. }
  263. continue OUTER_LOOP
  264. }
  265. if !com.IsSliceContainsStr(noEndTags, token.Data) {
  266. startTags = append(startTags, token.Data)
  267. }
  268. case html.EndTagToken:
  269. if len(startTags) == 0 {
  270. buf.WriteString(token.String())
  271. break
  272. }
  273. buf.Write(leftAngleBracket)
  274. buf.WriteString(startTags[len(startTags)-1])
  275. buf.Write(rightAngleBracket)
  276. startTags = startTags[:len(startTags)-1]
  277. default:
  278. buf.WriteString(token.String())
  279. }
  280. }
  281. if io.EOF == tokenizer.Err() {
  282. return buf.Bytes()
  283. }
  284. // If we are not at the end of the input, then some other parsing error has occurred,
  285. // so return the input verbatim.
  286. return rawHtml
  287. }
  288. func RenderMarkdown(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  289. result := RenderRawMarkdown(rawBytes, urlPrefix)
  290. result = PostProcessMarkdown(result, urlPrefix, metas)
  291. result = Sanitizer.SanitizeBytes(result)
  292. return result
  293. }
  294. func RenderMarkdownString(raw, urlPrefix string, metas map[string]string) string {
  295. return string(RenderMarkdown([]byte(raw), urlPrefix, metas))
  296. }