You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

markdown.go 21 kB

11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
9 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  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 markdown
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "net/url"
  10. "path"
  11. "path/filepath"
  12. "regexp"
  13. "strings"
  14. "github.com/Unknwon/com"
  15. "github.com/microcosm-cc/bluemonday"
  16. "github.com/russross/blackfriday"
  17. "golang.org/x/net/html"
  18. "code.gitea.io/gitea/modules/base"
  19. "code.gitea.io/gitea/modules/setting"
  20. )
  21. // Issue name styles
  22. const (
  23. IssueNameStyleNumeric = "numeric"
  24. IssueNameStyleAlphanumeric = "alphanumeric"
  25. )
  26. // Sanitizer markdown sanitizer
  27. var Sanitizer = bluemonday.UGCPolicy()
  28. // BuildSanitizer initializes sanitizer with allowed attributes based on settings.
  29. // This function should only be called once during entire application lifecycle.
  30. func BuildSanitizer() {
  31. // Normal markdown-stuff
  32. Sanitizer.AllowAttrs("class").Matching(regexp.MustCompile(`[\p{L}\p{N}\s\-_',:\[\]!\./\\\(\)&]*`)).OnElements("code", "div", "ul", "ol", "dl")
  33. // Checkboxes
  34. Sanitizer.AllowAttrs("type").Matching(regexp.MustCompile(`^checkbox$`)).OnElements("input")
  35. Sanitizer.AllowAttrs("checked", "disabled").OnElements("input")
  36. Sanitizer.AllowNoAttrs().OnElements("label")
  37. // Custom URL-Schemes
  38. Sanitizer.AllowURLSchemes(setting.Markdown.CustomURLSchemes...)
  39. }
  40. // IsMarkdownFile reports whether name looks like a Markdown file
  41. // based on its extension.
  42. func IsMarkdownFile(name string) bool {
  43. extension := strings.ToLower(filepath.Ext(name))
  44. for _, ext := range setting.Markdown.FileExtensions {
  45. if strings.ToLower(ext) == extension {
  46. return true
  47. }
  48. }
  49. return false
  50. }
  51. // IsReadmeFile reports whether name looks like a README file
  52. // based on its name.
  53. func IsReadmeFile(name string) bool {
  54. name = strings.ToLower(name)
  55. if len(name) < 6 {
  56. return false
  57. } else if len(name) == 6 {
  58. return name == "readme"
  59. }
  60. return name[:7] == "readme."
  61. }
  62. var (
  63. // MentionPattern matches string that mentions someone, e.g. @Unknwon
  64. MentionPattern = regexp.MustCompile(`(\s|^|\W)@[0-9a-zA-Z-_\.]+`)
  65. // IssueNumericPattern matches string that references to a numeric issue, e.g. #1287
  66. IssueNumericPattern = regexp.MustCompile(`( |^|\()#[0-9]+\b`)
  67. // IssueAlphanumericPattern matches string that references to an alphanumeric issue, e.g. ABC-1234
  68. IssueAlphanumericPattern = regexp.MustCompile(`( |^|\()[A-Z]{1,10}-[1-9][0-9]*\b`)
  69. // CrossReferenceIssueNumericPattern matches string that references a numeric issue in a different repository
  70. // e.g. gogits/gogs#12345
  71. CrossReferenceIssueNumericPattern = regexp.MustCompile(`( |^)[0-9a-zA-Z]+/[0-9a-zA-Z]+#[0-9]+\b`)
  72. // Sha1CurrentPattern matches string that represents a commit SHA, e.g. d8a994ef243349f321568f9e36d5c3f444b99cae
  73. // FIXME: this pattern matches pure numbers as well, right now we do a hack to check in renderSha1CurrentPattern
  74. // by converting string to a number.
  75. Sha1CurrentPattern = regexp.MustCompile(`(?:^|\s|\()[0-9a-f]{40}\b`)
  76. // ShortLinkPattern matches short but difficult to parse [[name|link|arg=test]] syntax
  77. ShortLinkPattern = regexp.MustCompile(`(\[\[.*\]\]\w*)`)
  78. // AnySHA1Pattern allows to split url containing SHA into parts
  79. AnySHA1Pattern = regexp.MustCompile(`http\S+//(\S+)/(\S+)/(\S+)/(\S+)/([0-9a-f]{40})(?:/?([^#\s]+)?(?:#(\S+))?)?`)
  80. // IssueFullPattern allows to split issue (and pull) URLs into parts
  81. IssueFullPattern = regexp.MustCompile(`(?:^|\s|\()http\S+//((?:[^\s/]+/)+)((?:\w{1,10}-)?[1-9][0-9]*)([\?|#]\S+.(\S+)?)?\b`)
  82. validLinksPattern = regexp.MustCompile(`^[a-z][\w-]+://`)
  83. )
  84. // isLink reports whether link fits valid format.
  85. func isLink(link []byte) bool {
  86. return validLinksPattern.Match(link)
  87. }
  88. // FindAllMentions matches mention patterns in given content
  89. // and returns a list of found user names without @ prefix.
  90. func FindAllMentions(content string) []string {
  91. mentions := MentionPattern.FindAllString(content, -1)
  92. for i := range mentions {
  93. mentions[i] = mentions[i][strings.Index(mentions[i], "@")+1:] // Strip @ character
  94. }
  95. return mentions
  96. }
  97. // Renderer is a extended version of underlying render object.
  98. type Renderer struct {
  99. blackfriday.Renderer
  100. urlPrefix string
  101. isWikiMarkdown bool
  102. }
  103. // Link defines how formal links should be processed to produce corresponding HTML elements.
  104. func (r *Renderer) Link(out *bytes.Buffer, link []byte, title []byte, content []byte) {
  105. if len(link) > 0 && !isLink(link) {
  106. if link[0] != '#' {
  107. mLink := URLJoin(r.urlPrefix, string(link))
  108. if r.isWikiMarkdown {
  109. mLink = URLJoin(r.urlPrefix, "wiki", string(link))
  110. }
  111. link = []byte(mLink)
  112. }
  113. }
  114. r.Renderer.Link(out, link, title, content)
  115. }
  116. // List renders markdown bullet or digit lists to HTML
  117. func (r *Renderer) List(out *bytes.Buffer, text func() bool, flags int) {
  118. marker := out.Len()
  119. if out.Len() > 0 {
  120. out.WriteByte('\n')
  121. }
  122. if flags&blackfriday.LIST_TYPE_DEFINITION != 0 {
  123. out.WriteString("<dl>")
  124. } else if flags&blackfriday.LIST_TYPE_ORDERED != 0 {
  125. out.WriteString("<ol class='ui list'>")
  126. } else {
  127. out.WriteString("<ul class='ui list'>")
  128. }
  129. if !text() {
  130. out.Truncate(marker)
  131. return
  132. }
  133. if flags&blackfriday.LIST_TYPE_DEFINITION != 0 {
  134. out.WriteString("</dl>\n")
  135. } else if flags&blackfriday.LIST_TYPE_ORDERED != 0 {
  136. out.WriteString("</ol>\n")
  137. } else {
  138. out.WriteString("</ul>\n")
  139. }
  140. }
  141. // ListItem defines how list items should be processed to produce corresponding HTML elements.
  142. func (r *Renderer) ListItem(out *bytes.Buffer, text []byte, flags int) {
  143. // Detect procedures to draw checkboxes.
  144. prefix := ""
  145. if bytes.HasPrefix(text, []byte("<p>")) {
  146. prefix = "<p>"
  147. }
  148. switch {
  149. case bytes.HasPrefix(text, []byte(prefix+"[ ] ")):
  150. text = append([]byte(`<div class="ui fitted disabled checkbox"><input type="checkbox" disabled="disabled" /><label /></div>`), text[3+len(prefix):]...)
  151. case bytes.HasPrefix(text, []byte(prefix+"[x] ")):
  152. text = append([]byte(`<div class="ui checked fitted disabled checkbox"><input type="checkbox" checked="" disabled="disabled" /><label /></div>`), text[3+len(prefix):]...)
  153. }
  154. if prefix != "" {
  155. text = bytes.Replace(text, []byte("</p>"), []byte{}, 1)
  156. }
  157. r.Renderer.ListItem(out, text, flags)
  158. }
  159. // Note: this section is for purpose of increase performance and
  160. // reduce memory allocation at runtime since they are constant literals.
  161. var (
  162. svgSuffix = []byte(".svg")
  163. svgSuffixWithMark = []byte(".svg?")
  164. )
  165. // Image defines how images should be processed to produce corresponding HTML elements.
  166. func (r *Renderer) Image(out *bytes.Buffer, link []byte, title []byte, alt []byte) {
  167. prefix := r.urlPrefix
  168. if r.isWikiMarkdown {
  169. prefix = URLJoin(prefix, "wiki", "src")
  170. }
  171. prefix = strings.Replace(prefix, "/src/", "/raw/", 1)
  172. if len(link) > 0 {
  173. if isLink(link) {
  174. // External link with .svg suffix usually means CI status.
  175. // TODO: define a keyword to allow non-svg images render as external link.
  176. if bytes.HasSuffix(link, svgSuffix) || bytes.Contains(link, svgSuffixWithMark) {
  177. r.Renderer.Image(out, link, title, alt)
  178. return
  179. }
  180. } else {
  181. if link[0] != '/' {
  182. if !strings.HasSuffix(prefix, "/") {
  183. prefix += "/"
  184. }
  185. }
  186. link = []byte(url.QueryEscape(prefix + string(link)))
  187. }
  188. }
  189. out.WriteString(`<a href="`)
  190. out.Write(link)
  191. out.WriteString(`">`)
  192. r.Renderer.Image(out, link, title, alt)
  193. out.WriteString("</a>")
  194. }
  195. // cutoutVerbosePrefix cutouts URL prefix including sub-path to
  196. // return a clean unified string of request URL path.
  197. func cutoutVerbosePrefix(prefix string) string {
  198. if len(prefix) == 0 || prefix[0] != '/' {
  199. return prefix
  200. }
  201. count := 0
  202. for i := 0; i < len(prefix); i++ {
  203. if prefix[i] == '/' {
  204. count++
  205. }
  206. if count >= 3+setting.AppSubURLDepth {
  207. return prefix[:i]
  208. }
  209. }
  210. return prefix
  211. }
  212. // URLJoin joins url components, like path.Join, but preserving contents
  213. func URLJoin(elem ...string) string {
  214. res := ""
  215. last := len(elem) - 1
  216. for i, item := range elem {
  217. res += item
  218. if !strings.HasSuffix(res, "/") && i != last {
  219. res += "/"
  220. }
  221. }
  222. return res
  223. }
  224. // RenderIssueIndexPattern renders issue indexes to corresponding links.
  225. func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  226. urlPrefix = cutoutVerbosePrefix(urlPrefix)
  227. pattern := IssueNumericPattern
  228. if metas["style"] == IssueNameStyleAlphanumeric {
  229. pattern = IssueAlphanumericPattern
  230. }
  231. ms := pattern.FindAll(rawBytes, -1)
  232. for _, m := range ms {
  233. if m[0] == ' ' || m[0] == '(' {
  234. m = m[1:] // ignore leading space or opening parentheses
  235. }
  236. var link string
  237. if metas == nil {
  238. link = fmt.Sprintf(`<a href="%s">%s</a>`, URLJoin(urlPrefix, "issues", string(m[1:])), m)
  239. } else {
  240. // Support for external issue tracker
  241. if metas["style"] == IssueNameStyleAlphanumeric {
  242. metas["index"] = string(m)
  243. } else {
  244. metas["index"] = string(m[1:])
  245. }
  246. link = fmt.Sprintf(`<a href="%s">%s</a>`, com.Expand(metas["format"], metas), m)
  247. }
  248. rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
  249. }
  250. return rawBytes
  251. }
  252. // IsSameDomain checks if given url string has the same hostname as current Gitea instance
  253. func IsSameDomain(s string) bool {
  254. if uapp, err := url.Parse(setting.AppURL); err == nil {
  255. if u, err := url.Parse(s); err == nil {
  256. return u.Host == uapp.Host
  257. }
  258. return false
  259. }
  260. return false
  261. }
  262. // renderFullSha1Pattern renders SHA containing URLs
  263. func renderFullSha1Pattern(rawBytes []byte, urlPrefix string) []byte {
  264. ms := AnySHA1Pattern.FindAllSubmatch(rawBytes, -1)
  265. for _, m := range ms {
  266. all := m[0]
  267. paths := string(m[1])
  268. var path = "//" + paths
  269. author := string(m[2])
  270. repoName := string(m[3])
  271. path = URLJoin(path, author, repoName)
  272. ltype := "src"
  273. itemType := m[4]
  274. if IsSameDomain(paths) {
  275. ltype = string(itemType)
  276. } else if string(itemType) == "commit" {
  277. ltype = "commit"
  278. }
  279. sha := m[5]
  280. var subtree string
  281. if len(m) > 6 && len(m[6]) > 0 {
  282. subtree = string(m[6])
  283. }
  284. var line []byte
  285. if len(m) > 7 && len(m[7]) > 0 {
  286. line = m[7]
  287. }
  288. urlSuffix := ""
  289. text := base.ShortSha(string(sha))
  290. if subtree != "" {
  291. urlSuffix = "/" + subtree
  292. text += urlSuffix
  293. }
  294. if line != nil {
  295. value := string(line)
  296. urlSuffix += "#"
  297. urlSuffix += value
  298. text += " ("
  299. text += value
  300. text += ")"
  301. }
  302. rawBytes = bytes.Replace(rawBytes, all, []byte(fmt.Sprintf(
  303. `<a href="%s">%s</a>`, URLJoin(path, ltype, string(sha))+urlSuffix, text)), -1)
  304. }
  305. return rawBytes
  306. }
  307. // renderFullIssuePattern renders issues-like URLs
  308. func renderFullIssuePattern(rawBytes []byte, urlPrefix string) []byte {
  309. ms := IssueFullPattern.FindAllSubmatch(rawBytes, -1)
  310. for _, m := range ms {
  311. all := m[0]
  312. paths := bytes.Split(m[1], []byte("/"))
  313. paths = paths[:len(paths)-1]
  314. if bytes.HasPrefix(paths[0], []byte("gist.")) {
  315. continue
  316. }
  317. var path string
  318. if len(paths) > 3 {
  319. // Internal one
  320. path = URLJoin(urlPrefix, "issues")
  321. } else {
  322. path = "//" + string(m[1])
  323. }
  324. id := string(m[2])
  325. path = URLJoin(path, id)
  326. var comment []byte
  327. if len(m) > 3 {
  328. comment = m[3]
  329. }
  330. urlSuffix := ""
  331. text := "#" + id
  332. if comment != nil {
  333. urlSuffix += string(comment)
  334. text += " <i class='comment icon'></i>"
  335. }
  336. rawBytes = bytes.Replace(rawBytes, all, []byte(fmt.Sprintf(
  337. `<a href="%s%s">%s</a>`, path, urlSuffix, text)), -1)
  338. }
  339. return rawBytes
  340. }
  341. func firstIndexOfByte(sl []byte, target byte) int {
  342. for i := 0; i < len(sl); i++ {
  343. if sl[i] == target {
  344. return i
  345. }
  346. }
  347. return -1
  348. }
  349. func lastIndexOfByte(sl []byte, target byte) int {
  350. for i := len(sl) - 1; i >= 0; i-- {
  351. if sl[i] == target {
  352. return i
  353. }
  354. }
  355. return -1
  356. }
  357. // renderShortLinks processes [[syntax]]
  358. func renderShortLinks(rawBytes []byte, urlPrefix string, noLink bool) []byte {
  359. ms := ShortLinkPattern.FindAll(rawBytes, -1)
  360. for _, m := range ms {
  361. orig := bytes.TrimSpace(m)
  362. m = orig[2:]
  363. tailPos := lastIndexOfByte(m, ']') + 1
  364. tail := []byte{}
  365. if tailPos < len(m) {
  366. tail = m[tailPos:]
  367. m = m[:tailPos-1]
  368. }
  369. m = m[:len(m)-2]
  370. props := map[string]string{}
  371. // MediaWiki uses [[link|text]], while GitHub uses [[text|link]]
  372. // It makes page handling terrible, but we prefer GitHub syntax
  373. // And fall back to MediaWiki only when it is obvious from the look
  374. // Of text and link contents
  375. sl := bytes.Split(m, []byte("|"))
  376. for _, v := range sl {
  377. switch bytes.Count(v, []byte("=")) {
  378. // Piped args without = sign, these are mandatory arguments
  379. case 0:
  380. {
  381. sv := string(v)
  382. if props["name"] == "" {
  383. if isLink(v) {
  384. // If we clearly see it is a link, we save it so
  385. // But first we need to ensure, that if both mandatory args provided
  386. // look like links, we stick to GitHub syntax
  387. if props["link"] != "" {
  388. props["name"] = props["link"]
  389. }
  390. props["link"] = strings.TrimSpace(sv)
  391. } else {
  392. props["name"] = sv
  393. }
  394. } else {
  395. props["link"] = strings.TrimSpace(sv)
  396. }
  397. }
  398. // Piped args with = sign, these are optional arguments
  399. case 1:
  400. {
  401. sep := firstIndexOfByte(v, '=')
  402. key, val := string(v[:sep]), html.UnescapeString(string(v[sep+1:]))
  403. lastCharIndex := len(val) - 1
  404. if (val[0] == '"' || val[0] == '\'') && (val[lastCharIndex] == '"' || val[lastCharIndex] == '\'') {
  405. val = val[1:lastCharIndex]
  406. }
  407. props[key] = val
  408. }
  409. }
  410. }
  411. var name string
  412. var link string
  413. if props["link"] != "" {
  414. link = props["link"]
  415. } else if props["name"] != "" {
  416. link = props["name"]
  417. }
  418. if props["title"] != "" {
  419. name = props["title"]
  420. } else if props["name"] != "" {
  421. name = props["name"]
  422. } else {
  423. name = link
  424. }
  425. name += string(tail)
  426. image := false
  427. ext := filepath.Ext(string(link))
  428. if ext != "" {
  429. switch ext {
  430. case ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp", ".gif", ".bmp", ".ico", ".svg":
  431. {
  432. image = true
  433. }
  434. }
  435. }
  436. absoluteLink := isLink([]byte(link))
  437. if !absoluteLink {
  438. link = url.QueryEscape(link)
  439. }
  440. if image {
  441. if !absoluteLink {
  442. link = URLJoin(urlPrefix, "wiki", "raw", link)
  443. }
  444. title := props["title"]
  445. if title == "" {
  446. title = props["alt"]
  447. }
  448. if title == "" {
  449. title = path.Base(string(name))
  450. }
  451. alt := props["alt"]
  452. if alt == "" {
  453. alt = name
  454. }
  455. if alt != "" {
  456. alt = `alt="` + alt + `"`
  457. }
  458. name = fmt.Sprintf(`<img src="%s" %s title="%s" />`, link, alt, title)
  459. } else if !absoluteLink {
  460. link = URLJoin(urlPrefix, "wiki", link)
  461. }
  462. if noLink {
  463. rawBytes = bytes.Replace(rawBytes, orig, []byte(name), -1)
  464. } else {
  465. rawBytes = bytes.Replace(rawBytes, orig,
  466. []byte(fmt.Sprintf(`<a href="%s">%s</a>`, link, name)), -1)
  467. }
  468. }
  469. return rawBytes
  470. }
  471. // RenderCrossReferenceIssueIndexPattern renders issue indexes from other repositories to corresponding links.
  472. func RenderCrossReferenceIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  473. ms := CrossReferenceIssueNumericPattern.FindAll(rawBytes, -1)
  474. for _, m := range ms {
  475. if m[0] == ' ' || m[0] == '(' {
  476. m = m[1:] // ignore leading space or opening parentheses
  477. }
  478. repo := string(bytes.Split(m, []byte("#"))[0])
  479. issue := string(bytes.Split(m, []byte("#"))[1])
  480. link := fmt.Sprintf(`<a href="%s">%s</a>`, URLJoin(urlPrefix, repo, "issues", issue), m)
  481. rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
  482. }
  483. return rawBytes
  484. }
  485. // renderSha1CurrentPattern renders SHA1 strings to corresponding links that assumes in the same repository.
  486. func renderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
  487. ms := Sha1CurrentPattern.FindAllSubmatch(rawBytes, -1)
  488. for _, m := range ms {
  489. all := m[0]
  490. if com.StrTo(all).MustInt() > 0 {
  491. continue
  492. }
  493. rawBytes = bytes.Replace(rawBytes, all, []byte(fmt.Sprintf(
  494. `<a href="%s">%s</a>`, URLJoin(urlPrefix, "commit", string(all)), base.ShortSha(string(all)))), -1)
  495. }
  496. return rawBytes
  497. }
  498. // RenderSpecialLink renders mentions, indexes and SHA1 strings to corresponding links.
  499. func RenderSpecialLink(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  500. ms := MentionPattern.FindAll(rawBytes, -1)
  501. for _, m := range ms {
  502. m = m[bytes.Index(m, []byte("@")):]
  503. rawBytes = bytes.Replace(rawBytes, m,
  504. []byte(fmt.Sprintf(`<a href="%s">%s</a>`, URLJoin(setting.AppURL, string(m[1:])), m)), -1)
  505. }
  506. rawBytes = renderShortLinks(rawBytes, urlPrefix, false)
  507. rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix, metas)
  508. rawBytes = RenderCrossReferenceIssueIndexPattern(rawBytes, urlPrefix, metas)
  509. rawBytes = renderFullSha1Pattern(rawBytes, urlPrefix)
  510. rawBytes = renderSha1CurrentPattern(rawBytes, urlPrefix)
  511. rawBytes = renderFullIssuePattern(rawBytes, urlPrefix)
  512. return rawBytes
  513. }
  514. // RenderRaw renders Markdown to HTML without handling special links.
  515. func RenderRaw(body []byte, urlPrefix string, wikiMarkdown bool) []byte {
  516. htmlFlags := 0
  517. htmlFlags |= blackfriday.HTML_SKIP_STYLE
  518. htmlFlags |= blackfriday.HTML_OMIT_CONTENTS
  519. renderer := &Renderer{
  520. Renderer: blackfriday.HtmlRenderer(htmlFlags, "", ""),
  521. urlPrefix: urlPrefix,
  522. isWikiMarkdown: wikiMarkdown,
  523. }
  524. // set up the parser
  525. extensions := 0
  526. extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
  527. extensions |= blackfriday.EXTENSION_TABLES
  528. extensions |= blackfriday.EXTENSION_FENCED_CODE
  529. extensions |= blackfriday.EXTENSION_STRIKETHROUGH
  530. extensions |= blackfriday.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK
  531. if setting.Markdown.EnableHardLineBreak {
  532. extensions |= blackfriday.EXTENSION_HARD_LINE_BREAK
  533. }
  534. body = blackfriday.Markdown(body, renderer, extensions)
  535. return body
  536. }
  537. var (
  538. leftAngleBracket = []byte("</")
  539. rightAngleBracket = []byte(">")
  540. )
  541. var noEndTags = []string{"img", "input", "br", "hr"}
  542. // PostProcess treats different types of HTML differently,
  543. // and only renders special links for plain text blocks.
  544. func PostProcess(rawHTML []byte, urlPrefix string, metas map[string]string) []byte {
  545. startTags := make([]string, 0, 5)
  546. var buf bytes.Buffer
  547. tokenizer := html.NewTokenizer(bytes.NewReader(rawHTML))
  548. OUTER_LOOP:
  549. for html.ErrorToken != tokenizer.Next() {
  550. token := tokenizer.Token()
  551. switch token.Type {
  552. case html.TextToken:
  553. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix, metas))
  554. case html.StartTagToken:
  555. buf.WriteString(token.String())
  556. tagName := token.Data
  557. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  558. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  559. stackNum := 1
  560. for html.ErrorToken != tokenizer.Next() {
  561. token = tokenizer.Token()
  562. // Copy the token to the output verbatim
  563. buf.Write(renderShortLinks([]byte(token.String()), urlPrefix, true))
  564. if token.Type == html.StartTagToken {
  565. if !com.IsSliceContainsStr(noEndTags, token.Data) {
  566. stackNum++
  567. }
  568. }
  569. // If this is the close tag to the outer-most, we are done
  570. if token.Type == html.EndTagToken {
  571. stackNum--
  572. if stackNum <= 0 && strings.EqualFold(tagName, token.Data) {
  573. break
  574. }
  575. }
  576. }
  577. continue OUTER_LOOP
  578. }
  579. if !com.IsSliceContainsStr(noEndTags, token.Data) {
  580. startTags = append(startTags, token.Data)
  581. }
  582. case html.EndTagToken:
  583. if len(startTags) == 0 {
  584. buf.WriteString(token.String())
  585. break
  586. }
  587. buf.Write(leftAngleBracket)
  588. buf.WriteString(startTags[len(startTags)-1])
  589. buf.Write(rightAngleBracket)
  590. startTags = startTags[:len(startTags)-1]
  591. default:
  592. buf.WriteString(token.String())
  593. }
  594. }
  595. if io.EOF == tokenizer.Err() {
  596. return buf.Bytes()
  597. }
  598. // If we are not at the end of the input, then some other parsing error has occurred,
  599. // so return the input verbatim.
  600. return rawHTML
  601. }
  602. // Render renders Markdown to HTML with all specific handling stuff.
  603. func render(rawBytes []byte, urlPrefix string, metas map[string]string, isWikiMarkdown bool) []byte {
  604. urlPrefix = strings.Replace(urlPrefix, " ", "%20", -1)
  605. result := RenderRaw(rawBytes, urlPrefix, isWikiMarkdown)
  606. result = PostProcess(result, urlPrefix, metas)
  607. result = Sanitizer.SanitizeBytes(result)
  608. return result
  609. }
  610. // Render renders Markdown to HTML with all specific handling stuff.
  611. func Render(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  612. return render(rawBytes, urlPrefix, metas, false)
  613. }
  614. // RenderString renders Markdown to HTML with special links and returns string type.
  615. func RenderString(raw, urlPrefix string, metas map[string]string) string {
  616. return string(render([]byte(raw), urlPrefix, metas, false))
  617. }
  618. // RenderWiki renders markdown wiki page to HTML and return HTML string
  619. func RenderWiki(rawBytes []byte, urlPrefix string, metas map[string]string) string {
  620. return string(render(rawBytes, urlPrefix, metas, true))
  621. }