Skip to content

Commit f27aa95

Browse files
authored
Merge pull request #25 from xypwn/fix-format-help-row
Fix formatHelpRow with color output
2 parents 5db6772 + 2dfb002 commit f27aa95

1 file changed

Lines changed: 32 additions & 14 deletions

File tree

utils.go

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package argparse
22

33
import (
4-
"fmt"
54
"os"
65
"strings"
76

@@ -18,23 +17,42 @@ func decideTerminalWidth() int {
1817

1918
func formatHelpRow(head, content string, bareHeadLength, maxHeadLength, terminalWidth int, withBreak bool) string {
2019
content = strings.Replace(content, "\n", "", -1)
21-
result := fmt.Sprintf(" %s ", head)
22-
headLeftPadding := maxHeadLength - bareHeadLength - 3
23-
if headLeftPadding > 0 { // fill left padding
24-
result += strings.Repeat(" ", headLeftPadding)
20+
21+
head = " " + head + " " // head content
22+
bareHeadLength += 3 // head length without control chars
23+
24+
// length of a single content row, constant
25+
contentRowLen := terminalWidth - maxHeadLength
26+
27+
min := func(x, y int) int {
28+
if x < y {
29+
return x
30+
} else {
31+
return y
32+
}
2533
}
26-
contentPadding := strings.Repeat(" ", maxHeadLength)
34+
2735
var rows []string
28-
if withBreak && headLeftPadding < 0 {
29-
rows = append(rows, result, contentPadding+content)
36+
if withBreak && maxHeadLength < bareHeadLength {
37+
rows = append(rows, head)
3038
} else {
31-
rows = append(rows, result+content)
39+
// no break -> head is on the same row
40+
// as first content line
41+
var headRowPadding string
42+
if maxHeadLength > bareHeadLength {
43+
headRowPadding = strings.Repeat(" ", maxHeadLength-bareHeadLength)
44+
}
45+
rowLen := min(contentRowLen, len(content))
46+
rows = append(rows, head+headRowPadding+content[:rowLen])
47+
content = content[rowLen:]
3248
}
33-
for len(rows[len(rows)-1]) > terminalWidth { // break into lines
34-
lastIndex := len(rows) - 1
35-
lastOne := rows[lastIndex]
36-
rows[lastIndex] = rows[lastIndex][0:terminalWidth]
37-
rows = append(rows, contentPadding+lastOne[terminalWidth:])
49+
50+
rowPadding := strings.Repeat(" ", maxHeadLength)
51+
for content != "" {
52+
rowLen := min(contentRowLen, len(content))
53+
rows = append(rows, rowPadding+content[:rowLen])
54+
content = content[rowLen:]
3855
}
56+
3957
return strings.Join(rows, "\n")
4058
}

0 commit comments

Comments
 (0)