website/pkg/markdown/markdown.go

61 lines
1.6 KiB
Go
Raw Permalink Normal View History

// Package markdown provides markdown render functions.
package markdown
import (
"regexp"
"strings"
"github.com/microcosm-cc/bluemonday"
"github.com/shurcooL/github_flavored_markdown"
)
var (
RegexpHTMLTag = regexp.MustCompile(`<(.|\n)+?>`)
RegexpMarkdownLink = regexp.MustCompile(`\[([^\[\]]*)\]\((.*?)\)`)
)
// 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)
}
// 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")
}
/*
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
}