-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_block.go
More file actions
80 lines (64 loc) · 1.36 KB
/
code_block.go
File metadata and controls
80 lines (64 loc) · 1.36 KB
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
74
75
76
77
78
79
80
package remark
import (
"fmt"
"html"
"html/template"
"path/filepath"
"strings"
"github.com/gobuffalo/flect"
"github.com/gobuffalo/tags/v3"
)
type CodeBlock struct {
*Generic
Language string
Snippets Snippets
}
func (code CodeBlock) Name() string {
return "code"
}
func (code CodeBlock) ID() string {
id, _ := code.Get("src")
ext := filepath.Ext(id)
id = strings.TrimSuffix(id, ext)
id = flect.Dasherize(id)
id += ext
if s, ok := code.Attributes.Get("snippet"); ok {
id += "#" + s
}
return id
}
func (code *CodeBlock) HTML() template.HTML {
opts := code.Options()
lang := code.Language
if len(lang) == 0 {
lang = "plain"
}
opts["language"] = lang
var lines []string
for _, e := range code.Children {
switch t := e.(type) {
case String:
lines = append(lines, string(t))
case fmt.Stringer:
lines = append(lines, t.String())
default:
lines = append(lines, fmt.Sprintf("%s", t))
}
}
h := template.HTML(strings.Join(lines, "\n"))
if s, ok := code.Attributes.Get("snippet"); ok {
h = code.Snippets[s].HTML()
}
if id := code.ID(); len(id) > 0 {
opts["id"] = id
}
t := tags.New(code.Name(), opts)
hs := html.EscapeString(string(h))
t.Append(strings.TrimSpace(hs))
pre := tags.New("pre", nil)
pre.Append(t)
return pre.HTML()
}
func (code CodeBlock) String() string {
return html.UnescapeString(string(code.HTML()))
}