-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathprettyprint.go
73 lines (66 loc) · 1.45 KB
/
prettyprint.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
package prettyprint
import (
"golang.org/x/net/html"
"strings"
)
// Prettify takes a string with unformatted HTML content and formats
// it prettily with indentation supplied through the indent argument.
//
// For example, it takes a string of html like this:
//
// <html><head></head><body><p>Hello</p></body></html>
//
// and formats it into this:
//
// <html>
// <head>
// </head>
// <body>
// <a href="http://test.com">Test link</a>
// <p>
// <br/>
// </p>
// </body>
// </html>
//
// if the provided indent parameter is a string with four spaces (" ").
//
// It returns the prettified string :pretty:, and possibly an error :e:
func Prettify(raw string, indent string) (pretty string, e error) {
r := strings.NewReader(raw)
z := html.NewTokenizer(r)
pretty = ""
depth := 0
prevToken := html.CommentToken
for {
tt := z.Next()
tokenString := string(z.Raw())
// strip away newlines
if tt == html.TextToken {
stripped := strings.Trim(tokenString, "\n")
if len(stripped) == 0 {
continue
}
}
if tt == html.EndTagToken {
depth -= 1
}
if tt != html.TextToken {
if prevToken != html.TextToken {
pretty += "\n"
for i := 0; i < depth; i++ {
pretty += indent
}
}
}
pretty += tokenString
// last token
if tt == html.ErrorToken {
break
} else if tt == html.StartTagToken {
depth += 1
}
prevToken = tt
}
return strings.Trim(pretty, "\n"), nil
}