-
-
Notifications
You must be signed in to change notification settings - Fork 69
/
markdown.go
76 lines (64 loc) · 2 KB
/
markdown.go
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
// Copyright (c) 2020 Tulir Asokan
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package format
import (
"io"
"regexp"
"strings"
"github.com/russross/blackfriday/v2"
"maunium.net/go/mautrix/event"
)
type EscapingRenderer struct {
*blackfriday.HTMLRenderer
}
func (r *EscapingRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
if node.Type == blackfriday.HTMLSpan {
node.Type = blackfriday.Text
}
return r.HTMLRenderer.RenderNode(w, node, entering)
}
var AntiParagraphRegex = regexp.MustCompile("^<p>(.+?)</p>$")
var Extensions = blackfriday.WithExtensions(blackfriday.NoIntraEmphasis |
blackfriday.Tables |
blackfriday.FencedCode |
blackfriday.Strikethrough |
blackfriday.SpaceHeadings |
blackfriday.DefinitionLists |
blackfriday.HardLineBreak)
var bfhtml = blackfriday.NewHTMLRenderer(blackfriday.HTMLRendererParameters{
Flags: blackfriday.UseXHTML,
})
var Renderer = blackfriday.WithRenderer(bfhtml)
var NoHTMLRenderer = blackfriday.WithRenderer(&EscapingRenderer{bfhtml})
func RenderMarkdown(text string, allowMarkdown, allowHTML bool) event.MessageEventContent {
var htmlBody string
if allowMarkdown {
renderer := Renderer
if !allowHTML {
renderer = NoHTMLRenderer
}
htmlBodyBytes := blackfriday.Run([]byte(text), Extensions, renderer)
htmlBody = strings.TrimRight(string(htmlBodyBytes), "\n")
htmlBody = AntiParagraphRegex.ReplaceAllString(htmlBody, "$1")
} else {
htmlBody = strings.Replace(text, "\n", "<br>", -1)
}
if len(htmlBody) > 0 && (allowMarkdown || allowHTML) {
text = HTMLToText(htmlBody)
if htmlBody != text {
return event.MessageEventContent{
FormattedBody: htmlBody,
Format: event.FormatHTML,
MsgType: event.MsgText,
Body: text,
}
}
}
return event.MessageEventContent{
MsgType: event.MsgText,
Body: text,
}
}