summaryrefslogtreecommitdiffstats
path: root/modules/markup/markdown/markdown.go
blob: ff78d7ea3a8e44535d14b8732edf309e64b9a585 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
// Copyright 2014 The Gogs Authors. All rights reserved.
// Copyright 2018 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package markdown

import (
	"bytes"
	"io"
	"strings"

	"code.gitea.io/gitea/modules/markup"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/util"

	"github.com/russross/blackfriday/v2"
)

// Renderer is a extended version of underlying render object.
type Renderer struct {
	blackfriday.Renderer
	URLPrefix string
	IsWiki    bool
}

var byteMailto = []byte("mailto:")

var htmlEscaper = [256][]byte{
	'&': []byte("&"),
	'<': []byte("&lt;"),
	'>': []byte("&gt;"),
	'"': []byte("&quot;"),
}

func escapeHTML(w io.Writer, s []byte) {
	var start, end int
	for end < len(s) {
		escSeq := htmlEscaper[s[end]]
		if escSeq != nil {
			_, _ = w.Write(s[start:end])
			_, _ = w.Write(escSeq)
			start = end + 1
		}
		end++
	}
	if start < len(s) && end <= len(s) {
		_, _ = w.Write(s[start:end])
	}
}

// RenderNode is a default renderer of a single node of a syntax tree. For
// block nodes it will be called twice: first time with entering=true, second
// time with entering=false, so that it could know when it's working on an open
// tag and when on close. It writes the result to w.
//
// The return value is a way to tell the calling walker to adjust its walk
// pattern: e.g. it can terminate the traversal by returning Terminate. Or it
// can ask the walker to skip a subtree of this node by returning SkipChildren.
// The typical behavior is to return GoToNext, which asks for the usual
// traversal to the next node.
func (r *Renderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
	switch node.Type {
	case blackfriday.Image:
		prefix := r.URLPrefix
		if r.IsWiki {
			prefix = util.URLJoin(prefix, "wiki", "raw")
		}
		prefix = strings.Replace(prefix, "/src/", "/media/", 1)
		link := node.LinkData.Destination
		if len(link) > 0 && !markup.IsLink(link) {
			lnk := string(link)
			lnk = util.URLJoin(prefix, lnk)
			lnk = strings.Replace(lnk, " ", "+", -1)
			link = []byte(lnk)
		}
		node.LinkData.Destination = link
		// Render link around image only if parent is not link already
		if node.Parent != nil && node.Parent.Type != blackfriday.Link {
			if entering {
				_, _ = w.Write([]byte(`<a href="`))
				escapeHTML(w, link)
				_, _ = w.Write([]byte(`">`))
				return r.Renderer.RenderNode(w, node, entering)
			}
			s := r.Renderer.RenderNode(w, node, entering)
			_, _ = w.Write([]byte(`</a>`))
			return s
		}
		return r.Renderer.RenderNode(w, node, entering)
	case blackfriday.Link:
		// special case: this is not a link, a hash link or a mailto:, so it's a
		// relative URL
		link := node.LinkData.Destination
		if len(link) > 0 && !markup.IsLink(link) &&
			link[0] != '#' && !bytes.HasPrefix(link, byteMailto) &&
			node.LinkData.Footnote == nil {
			lnk := string(link)
			if r.IsWiki {
				lnk = util.URLJoin("wiki", lnk)
			}
			link = []byte(util.URLJoin(r.URLPrefix, lnk))
		}
		node.LinkData.Destination = link
		return r.Renderer.RenderNode(w, node, entering)
	case blackfriday.Text:
		isListItem := false
		for n := node.Parent; n != nil; n = n.Parent {
			if n.Type == blackfriday.Item {
				isListItem = true
				break
			}
		}
		if isListItem {
			text := node.Literal
			switch {
			case bytes.HasPrefix(text, []byte("[ ] ")):
				_, _ = w.Write([]byte(`<span class="ui fitted disabled checkbox"><input type="checkbox" disabled="disabled" /><label /></span>`))
				text = text[3:]
			case bytes.HasPrefix(text, []byte("[x] ")):
				_, _ = w.Write([]byte(`<span class="ui checked fitted disabled checkbox"><input type="checkbox" checked="" disabled="disabled" /><label /></span>`))
				text = text[3:]
			}
			node.Literal = text
		}
	}
	return r.Renderer.RenderNode(w, node, entering)
}

const (
	blackfridayExtensions = 0 |
		blackfriday.NoIntraEmphasis |
		blackfriday.Tables |
		blackfriday.FencedCode |
		blackfriday.Strikethrough |
		blackfriday.NoEmptyLineBeforeBlock |
		blackfriday.DefinitionLists |
		blackfriday.Footnotes |
		blackfriday.HeadingIDs |
		blackfriday.AutoHeadingIDs
	blackfridayHTMLFlags = 0 |
		blackfriday.Smartypants
)

// RenderRaw renders Markdown to HTML without handling special links.
func RenderRaw(body []byte, urlPrefix string, wikiMarkdown bool) []byte {
	renderer := &Renderer{
		Renderer: blackfriday.NewHTMLRenderer(blackfriday.HTMLRendererParameters{
			Flags: blackfridayHTMLFlags,
		}),
		URLPrefix: urlPrefix,
		IsWiki:    wikiMarkdown,
	}

	exts := blackfridayExtensions
	if setting.Markdown.EnableHardLineBreak {
		exts |= blackfriday.HardLineBreak
	}

	body = blackfriday.Run(body, blackfriday.WithRenderer(renderer), blackfriday.WithExtensions(exts))
	return markup.SanitizeBytes(body)
}

var (
	// MarkupName describes markup's name
	MarkupName = "markdown"
)

func init() {
	markup.RegisterParser(Parser{})
}

// Parser implements markup.Parser
type Parser struct {
}

// Name implements markup.Parser
func (Parser) Name() string {
	return MarkupName
}

// Extensions implements markup.Parser
func (Parser) Extensions() []string {
	return setting.Markdown.FileExtensions
}

// Render implements markup.Parser
func (Parser) Render(rawBytes []byte, urlPrefix string, metas map[string]string, isWiki bool) []byte {
	return RenderRaw(rawBytes, urlPrefix, isWiki)
}

// Render renders Markdown to HTML with all specific handling stuff.
func Render(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
	return markup.Render("a.md", rawBytes, urlPrefix, metas)
}

// RenderString renders Markdown to HTML with special links and returns string type.
func RenderString(raw, urlPrefix string, metas map[string]string) string {
	return markup.RenderString("a.md", raw, urlPrefix, metas)
}

// RenderWiki renders markdown wiki page to HTML and return HTML string
func RenderWiki(rawBytes []byte, urlPrefix string, metas map[string]string) string {
	return markup.RenderWiki("a.md", rawBytes, urlPrefix, metas)
}

// IsMarkdownFile reports whether name looks like a Markdown file
// based on its extension.
func IsMarkdownFile(name string) bool {
	return markup.IsMarkupFile(name, MarkupName)
}