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.

html.go 19 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. // Copyright 2017 The Gitea 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. "net/url"
  8. "path"
  9. "path/filepath"
  10. "regexp"
  11. "strings"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/modules/util"
  15. "github.com/Unknwon/com"
  16. "github.com/mvdan/xurls"
  17. "golang.org/x/net/html"
  18. "golang.org/x/net/html/atom"
  19. )
  20. // Issue name styles
  21. const (
  22. IssueNameStyleNumeric = "numeric"
  23. IssueNameStyleAlphanumeric = "alphanumeric"
  24. )
  25. var (
  26. // NOTE: All below regex matching do not perform any extra validation.
  27. // Thus a link is produced even if the linked entity does not exist.
  28. // While fast, this is also incorrect and lead to false positives.
  29. // TODO: fix invalid linking issue
  30. // mentionPattern matches all mentions in the form of "@user"
  31. mentionPattern = regexp.MustCompile(`(?:\s|^|\W)(@[0-9a-zA-Z-_\.]+)`)
  32. // issueNumericPattern matches string that references to a numeric issue, e.g. #1287
  33. issueNumericPattern = regexp.MustCompile(`(?:\s|^|\W)(#[0-9]+)\b`)
  34. // issueAlphanumericPattern matches string that references to an alphanumeric issue, e.g. ABC-1234
  35. issueAlphanumericPattern = regexp.MustCompile(`(?:\s|^|\W)([A-Z]{1,10}-[1-9][0-9]*)\b`)
  36. // crossReferenceIssueNumericPattern matches string that references a numeric issue in a different repository
  37. // e.g. gogits/gogs#12345
  38. crossReferenceIssueNumericPattern = regexp.MustCompile(`(?:\s|^|\W)([0-9a-zA-Z-_\.]+/[0-9a-zA-Z-_\.]+#[0-9]+)\b`)
  39. // sha1CurrentPattern matches string that represents a commit SHA, e.g. d8a994ef243349f321568f9e36d5c3f444b99cae
  40. // Although SHA1 hashes are 40 chars long, the regex matches the hash from 7 to 40 chars in length
  41. // so that abbreviated hash links can be used as well. This matches git and github useability.
  42. sha1CurrentPattern = regexp.MustCompile(`(?:\s|^|\W)([0-9a-f]{7,40})\b`)
  43. // shortLinkPattern matches short but difficult to parse [[name|link|arg=test]] syntax
  44. shortLinkPattern = regexp.MustCompile(`\[\[(.*?)\]\](\w*)`)
  45. // anySHA1Pattern allows to split url containing SHA into parts
  46. anySHA1Pattern = regexp.MustCompile(`https?://(?:\S+/){4}([0-9a-f]{40})/?([^#\s]+)?(?:#(\S+))?`)
  47. validLinksPattern = regexp.MustCompile(`^[a-z][\w-]+://`)
  48. // While this email regex is definitely not perfect and I'm sure you can come up
  49. // with edge cases, it is still accepted by the CommonMark specification, as
  50. // well as the HTML5 spec:
  51. // http://spec.commonmark.org/0.28/#email-address
  52. // https://html.spec.whatwg.org/multipage/input.html#e-mail-state-(type%3Demail)
  53. emailRegex = regexp.MustCompile("[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*")
  54. linkRegex, _ = xurls.StrictMatchingScheme("https?://")
  55. )
  56. // regexp for full links to issues/pulls
  57. var issueFullPattern *regexp.Regexp
  58. // IsLink reports whether link fits valid format.
  59. func IsLink(link []byte) bool {
  60. return isLink(link)
  61. }
  62. // isLink reports whether link fits valid format.
  63. func isLink(link []byte) bool {
  64. return validLinksPattern.Match(link)
  65. }
  66. func isLinkStr(link string) bool {
  67. return validLinksPattern.MatchString(link)
  68. }
  69. func getIssueFullPattern() *regexp.Regexp {
  70. if issueFullPattern == nil {
  71. appURL := setting.AppURL
  72. if len(appURL) > 0 && appURL[len(appURL)-1] != '/' {
  73. appURL += "/"
  74. }
  75. issueFullPattern = regexp.MustCompile(appURL +
  76. `\w+/\w+/(?:issues|pulls)/((?:\w{1,10}-)?[1-9][0-9]*)([\?|#]\S+.(\S+)?)?\b`)
  77. }
  78. return issueFullPattern
  79. }
  80. // FindAllMentions matches mention patterns in given content
  81. // and returns a list of found user names without @ prefix.
  82. func FindAllMentions(content string) []string {
  83. mentions := mentionPattern.FindAllStringSubmatch(content, -1)
  84. ret := make([]string, len(mentions))
  85. for i, val := range mentions {
  86. ret[i] = val[1][1:]
  87. }
  88. return ret
  89. }
  90. // cutoutVerbosePrefix cutouts URL prefix including sub-path to
  91. // return a clean unified string of request URL path.
  92. func cutoutVerbosePrefix(prefix string) string {
  93. if len(prefix) == 0 || prefix[0] != '/' {
  94. return prefix
  95. }
  96. count := 0
  97. for i := 0; i < len(prefix); i++ {
  98. if prefix[i] == '/' {
  99. count++
  100. }
  101. if count >= 3+setting.AppSubURLDepth {
  102. return prefix[:i]
  103. }
  104. }
  105. return prefix
  106. }
  107. // IsSameDomain checks if given url string has the same hostname as current Gitea instance
  108. func IsSameDomain(s string) bool {
  109. if strings.HasPrefix(s, "/") {
  110. return true
  111. }
  112. if uapp, err := url.Parse(setting.AppURL); err == nil {
  113. if u, err := url.Parse(s); err == nil {
  114. return u.Host == uapp.Host
  115. }
  116. return false
  117. }
  118. return false
  119. }
  120. type postProcessError struct {
  121. context string
  122. err error
  123. }
  124. func (p *postProcessError) Error() string {
  125. return "PostProcess: " + p.context + ", " + p.Error()
  126. }
  127. type processor func(ctx *postProcessCtx, node *html.Node)
  128. var defaultProcessors = []processor{
  129. mentionProcessor,
  130. shortLinkProcessor,
  131. fullIssuePatternProcessor,
  132. issueIndexPatternProcessor,
  133. crossReferenceIssueIndexPatternProcessor,
  134. fullSha1PatternProcessor,
  135. sha1CurrentPatternProcessor,
  136. emailAddressProcessor,
  137. linkProcessor,
  138. }
  139. type postProcessCtx struct {
  140. metas map[string]string
  141. urlPrefix string
  142. isWikiMarkdown bool
  143. // processors used by this context.
  144. procs []processor
  145. }
  146. // PostProcess does the final required transformations to the passed raw HTML
  147. // data, and ensures its validity. Transformations include: replacing links and
  148. // emails with HTML links, parsing shortlinks in the format of [[Link]], like
  149. // MediaWiki, linking issues in the format #ID, and mentions in the format
  150. // @user, and others.
  151. func PostProcess(
  152. rawHTML []byte,
  153. urlPrefix string,
  154. metas map[string]string,
  155. isWikiMarkdown bool,
  156. ) ([]byte, error) {
  157. // create the context from the parameters
  158. ctx := &postProcessCtx{
  159. metas: metas,
  160. urlPrefix: urlPrefix,
  161. isWikiMarkdown: isWikiMarkdown,
  162. procs: defaultProcessors,
  163. }
  164. return ctx.postProcess(rawHTML)
  165. }
  166. var commitMessageProcessors = []processor{
  167. mentionProcessor,
  168. fullIssuePatternProcessor,
  169. issueIndexPatternProcessor,
  170. crossReferenceIssueIndexPatternProcessor,
  171. fullSha1PatternProcessor,
  172. sha1CurrentPatternProcessor,
  173. emailAddressProcessor,
  174. linkProcessor,
  175. }
  176. // RenderCommitMessage will use the same logic as PostProcess, but will disable
  177. // the shortLinkProcessor and will add a defaultLinkProcessor if defaultLink is
  178. // set, which changes every text node into a link to the passed default link.
  179. func RenderCommitMessage(
  180. rawHTML []byte,
  181. urlPrefix, defaultLink string,
  182. metas map[string]string,
  183. ) ([]byte, error) {
  184. ctx := &postProcessCtx{
  185. metas: metas,
  186. urlPrefix: urlPrefix,
  187. procs: commitMessageProcessors,
  188. }
  189. if defaultLink != "" {
  190. // we don't have to fear data races, because being
  191. // commitMessageProcessors of fixed len and cap, every time we append
  192. // something to it the slice is realloc+copied, so append always
  193. // generates the slice ex-novo.
  194. ctx.procs = append(ctx.procs, genDefaultLinkProcessor(defaultLink))
  195. }
  196. return ctx.postProcess(rawHTML)
  197. }
  198. var byteBodyTag = []byte("<body>")
  199. var byteBodyTagClosing = []byte("</body>")
  200. func (ctx *postProcessCtx) postProcess(rawHTML []byte) ([]byte, error) {
  201. if ctx.procs == nil {
  202. ctx.procs = defaultProcessors
  203. }
  204. // give a generous extra 50 bytes
  205. res := make([]byte, 0, len(rawHTML)+50)
  206. res = append(res, byteBodyTag...)
  207. res = append(res, rawHTML...)
  208. res = append(res, byteBodyTagClosing...)
  209. // parse the HTML
  210. nodes, err := html.ParseFragment(bytes.NewReader(res), nil)
  211. if err != nil {
  212. return nil, &postProcessError{"invalid HTML", err}
  213. }
  214. for _, node := range nodes {
  215. ctx.visitNode(node)
  216. }
  217. // Create buffer in which the data will be placed again. We know that the
  218. // length will be at least that of res; to spare a few alloc+copy, we
  219. // reuse res, resetting its length to 0.
  220. buf := bytes.NewBuffer(res[:0])
  221. // Render everything to buf.
  222. for _, node := range nodes {
  223. err = html.Render(buf, node)
  224. if err != nil {
  225. return nil, &postProcessError{"error rendering processed HTML", err}
  226. }
  227. }
  228. // remove initial parts - because Render creates a whole HTML page.
  229. res = buf.Bytes()
  230. res = res[bytes.Index(res, byteBodyTag)+len(byteBodyTag) : bytes.LastIndex(res, byteBodyTagClosing)]
  231. // Everything done successfully, return parsed data.
  232. return res, nil
  233. }
  234. func (ctx *postProcessCtx) visitNode(node *html.Node) {
  235. // We ignore code, pre and already generated links.
  236. switch node.Type {
  237. case html.TextNode:
  238. ctx.textNode(node)
  239. case html.ElementNode:
  240. if node.Data == "a" || node.Data == "code" || node.Data == "pre" {
  241. return
  242. }
  243. for n := node.FirstChild; n != nil; n = n.NextSibling {
  244. ctx.visitNode(n)
  245. }
  246. }
  247. // ignore everything else
  248. }
  249. func (ctx *postProcessCtx) visitNodeForShortLinks(node *html.Node) {
  250. switch node.Type {
  251. case html.TextNode:
  252. shortLinkProcessorFull(ctx, node, true)
  253. case html.ElementNode:
  254. if node.Data == "code" || node.Data == "pre" || node.Data == "a" {
  255. return
  256. }
  257. for n := node.FirstChild; n != nil; n = n.NextSibling {
  258. ctx.visitNodeForShortLinks(n)
  259. }
  260. }
  261. }
  262. // textNode runs the passed node through various processors, in order to handle
  263. // all kinds of special links handled by the post-processing.
  264. func (ctx *postProcessCtx) textNode(node *html.Node) {
  265. for _, processor := range ctx.procs {
  266. processor(ctx, node)
  267. }
  268. }
  269. func createLink(href, content string) *html.Node {
  270. textNode := &html.Node{
  271. Type: html.TextNode,
  272. Data: content,
  273. }
  274. linkNode := &html.Node{
  275. FirstChild: textNode,
  276. LastChild: textNode,
  277. Type: html.ElementNode,
  278. Data: "a",
  279. DataAtom: atom.A,
  280. Attr: []html.Attribute{
  281. {Key: "href", Val: href},
  282. },
  283. }
  284. textNode.Parent = linkNode
  285. return linkNode
  286. }
  287. // replaceContent takes a text node, and in its content it replaces a section of
  288. // it with the specified newNode. An example to visualize how this can work can
  289. // be found here: https://play.golang.org/p/5zP8NnHZ03s
  290. func replaceContent(node *html.Node, i, j int, newNode *html.Node) {
  291. // get the data before and after the match
  292. before := node.Data[:i]
  293. after := node.Data[j:]
  294. // Replace in the current node the text, so that it is only what it is
  295. // supposed to have.
  296. node.Data = before
  297. // Get the current next sibling, before which we place the replaced data,
  298. // and after that we place the new text node.
  299. nextSibling := node.NextSibling
  300. node.Parent.InsertBefore(newNode, nextSibling)
  301. if after != "" {
  302. node.Parent.InsertBefore(&html.Node{
  303. Type: html.TextNode,
  304. Data: after,
  305. }, nextSibling)
  306. }
  307. }
  308. func mentionProcessor(_ *postProcessCtx, node *html.Node) {
  309. m := mentionPattern.FindStringSubmatchIndex(node.Data)
  310. if m == nil {
  311. return
  312. }
  313. // Replace the mention with a link to the specified user.
  314. mention := node.Data[m[2]:m[3]]
  315. replaceContent(node, m[2], m[3], createLink(util.URLJoin(setting.AppURL, mention[1:]), mention))
  316. }
  317. func shortLinkProcessor(ctx *postProcessCtx, node *html.Node) {
  318. shortLinkProcessorFull(ctx, node, false)
  319. }
  320. func shortLinkProcessorFull(ctx *postProcessCtx, node *html.Node, noLink bool) {
  321. m := shortLinkPattern.FindStringSubmatchIndex(node.Data)
  322. if m == nil {
  323. return
  324. }
  325. content := node.Data[m[2]:m[3]]
  326. tail := node.Data[m[4]:m[5]]
  327. props := make(map[string]string)
  328. // MediaWiki uses [[link|text]], while GitHub uses [[text|link]]
  329. // It makes page handling terrible, but we prefer GitHub syntax
  330. // And fall back to MediaWiki only when it is obvious from the look
  331. // Of text and link contents
  332. sl := strings.Split(content, "|")
  333. for _, v := range sl {
  334. if equalPos := strings.IndexByte(v, '='); equalPos == -1 {
  335. // There is no equal in this argument; this is a mandatory arg
  336. if props["name"] == "" {
  337. if isLinkStr(v) {
  338. // If we clearly see it is a link, we save it so
  339. // But first we need to ensure, that if both mandatory args provided
  340. // look like links, we stick to GitHub syntax
  341. if props["link"] != "" {
  342. props["name"] = props["link"]
  343. }
  344. props["link"] = strings.TrimSpace(v)
  345. } else {
  346. props["name"] = v
  347. }
  348. } else {
  349. props["link"] = strings.TrimSpace(v)
  350. }
  351. } else {
  352. // There is an equal; optional argument.
  353. sep := strings.IndexByte(v, '=')
  354. key, val := v[:sep], html.UnescapeString(v[sep+1:])
  355. // When parsing HTML, x/net/html will change all quotes which are
  356. // not used for syntax into UTF-8 quotes. So checking val[0] won't
  357. // be enough, since that only checks a single byte.
  358. if (strings.HasPrefix(val, "“") && strings.HasSuffix(val, "”")) ||
  359. (strings.HasPrefix(val, "‘") && strings.HasSuffix(val, "’")) {
  360. const lenQuote = len("‘")
  361. val = val[lenQuote : len(val)-lenQuote]
  362. }
  363. props[key] = val
  364. }
  365. }
  366. var name, link string
  367. if props["link"] != "" {
  368. link = props["link"]
  369. } else if props["name"] != "" {
  370. link = props["name"]
  371. }
  372. if props["title"] != "" {
  373. name = props["title"]
  374. } else if props["name"] != "" {
  375. name = props["name"]
  376. } else {
  377. name = link
  378. }
  379. name += tail
  380. image := false
  381. switch ext := filepath.Ext(string(link)); ext {
  382. // fast path: empty string, ignore
  383. case "":
  384. break
  385. case ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp", ".gif", ".bmp", ".ico", ".svg":
  386. image = true
  387. }
  388. childNode := &html.Node{}
  389. linkNode := &html.Node{
  390. FirstChild: childNode,
  391. LastChild: childNode,
  392. Type: html.ElementNode,
  393. Data: "a",
  394. DataAtom: atom.A,
  395. }
  396. childNode.Parent = linkNode
  397. absoluteLink := isLinkStr(link)
  398. if !absoluteLink {
  399. if image {
  400. link = strings.Replace(link, " ", "+", -1)
  401. } else {
  402. link = strings.Replace(link, " ", "-", -1)
  403. }
  404. if !strings.Contains(link, "/") {
  405. link = url.PathEscape(link)
  406. }
  407. }
  408. urlPrefix := ctx.urlPrefix
  409. if image {
  410. if !absoluteLink {
  411. if IsSameDomain(urlPrefix) {
  412. urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
  413. }
  414. if ctx.isWikiMarkdown {
  415. link = util.URLJoin("wiki", "raw", link)
  416. }
  417. link = util.URLJoin(urlPrefix, link)
  418. }
  419. title := props["title"]
  420. if title == "" {
  421. title = props["alt"]
  422. }
  423. if title == "" {
  424. title = path.Base(string(name))
  425. }
  426. alt := props["alt"]
  427. if alt == "" {
  428. alt = name
  429. }
  430. // make the childNode an image - if we can, we also place the alt
  431. childNode.Type = html.ElementNode
  432. childNode.Data = "img"
  433. childNode.DataAtom = atom.Img
  434. childNode.Attr = []html.Attribute{
  435. {Key: "src", Val: link},
  436. {Key: "title", Val: title},
  437. {Key: "alt", Val: alt},
  438. }
  439. if alt == "" {
  440. childNode.Attr = childNode.Attr[:2]
  441. }
  442. } else {
  443. if !absoluteLink {
  444. if ctx.isWikiMarkdown {
  445. link = util.URLJoin("wiki", link)
  446. }
  447. link = util.URLJoin(urlPrefix, link)
  448. }
  449. childNode.Type = html.TextNode
  450. childNode.Data = name
  451. }
  452. if noLink {
  453. linkNode = childNode
  454. } else {
  455. linkNode.Attr = []html.Attribute{{Key: "href", Val: link}}
  456. }
  457. replaceContent(node, m[0], m[1], linkNode)
  458. }
  459. func fullIssuePatternProcessor(ctx *postProcessCtx, node *html.Node) {
  460. m := getIssueFullPattern().FindStringSubmatchIndex(node.Data)
  461. if m == nil {
  462. return
  463. }
  464. link := node.Data[m[0]:m[1]]
  465. id := "#" + node.Data[m[2]:m[3]]
  466. // TODO if m[4]:m[5] is not nil, then link is to a comment,
  467. // and we should indicate that in the text somehow
  468. replaceContent(node, m[0], m[1], createLink(link, id))
  469. }
  470. func issueIndexPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  471. prefix := cutoutVerbosePrefix(ctx.urlPrefix)
  472. // default to numeric pattern, unless alphanumeric is requested.
  473. pattern := issueNumericPattern
  474. if ctx.metas["style"] == IssueNameStyleAlphanumeric {
  475. pattern = issueAlphanumericPattern
  476. }
  477. match := pattern.FindStringSubmatchIndex(node.Data)
  478. if match == nil {
  479. return
  480. }
  481. id := node.Data[match[2]:match[3]]
  482. var link *html.Node
  483. if ctx.metas == nil {
  484. link = createLink(util.URLJoin(prefix, "issues", id[1:]), id)
  485. } else {
  486. // Support for external issue tracker
  487. if ctx.metas["style"] == IssueNameStyleAlphanumeric {
  488. ctx.metas["index"] = id
  489. } else {
  490. ctx.metas["index"] = id[1:]
  491. }
  492. link = createLink(com.Expand(ctx.metas["format"], ctx.metas), id)
  493. }
  494. replaceContent(node, match[2], match[3], link)
  495. }
  496. func crossReferenceIssueIndexPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  497. m := crossReferenceIssueNumericPattern.FindStringSubmatchIndex(node.Data)
  498. if m == nil {
  499. return
  500. }
  501. ref := node.Data[m[2]:m[3]]
  502. parts := strings.SplitN(ref, "#", 2)
  503. repo, issue := parts[0], parts[1]
  504. replaceContent(node, m[2], m[3],
  505. createLink(util.URLJoin(setting.AppURL, repo, "issues", issue), ref))
  506. }
  507. // fullSha1PatternProcessor renders SHA containing URLs
  508. func fullSha1PatternProcessor(ctx *postProcessCtx, node *html.Node) {
  509. m := anySHA1Pattern.FindStringSubmatchIndex(node.Data)
  510. if m == nil {
  511. return
  512. }
  513. // take out what's relevant
  514. urlFull := node.Data[m[0]:m[1]]
  515. hash := node.Data[m[2]:m[3]]
  516. var subtree, line string
  517. // optional, we do them depending on the length.
  518. if m[7] > 0 {
  519. line = node.Data[m[6]:m[7]]
  520. }
  521. if m[5] > 0 {
  522. subtree = node.Data[m[4]:m[5]]
  523. }
  524. text := base.ShortSha(hash)
  525. if subtree != "" {
  526. text += "/" + subtree
  527. }
  528. if line != "" {
  529. text += " ("
  530. text += line
  531. text += ")"
  532. }
  533. replaceContent(node, m[0], m[1], createLink(urlFull, text))
  534. }
  535. // sha1CurrentPatternProcessor renders SHA1 strings to corresponding links that
  536. // are assumed to be in the same repository.
  537. func sha1CurrentPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  538. m := sha1CurrentPattern.FindStringSubmatchIndex(node.Data)
  539. if m == nil {
  540. return
  541. }
  542. hash := node.Data[m[2]:m[3]]
  543. // The regex does not lie, it matches the hash pattern.
  544. // However, a regex cannot know if a hash actually exists or not.
  545. // We could assume that a SHA1 hash should probably contain alphas AND numerics
  546. // but that is not always the case.
  547. // Although unlikely, deadbeef and 1234567 are valid short forms of SHA1 hash
  548. // as used by git and github for linking and thus we have to do similar.
  549. replaceContent(node, m[2], m[3],
  550. createLink(util.URLJoin(ctx.urlPrefix, "commit", hash), base.ShortSha(hash)))
  551. }
  552. // emailAddressProcessor replaces raw email addresses with a mailto: link.
  553. func emailAddressProcessor(ctx *postProcessCtx, node *html.Node) {
  554. m := emailRegex.FindStringIndex(node.Data)
  555. if m == nil {
  556. return
  557. }
  558. mail := node.Data[m[0]:m[1]]
  559. replaceContent(node, m[0], m[1], createLink("mailto:"+mail, mail))
  560. }
  561. // linkProcessor creates links for any HTTP or HTTPS URL not captured by
  562. // markdown.
  563. func linkProcessor(ctx *postProcessCtx, node *html.Node) {
  564. m := linkRegex.FindStringIndex(node.Data)
  565. if m == nil {
  566. return
  567. }
  568. uri := node.Data[m[0]:m[1]]
  569. replaceContent(node, m[0], m[1], createLink(uri, uri))
  570. }
  571. func genDefaultLinkProcessor(defaultLink string) processor {
  572. return func(ctx *postProcessCtx, node *html.Node) {
  573. ch := &html.Node{
  574. Parent: node,
  575. Type: html.TextNode,
  576. Data: node.Data,
  577. }
  578. node.Type = html.ElementNode
  579. node.Data = "a"
  580. node.DataAtom = atom.A
  581. node.Attr = []html.Attribute{{Key: "href", Val: defaultLink}}
  582. node.FirstChild, node.LastChild = ch, ch
  583. }
  584. }