-
Notifications
You must be signed in to change notification settings - Fork 0
/
encodeTabs.go
114 lines (98 loc) · 2.23 KB
/
encodeTabs.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package encode
import (
"io"
"strconv"
"github.com/ionous/tell/runes"
)
type TabWriter struct {
depth int // requested leading spaces on each new line
spaces int // trailing spaces
newLines int
Writer io.Writer
xpos int
}
// a soft space -- eaten if theres a newline
func (tab *TabWriter) Space() {
tab.spaces++
}
func (tab *TabWriter) Tab() {
tab.spaces += 2
}
func (tab *TabWriter) Softline() {
if tab.newLines == 0 {
tab.newLines++
}
tab.spaces = 0
}
func (tab *TabWriter) OptionalLine(b bool) {
if b {
tab.Softline()
}
}
// inc: increases the current indent
// line: increases the current line
func (tab *TabWriter) Indent(inc bool) {
if inc {
tab.depth += 2
} else {
tab.depth -= 2
}
}
// call before writing runes or strings
// advances the line and pads the indent
func (tab *TabWriter) pad() {
if n := tab.newLines; n > 0 {
tab.newLines = 0
for i := 0; i < n; i++ {
runes.WriteRune(tab.Writer, runes.Newline)
}
writeSpaces(tab.Writer, tab.depth)
tab.xpos = tab.depth
}
//
tab.writeSpaces()
}
func (tab *TabWriter) writeSpaces() {
if tab.spaces > 0 {
writeSpaces(tab.Writer, tab.spaces)
tab.xpos += tab.spaces
tab.spaces = 0
}
}
// quotes and escapes the passed string.
// fix? uses strconv, and strconv produces \x, \u, and \U escapes
// ( plus it requires multiple traversals over the string )
func (tab *TabWriter) Quote(s string) {
str := strconv.Quote(s)
tab.WriteString(str)
}
// write a non-quoted escaped string
func (tab *TabWriter) Escape(s string) {
str := strconv.Quote(s) // fix? strconv doesnt have a writer api
tab.WriteString(str[1 : len(str)-1])
}
func (tab *TabWriter) WriteString(s string) (int, error) {
tab.pad()
tab.xpos += len(s) // approximate
return io.WriteString(tab.Writer, s)
}
func (tab *TabWriter) WriteRune(q rune) (ret int, err error) {
tab.pad()
tab.xpos += 1 // approximate
return runes.WriteRune(tab.Writer, q)
}
func (tab *TabWriter) writeLine(str string) {
tab.WriteString(str)
tab.Softline()
}
func (tab *TabWriter) writeLines(lines []string) {
for _, line := range lines {
tab.writeLine(line)
}
}
func writeSpaces(w io.Writer, cnt int) {
b := []byte{runes.Space} // what is the fast way to do this?
for i := 0; i < cnt; i++ {
w.Write(b)
}
}