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

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