2022-08-11 03:59:59 +00:00
|
|
|
// Package markdown provides markdown render functions.
|
|
|
|
package markdown
|
|
|
|
|
|
|
|
import (
|
2024-11-28 20:31:04 +00:00
|
|
|
"regexp"
|
2022-08-24 05:55:19 +00:00
|
|
|
"strings"
|
|
|
|
|
2022-08-11 03:59:59 +00:00
|
|
|
"github.com/microcosm-cc/bluemonday"
|
|
|
|
"github.com/shurcooL/github_flavored_markdown"
|
|
|
|
)
|
|
|
|
|
2024-11-28 20:31:04 +00:00
|
|
|
var (
|
|
|
|
RegexpHTMLTag = regexp.MustCompile(`<(.|\n)+?>`)
|
|
|
|
RegexpMarkdownLink = regexp.MustCompile(`\[([^\[\]]*)\]\((.*?)\)`)
|
|
|
|
)
|
|
|
|
|
2022-08-11 03:59:59 +00:00
|
|
|
// Render markdown from untrusted sources.
|
|
|
|
func Render(input string) string {
|
|
|
|
// Render Markdown to HTML.
|
|
|
|
html := github_flavored_markdown.Markdown([]byte(input))
|
|
|
|
|
|
|
|
// Sanitize the HTML from any nasties.
|
|
|
|
p := bluemonday.UGCPolicy()
|
|
|
|
safened := p.SanitizeBytes(html)
|
|
|
|
return string(safened)
|
|
|
|
}
|
2022-08-24 05:55:19 +00:00
|
|
|
|
|
|
|
// Quotify a message putting it into a Markdown "> quotes" block.
|
|
|
|
func Quotify(input string) string {
|
|
|
|
var lines = []string{}
|
|
|
|
for _, line := range strings.Split(input, "\n") {
|
|
|
|
lines = append(lines, "> "+line)
|
|
|
|
}
|
|
|
|
return strings.Join(lines, "\n")
|
|
|
|
}
|
2024-11-28 20:31:04 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
DeMarkify strips some Markdown syntax from plain text snippets.
|
|
|
|
|
|
|
|
It is especially useful on Forum views that show plain text contents of posts, and especially
|
|
|
|
for linked at-mentions of the form `[@username](/go/comment?id=1234)` so that those can be
|
|
|
|
simplified down to just the `@username` text contents.
|
|
|
|
|
|
|
|
This function will strip and simplify:
|
|
|
|
|
|
|
|
- Markdown hyperlinks as spelled out above
|
|
|
|
- Literal HTML tags such as <a href="">
|
|
|
|
*/
|
|
|
|
func DeMarkify(input string) string {
|
|
|
|
// Strip all standard HTML tags.
|
|
|
|
input = RegexpHTMLTag.ReplaceAllString(input, "")
|
|
|
|
|
|
|
|
// Replace Markdown hyperlinks.
|
|
|
|
matches := RegexpMarkdownLink.FindAllStringSubmatch(input, -1)
|
|
|
|
for _, m := range matches {
|
|
|
|
input = strings.ReplaceAll(input, m[0], m[1])
|
|
|
|
}
|
|
|
|
|
|
|
|
return input
|
|
|
|
}
|