Repository navigation
Expand file tree
/
Copy pathguesswidth.go
More file actions
542 lines (492 loc) · 11.9 KB
/
Copy pathguesswidth.go
File metadata and controls
542 lines (492 loc) · 11.9 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
// Package guesswidth handles the format as formatted by printf.
// Spaces exist as delimiters, but spaces are not always delimiters.
// The width seems to be a fixed length, but it doesn't always fit.
// guesswidth finds the column separation position
// from the reference line(header) and multiple lines(body).
package guesswidth
import (
"bufio"
"fmt"
"io"
"runtime/debug"
"sort"
"strings"
"unicode"
"unicode/utf8"
"github.com/rivo/uniseg"
)
// GuessWidth reads records from printf-like output.
type GuessWidth struct {
reader *bufio.Reader
// pos is a list of separator positions.
pos []int
// Widths is the width of the column.
Widths []Cols
// preLines stores the lines read for scan.
preLines []string
// preCount is the number returned by read.
preCount int
// ScanNum is the number to scan to analyze.
ScanNum int
// Header is the base line number. It starts from 0.
Header int
// limitSplit is the maximum number of columns to split.
LimitSplit int
// MinLines is the minimum number of lines to recognize as a separator.
// 1 if only the header, 2 or more if there is a blank in the body.
MinLines int
// TrimSpace is whether to trim the space in the value.
TrimSpace bool
}
// Cols is the width and justification of the column.
type Cols struct {
Width int // Width is the width of the column.
Justified int // Justified indicates the justification of the column (Left or Right).
rightCount int // rightCount is the number of times the column appears to be right-aligned.
}
// Justification constants for columns.
const (
Left = iota // Left indicates left alignment.
Right // Right indicates right alignment.
)
// NewReader returns a new Reader that reads from r.
func NewReader(r io.Reader) *GuessWidth {
reader := bufio.NewReader(r)
g := &GuessWidth{
reader: reader,
ScanNum: 100,
preCount: 0,
Header: 0,
LimitSplit: 0,
MinLines: 2,
TrimSpace: true,
}
return g
}
// ReadAll reads all rows
// and returns a two-dimensional slice of rows and columns.
func (g *GuessWidth) ReadAll() [][]string {
if len(g.preLines) == 0 {
g.Scan(g.ScanNum)
}
g.Widths = make([]Cols, len(g.pos)+1)
var rows [][]string
for {
columns, err := g.Read()
if err != nil {
break
}
g.UpdateMaxWidth(columns)
rows = append(rows, columns)
}
rightThreshold := len(rows) / 2
if rightThreshold == 0 {
// Avoid deciding alignment from a single row.
rightThreshold = len(rows)
}
g.SetJustified(rightThreshold)
return rows
}
// UpdateMaxWidth updates the maximum width of the column.
func (g *GuessWidth) UpdateMaxWidth(columns []string) []Cols {
if len(g.Widths) < len(columns) {
for n := len(g.Widths); n < len(columns); n++ {
g.Widths = append(g.Widths, Cols{})
}
}
lastCol := len(g.Widths) - 1
for n, col := range columns {
width := uniseg.StringWidth(strings.TrimSpace(col))
if width > g.Widths[n].Width {
g.Widths[n].Width = width
}
if n != lastCol && isRightAlign(col) {
g.Widths[n].rightCount++
}
}
return g.Widths
}
// SetJustified marks a column as right-justified when its right-aligned row count
// exceeds threshold.
func (g *GuessWidth) SetJustified(threshold int) []Cols {
for n, col := range g.Widths {
if col.rightCount > threshold {
col.Justified = Right
}
g.Widths[n] = col
}
return g.Widths
}
// isRightAlign checks if a string is right-aligned based on trailing spaces.
// A string is considered right-aligned if it has non-space characters followed by one or more spaces at the end.
func isRightAlign(str string) bool {
if str == "" {
return false
}
r := len(str) - 1
for n := 0; n < len(str); n++ {
if str[n] != ' ' {
return false
}
if str[r-n] != ' ' {
return true
}
}
return false
}
// readLine reads a single line from the reader, handling line endings and EOF correctly.
func readLine(reader *bufio.Reader) (string, error) {
line, err := reader.ReadString('\n')
if err != nil && (err != io.EOF || len(line) == 0) {
return "", err
}
if before, ok := strings.CutSuffix(line, "\n"); ok {
line = before
line = strings.TrimSuffix(line, "\r")
}
return line, nil
}
// Scan preReads and parses the lines.
func (g *GuessWidth) Scan(num int) {
for range num {
line, err := readLine(g.reader)
if err != nil {
break
}
g.preLines = append(g.preLines, line)
}
g.pos = Positions(g.preLines, g.Header, g.MinLines)
if g.LimitSplit > 0 {
if len(g.pos) > g.LimitSplit {
g.pos = g.pos[:g.LimitSplit]
}
}
}
// Read reads one row and returns a slice of columns.
// Scan is executed first if it is not preRead.
func (g *GuessWidth) Read() ([]string, error) {
if len(g.preLines) == 0 {
g.Scan(g.ScanNum)
}
var line string
if g.preCount < len(g.preLines) {
line = g.preLines[g.preCount]
g.preCount++
} else {
var err error
line, err = readLine(g.reader)
if err != nil {
return nil, err
}
}
return split(line, g.pos, g.TrimSpace), nil
}
// ToTable parses a slice of lines and returns a table.
func ToTable(lines []string, header int, trimSpace bool) [][]string {
pos := Positions(lines, header, 2)
return toRows(lines, pos, trimSpace)
}
// ToTableN parses a slice of lines and returns a table, but limits the number of splits.
func ToTableN(lines []string, header int, numSplit int, trimSpace bool) [][]string {
if numSplit <= 0 {
return ToTable(lines, header, trimSpace)
}
pos := Positions(lines, header, 2)
if len(pos) > numSplit {
pos = pos[:numSplit]
}
return toRows(lines, pos, trimSpace)
}
// Positions returns separator positions
// from multiple lines and header line number.
// Lines before the header line are ignored.
func Positions(lines []string, header int, minLines int) []int {
var blanks []int
if header < 0 {
header = 0
}
for n, line := range lines {
if n < header {
continue
}
if n == header {
blanks = lookupBlanks(strings.TrimSuffix(line, " "))
continue
}
blanks = countBlanks(blanks, strings.TrimSuffix(line, " "))
}
pos := positions(blanks, minLines)
if header < len(lines) {
pos = ensureLastHeaderColumnPosition(pos, lines[header])
}
return pos
}
// ensureLastHeaderColumnPosition ensures that the last header column position
// is included in the separator positions if it exists.
func ensureLastHeaderColumnPosition(pos []int, headerLine string) []int {
if p, ok := lastHeaderColumnPosition(headerLine); ok {
found := false
for _, existing := range pos {
if existing >= p-1 && existing <= p {
found = true
break
}
}
if !found {
pos = append(pos, p)
sort.Ints(pos)
}
}
return pos
}
// lastHeaderColumnPosition returns the start position of the last column in
// the header line and a boolean indicating if it exists.
func lastHeaderColumnPosition(line string) (int, bool) {
gr := uniseg.NewGraphemes(line)
width := 0
lastColumnStart := 0
hasPreviousColumn := false
previousWasSpace := true
for gr.Next() {
value := gr.Str()
if value == " " {
previousWasSpace = true
} else {
if previousWasSpace {
if hasPreviousColumn {
lastColumnStart = width
}
hasPreviousColumn = true
}
previousWasSpace = false
}
width += gr.Width()
}
return lastColumnStart, hasPreviousColumn && lastColumnStart > 0
}
// separatorPosition determines the best position for a separator in a line.
func separatorPosition(graphemes []string, widths []int, p int, start int, pos []int, n int, w int) int {
r, _ := utf8.DecodeRuneInString(graphemes[p])
if unicode.IsSpace(r) {
return p
}
f := p
fp := 0
for ; f < len(graphemes); f++ {
r, _ := utf8.DecodeRuneInString(graphemes[f])
if unicode.IsSpace(r) {
break
}
fp += widths[f]
}
b := p
bp := 0
for ; b > 0; b-- {
r, _ := utf8.DecodeRuneInString(graphemes[b])
if unicode.IsSpace(r) {
break
}
bp += widths[b]
}
fWidth := w + fp
bWidth := w - bp
if n < len(pos)-1 {
if separatorBeforeDoubleSpace(graphemes, widths, p, f, fWidth, pos[n+1]) {
return f
}
if fWidth == pos[n+1] {
return b
}
if bWidth == pos[n] {
return f
}
if bWidth > pos[n] && bWidth < pos[n+1] {
return b
}
}
if fp > bp && b > start {
return b
}
return f
}
// separatorBeforeDoubleSpace keeps a shifted value in its column when the
// following value starts after at least two spaces at the next column boundary.
func separatorBeforeDoubleSpace(graphemes []string, widths []int, p, f, fWidth, nextPosition int) bool {
wordStart := p == 0
if p > 0 {
r, _ := utf8.DecodeRuneInString(graphemes[p-1])
wordStart = unicode.IsSpace(r)
}
if !wordStart || f >= len(graphemes) {
return false
}
next := f
spaceWidth := 0
for next < len(graphemes) {
r, _ := utf8.DecodeRuneInString(graphemes[next])
if !unicode.IsSpace(r) {
break
}
spaceWidth += widths[next]
next++
}
if spaceWidth < 2 || next >= len(graphemes) {
return false
}
nextWidth := fWidth + spaceWidth
for next < len(graphemes) {
r, _ := utf8.DecodeRuneInString(graphemes[next])
if unicode.IsSpace(r) {
break
}
nextWidth += widths[next]
next++
}
return nextWidth == nextPosition
}
// split splits a line into columns based on separator positions.
func split(line string, pos []int, trimSpace bool) []string {
columns := make([]string, len(pos)+1)
if len(pos) == 0 {
if trimSpace {
line = strings.TrimSpace(line)
}
columns[0] = line
return columns
}
var graphemes []string
var widths []int
gr := uniseg.NewGraphemes(line)
for gr.Next() {
graphemes = append(graphemes, gr.Str())
widths = append(widths, gr.Width())
}
n := 0
start, end := 0, 0
w := 0
for p := 0; p < len(graphemes); p++ {
if n >= len(pos) {
start = end + 1
break
}
if pos[n] <= w {
end = separatorPosition(graphemes, widths, p, start, pos, n, w)
if start > end {
break
}
col := strings.Join(graphemes[start:end], "")
if trimSpace {
columns[n] = strings.TrimSpace(col)
} else {
columns[n] = col
}
n++
start = end
}
w += widths[p]
}
if start >= len(graphemes) {
return columns
}
// Handle the remaining part of the line after the last separator.
col := strings.Join(graphemes[start:], "")
if trimSpace {
col = strings.TrimSpace(col)
}
columns[n] = col
return columns
}
// toRows returns rows separated by columns.
func toRows(lines []string, pos []int, trimSpace bool) [][]string {
rows := make([][]string, 0, len(lines))
for _, line := range lines {
columns := split(line, pos, trimSpace)
rows = append(rows, columns)
}
return rows
}
// lookupBlanks returns a slice of counts of blank spaces in the line.
func lookupBlanks(line string) []int {
blanks := make([]int, 0)
first := true
gr := uniseg.NewGraphemes(line)
for gr.Next() {
v := gr.Str()
if v == " " {
if first {
blanks = append(blanks, 0)
continue
}
blanks = append(blanks, 1)
continue
}
first = false
blanks = append(blanks, 0)
if gr.Width() == 2 {
blanks = append(blanks, 0)
}
}
return blanks
}
// countBlanks counts the number of blank spaces in the line and updates the blanks slice.
func countBlanks(blanks []int, line string) []int {
n := 0
gr := uniseg.NewGraphemes(line)
for gr.Next() {
r := gr.Str()
if n >= len(blanks) {
break
}
if r == " " && blanks[n] > 0 {
blanks[n] += 1
}
n++
if gr.Width() == 2 {
n++
}
}
return blanks
}
// positions generates a list of separator positions from a blank slice.
func positions(blanks []int, minLines int) []int {
max := minLines
p := 0
var pos []int
for n, v := range blanks {
if v >= max {
max = v
p = n
}
if v == 0 {
max = minLines
if p > 0 {
pos = append(pos, p)
p = 0
}
}
}
return pos
}
// DebugCountPrint is for debugging which prints the space count.
func DebugCountPrint(line string, blanks []int) {
fmt.Println(line)
for _, k := range blanks {
fmt.Print(k)
}
fmt.Println()
}
var (
version string
revision string
)
// Version returns the version of the package.
func Version() string {
if version != "" {
return version + " rev:" + revision
}
info, ok := debug.ReadBuildInfo()
if !ok {
return "(devel)"
}
return info.Main.Version
}