...
1 package statements
2
3 import (
4 "fmt"
5 "regexp"
6 "strings"
7
8 "github.com/noirbizarre/gonja/exec"
9 "github.com/noirbizarre/gonja/nodes"
10 "github.com/noirbizarre/gonja/parser"
11 "github.com/noirbizarre/gonja/tokens"
12 )
13
14 type SpacelessStmt struct {
15 Location *tokens.Token
16 wrapper *nodes.Wrapper
17 }
18
19 func (stmt *SpacelessStmt) Position() *tokens.Token { return stmt.Location }
20 func (stmt *SpacelessStmt) String() string {
21 t := stmt.Position()
22 return fmt.Sprintf("SpacelessStmt(Line=%d Col=%d)", t.Line, t.Col)
23 }
24
25 var spacelessRegexp = regexp.MustCompile(`(?U:(<.*>))([\t\n\v\f\r ]+)(?U:(<.*>))`)
26
27 func (stmt *SpacelessStmt) Execute(r *exec.Renderer, tag *nodes.StatementBlock) error {
28 var out strings.Builder
29
30 sub := r.Inherit()
31 sub.Out = &out
32 err := sub.ExecuteWrapper(stmt.wrapper)
33 if err != nil {
34 return err
35 }
36
37 s := out.String()
38
39 changed := true
40 for changed {
41 s2 := spacelessRegexp.ReplaceAllString(s, "$1$3")
42 changed = s != s2
43 s = s2
44 }
45
46 r.WriteString(s)
47
48 return nil
49 }
50
51 func spacelessParser(p *parser.Parser, args *parser.Parser) (nodes.Statement, error) {
52 stmt := &SpacelessStmt{
53 Location: p.Current(),
54 }
55
56 wrapper, _, err := p.WrapUntil("endspaceless")
57 if err != nil {
58 return nil, err
59 }
60 stmt.wrapper = wrapper
61
62 if !args.End() {
63 return nil, args.Error("Malformed spaceless-tag args.", nil)
64 }
65
66 return stmt, nil
67 }
68
69 func init() {
70 All.Register("spaceless", spacelessParser)
71 }
72
View as plain text