123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362 |
- package markup
- import (
- "bytes"
- "fmt"
- "io"
- "regexp"
- "strings"
- "github.com/Unknwon/com"
- "golang.org/x/net/html"
- "github.com/gogs/gogs/pkg/setting"
- "github.com/gogs/gogs/pkg/tool"
- )
- func IsReadmeFile(name string) bool {
- return strings.HasPrefix(strings.ToLower(name), "readme")
- }
- func IsIPythonNotebook(name string) bool {
- return strings.HasSuffix(name, ".ipynb")
- }
- const (
- ISSUE_NAME_STYLE_NUMERIC = "numeric"
- ISSUE_NAME_STYLE_ALPHANUMERIC = "alphanumeric"
- )
- var (
-
- MentionPattern = regexp.MustCompile(`(\s|^|\W)@[0-9a-zA-Z-_\.]+`)
-
-
- CommitPattern = regexp.MustCompile(`(\s|^)https?.*commit/[0-9a-zA-Z]+(#+[0-9a-zA-Z-]*)?`)
-
-
- IssueFullPattern = regexp.MustCompile(`(\s|^)https?.*issues/[0-9]+(#+[0-9a-zA-Z-]*)?`)
-
- IssueNumericPattern = regexp.MustCompile(`( |^|\(|\[)#[0-9]+\b`)
-
- IssueAlphanumericPattern = regexp.MustCompile(`( |^|\(|\[)[A-Z]{1,10}-[1-9][0-9]*\b`)
-
-
- CrossReferenceIssueNumericPattern = regexp.MustCompile(`( |^)[0-9a-zA-Z-_\.]+/[0-9a-zA-Z-_\.]+#[0-9]+\b`)
-
-
- Sha1CurrentPattern = regexp.MustCompile(`\b[0-9a-f]{7,40}\b`)
- )
- func FindAllMentions(content string) []string {
- mentions := MentionPattern.FindAllString(content, -1)
- for i := range mentions {
- mentions[i] = mentions[i][strings.Index(mentions[i], "@")+1:]
- }
- return mentions
- }
- func cutoutVerbosePrefix(prefix string) string {
- if len(prefix) == 0 || prefix[0] != '/' {
- return prefix
- }
- count := 0
- for i := 0; i < len(prefix); i++ {
- if prefix[i] == '/' {
- count++
- }
- if count >= 3+setting.AppSubURLDepth {
- return prefix[:i]
- }
- }
- return prefix
- }
- func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
- urlPrefix = cutoutVerbosePrefix(urlPrefix)
- pattern := IssueNumericPattern
- if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC {
- pattern = IssueAlphanumericPattern
- }
- ms := pattern.FindAll(rawBytes, -1)
- for _, m := range ms {
- if m[0] == ' ' || m[0] == '(' || m[0] == '[' {
-
- m = m[1:]
- }
- var link string
- if metas == nil {
- link = fmt.Sprintf(`<a href="%s/issues/%s">%s</a>`, urlPrefix, m[1:], m)
- } else {
-
- if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC {
- metas["index"] = string(m)
- } else {
- metas["index"] = string(m[1:])
- }
- link = fmt.Sprintf(`<a href="%s">%s</a>`, com.Expand(metas["format"], metas), m)
- }
- rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
- }
- return rawBytes
- }
- var pound = []byte("#")
- func RenderCrossReferenceIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
- ms := CrossReferenceIssueNumericPattern.FindAll(rawBytes, -1)
- for _, m := range ms {
- if m[0] == ' ' || m[0] == '(' {
- m = m[1:]
- }
- delimIdx := bytes.Index(m, pound)
- repo := string(m[:delimIdx])
- index := string(m[delimIdx+1:])
- link := fmt.Sprintf(`<a href="%s%s/issues/%s">%s</a>`, setting.AppURL, repo, index, m)
- rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
- }
- return rawBytes
- }
- func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
- return []byte(Sha1CurrentPattern.ReplaceAllStringFunc(string(rawBytes[:]), func(m string) string {
- if com.StrTo(m).MustInt() > 0 {
- return m
- }
- return fmt.Sprintf(`<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, tool.ShortSHA1(string(m)))
- }))
- }
- func RenderSpecialLink(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
- ms := MentionPattern.FindAll(rawBytes, -1)
- for _, m := range ms {
- m = m[bytes.Index(m, []byte("@")):]
- rawBytes = bytes.Replace(rawBytes, m,
- []byte(fmt.Sprintf(`<a href="%s/%s">%s</a>`, setting.AppSubURL, m[1:], m)), -1)
- }
- rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix, metas)
- rawBytes = RenderCrossReferenceIssueIndexPattern(rawBytes, urlPrefix, metas)
- rawBytes = RenderSha1CurrentPattern(rawBytes, urlPrefix)
- return rawBytes
- }
- var (
- leftAngleBracket = []byte("</")
- rightAngleBracket = []byte(">")
- )
- var noEndTags = []string{"input", "br", "hr", "img"}
- func wrapImgWithLink(urlPrefix string, buf *bytes.Buffer, token html.Token) {
-
- var src, alt string
- for i := range token.Attr {
- switch token.Attr[i].Key {
- case "src":
- src = token.Attr[i].Val
- case "alt":
- alt = token.Attr[i].Val
- }
- }
-
- if len(src) == 0 {
- buf.WriteString(token.String())
- return
- }
-
- if strings.HasPrefix(src, "data:") {
- buf.WriteString(token.String())
- return
- }
-
- needPrepend := !isLink([]byte(src))
- if needPrepend {
- urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
- if src[0] != '/' {
- urlPrefix += "/"
- }
- }
- buf.WriteString(`<a href="`)
- if needPrepend {
- buf.WriteString(urlPrefix)
- buf.WriteString(src)
- } else {
- buf.WriteString(src)
- }
- buf.WriteString(`">`)
- if needPrepend {
- src = strings.Replace(urlPrefix+string(src), " ", "%20", -1)
- buf.WriteString(`<img src="`)
- buf.WriteString(src)
- buf.WriteString(`"`)
- if len(alt) > 0 {
- buf.WriteString(` alt="`)
- buf.WriteString(alt)
- buf.WriteString(`"`)
- }
- buf.WriteString(`>`)
- } else {
- buf.WriteString(token.String())
- }
- buf.WriteString(`</a>`)
- }
- func postProcessHTML(rawHTML []byte, urlPrefix string, metas map[string]string) []byte {
- startTags := make([]string, 0, 5)
- buf := bytes.NewBuffer(nil)
- tokenizer := html.NewTokenizer(bytes.NewReader(rawHTML))
- OUTER_LOOP:
- for html.ErrorToken != tokenizer.Next() {
- token := tokenizer.Token()
- switch token.Type {
- case html.TextToken:
- buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix, metas))
- case html.StartTagToken:
- tagName := token.Data
- if tagName == "img" {
- wrapImgWithLink(urlPrefix, buf, token)
- continue OUTER_LOOP
- }
- buf.WriteString(token.String())
-
- if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
- stackNum := 1
- for html.ErrorToken != tokenizer.Next() {
- token = tokenizer.Token()
-
- buf.WriteString(token.String())
-
- if token.Type == html.StartTagToken && !com.IsSliceContainsStr(noEndTags, token.Data) {
- stackNum++
- }
-
- if token.Type == html.EndTagToken {
- stackNum--
- if stackNum <= 0 && strings.EqualFold(tagName, token.Data) {
- break
- }
- }
- }
- continue OUTER_LOOP
- }
- if !com.IsSliceContainsStr(noEndTags, tagName) {
- startTags = append(startTags, tagName)
- }
- case html.EndTagToken:
- if len(startTags) == 0 {
- buf.WriteString(token.String())
- break
- }
- buf.Write(leftAngleBracket)
- buf.WriteString(startTags[len(startTags)-1])
- buf.Write(rightAngleBracket)
- startTags = startTags[:len(startTags)-1]
- default:
- buf.WriteString(token.String())
- }
- }
- if io.EOF == tokenizer.Err() {
- return buf.Bytes()
- }
-
-
- return rawHTML
- }
- type Type string
- const (
- UNRECOGNIZED Type = "unrecognized"
- MARKDOWN Type = "markdown"
- ORG_MODE Type = "orgmode"
- IPYTHON_NOTEBOOK Type = "ipynb"
- )
- func Detect(filename string) Type {
- switch {
- case IsMarkdownFile(filename):
- return MARKDOWN
- case IsOrgModeFile(filename):
- return ORG_MODE
- case IsIPythonNotebook(filename):
- return IPYTHON_NOTEBOOK
- default:
- return UNRECOGNIZED
- }
- }
- func Render(typ Type, input interface{}, urlPrefix string, metas map[string]string) []byte {
- var rawBytes []byte
- switch v := input.(type) {
- case []byte:
- rawBytes = v
- case string:
- rawBytes = []byte(v)
- default:
- panic(fmt.Sprintf("unrecognized input content type: %T", input))
- }
- urlPrefix = strings.TrimRight(strings.Replace(urlPrefix, " ", "%20", -1), "/")
- var rawHTML []byte
- switch typ {
- case MARKDOWN:
- rawHTML = RawMarkdown(rawBytes, urlPrefix)
- case ORG_MODE:
- rawHTML = RawOrgMode(rawBytes, urlPrefix)
- default:
- return rawBytes
- }
- rawHTML = postProcessHTML(rawHTML, urlPrefix, metas)
- return SanitizeBytes(rawHTML)
- }
|