-
Notifications
You must be signed in to change notification settings - Fork 1
/
bbgo.go
79 lines (65 loc) · 1.84 KB
/
bbgo.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
74
75
76
77
78
79
package bbgo
import (
"html"
"io"
"strings"
basecontext "context"
"github.com/namreg/bbgo/context"
"github.com/namreg/bbgo/lexer"
"github.com/namreg/bbgo/node"
"github.com/namreg/bbgo/parser"
"github.com/namreg/bbgo/processor"
"github.com/namreg/bbgo/token"
)
const br = "<br>"
// Processor process a bbcode tag and writes result to the given Writer.
type Processor func(*context.Context, node.Tag, io.Writer)
// BBGO is a main object.
type BBGO struct {
tags map[string]Processor
}
// New creates a new BBGO and registers default processors.
func New() *BBGO {
b := &BBGO{
tags: make(map[string]Processor),
}
b.registerDefaultProcessors()
return b
}
// RegisterTag registers a new tag.
func (b *BBGO) RegisterTag(name string, p Processor) {
b.tags[name] = p
token.RegisterIdentifiers(name)
}
// Parse parses the given input.
func (b *BBGO) Parse(input string) string {
ctx := context.New(basecontext.Background())
sb := new(strings.Builder)
l := lexer.New(input)
p := parser.New(l)
for n := range p.Parse() {
if t, ok := n.(node.Tag); ok && (ctx.RawModeTag() == nil || ctx.InRawMode(t)) {
if proc, ok := b.tags[t.TagName()]; ok {
proc(ctx, t, sb)
}
} else if _, ok := n.(*node.Newline); ok {
io.WriteString(sb, br)
} else {
io.WriteString(sb, html.EscapeString(n.String()))
}
ctx.SetPrevNode(n)
}
return sb.String()
}
func (b *BBGO) registerDefaultProcessors() {
b.RegisterTag("color", Processor(processor.Color))
b.RegisterTag("code", Processor(processor.Code))
b.RegisterTag("img", Processor(processor.Img))
b.RegisterTag("quote", Processor(processor.Quote))
b.RegisterTag("url", Processor(processor.URL))
b.RegisterTag("list", Processor(processor.List))
b.RegisterTag("*", Processor(processor.Asterisk))
for _, t := range []string{"i", "b", "u", "s"} {
b.RegisterTag(t, Processor(processor.Simple))
}
}