forked from pseudomuto/protoc-gen-doc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filters.go
52 lines (44 loc) · 1.78 KB
/
filters.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
package gendoc
import (
"fmt"
"html/template"
"regexp"
"strings"
)
var (
paraPattern = regexp.MustCompile(`(\n\n)\s*`)
spacePattern = regexp.MustCompile("( )+")
multiNewlinePattern = regexp.MustCompile(`(\n){2,}`)
specialCharsPattern = regexp.MustCompile(`[^a-zA-Z0-9_-]`)
)
// PFilter splits the content by new lines and wraps each one in a <p> tag.
func PFilter(content string) template.HTML {
normalized := strings.Replace(content, "\r\n", "\n", -1)
paragraphs := paraPattern.Split(normalized, -1)
return template.HTML(fmt.Sprintf("<p>%s</p>", strings.Join(paragraphs, "</p><p>")))
}
// ParaFilter splits the content by new lines and wraps each one in a <para> tag.
func ParaFilter(content string) string {
normalized := strings.Replace(content, "\r\n", "\n", -1)
paragraphs := paraPattern.Split(normalized, -1)
return fmt.Sprintf("<para>%s</para>", strings.Join(paragraphs, "</para><para>"))
}
// NoBrFilter removes single CR and LF from content.
func NoBrFilter(content string) string {
normalized := strings.Replace(content, "\r\n", "\n", -1)
paragraphs := multiNewlinePattern.Split(normalized, -1)
for i, p := range paragraphs {
withoutCR := strings.Replace(p, "\r", " ", -1)
withoutLF := strings.Replace(withoutCR, "\n", " ", -1)
paragraphs[i] = spacePattern.ReplaceAllString(withoutLF, " ")
}
return strings.Join(paragraphs, "\n\n")
}
// BrFilter uses NoBrFilter to remove single CR and LF and then replaces \n\n with <br/><br/>
func BrFilter(content string) template.HTML {
return template.HTML(strings.Replace(NoBrFilter(content), "\n\n", "<br/><br/>", -1))
}
// AnchorFilter replaces all special characters with URL friendly dashes
func AnchorFilter(str string) string {
return specialCharsPattern.ReplaceAllString(strings.ReplaceAll(str, "/", "_"), "-")
}