-
Notifications
You must be signed in to change notification settings - Fork 77
/
comment.go
68 lines (55 loc) · 1.48 KB
/
comment.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
package pgs
import (
"bufio"
"bytes"
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
const commentPrefix = "//"
// C returns a comment block, wrapping when the line's length will exceed wrap.
func C(wrap int, args ...interface{}) string {
s := commentScanner(wrap, args...)
buf := &bytes.Buffer{}
for s.Scan() {
fmt.Fprintln(buf, commentPrefix, s.Text())
}
return buf.String()
}
// C80 is an alias for C(80, args...)
func C80(args ...interface{}) string { return C(80, args...) }
func commentScanner(wrap int, args ...interface{}) *bufio.Scanner {
s := bufio.NewScanner(strings.NewReader(fmt.Sprint(args...)))
s.Split(splitComment(wrap - 3))
return s
}
func splitComment(w int) bufio.SplitFunc {
return func(data []byte, atEOF bool) (advance int, token []byte, err error) {
var r rune
start := 0
lastSpace := 0
for width := 0; start < len(data); start += width {
r, width = utf8.DecodeRune(data[start:])
if !unicode.IsSpace(r) {
break
}
}
for width, i := 0, start; i < len(data); i += width {
r, width = utf8.DecodeRune(data[i:])
if unicode.IsSpace(r) {
if i >= w { // we are at our max comment width
if lastSpace == 0 { // the token cannot be broken down further, allow it to break the limit
return i + width, data[start:i], nil
}
return lastSpace, data[start:lastSpace], nil
}
lastSpace = i
}
}
if atEOF && len(data) > start {
return len(data), bytes.TrimSpace(data[start:]), nil
}
return start, nil, nil
}
}