Debian Codegraph @

format/markdown.go

raw
1 // Copyright (c) 2022 Tulir Asokan
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package format
8
9 import (
10 "fmt"
11 "regexp"
12 "strings"
13
14 "github.com/yuin/goldmark"
15 "github.com/yuin/goldmark/extension"
16 "github.com/yuin/goldmark/renderer/html"
17
18 "maunium.net/go/mautrix/event"
19 )
20
21 var AntiParagraphRegex = regexp.MustCompile("^<p>(.+?)</p>$")
22
23 var Extensions = goldmark.WithExtensions(extension.Strikethrough, extension.Table, ExtensionSpoiler)
24 var HTMLOptions = goldmark.WithRendererOptions(html.WithHardWraps(), html.WithUnsafe())
25
26 var withHTML = goldmark.New(Extensions, HTMLOptions)
27 var noHTML = goldmark.New(Extensions, HTMLOptions, goldmark.WithExtensions(ExtensionEscapeHTML))
28
29 func RenderMarkdown(text string, allowMarkdown, allowHTML bool) event.MessageEventContent {
30 var htmlBody string
31
32 if allowMarkdown {
33 rndr := withHTML
34 if !allowHTML {
35 rndr = noHTML
36 }
37 var buf strings.Builder
38 err := rndr.Convert([]byte(text), &buf)
39 if err != nil {
40 panic(fmt.Errorf("markdown parser errored: %w", err))
41 }
42 htmlBody = strings.TrimRight(buf.String(), "\n")
43 htmlBody = AntiParagraphRegex.ReplaceAllString(htmlBody, "$1")
44 } else {
45 htmlBody = strings.Replace(text, "\n", "<br>", -1)
46 }
47
48 if len(htmlBody) > 0 && (allowMarkdown || allowHTML) {
49 text = HTMLToText(htmlBody)
50
51 if htmlBody != text {
52 return event.MessageEventContent{
53 FormattedBody: htmlBody,
54 Format: event.FormatHTML,
55 MsgType: event.MsgText,
56 Body: text,
57 }
58 }
59 }
60
61 return event.MessageEventContent{
62 MsgType: event.MsgText,
63 Body: text,
64 }
65 }