11package argparse
22
33import (
4- "fmt"
54 "os"
65 "strings"
76
@@ -18,23 +17,31 @@ func decideTerminalWidth() int {
1817
1918func 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 )
25- }
26- contentPadding := strings .Repeat (" " , maxHeadLength )
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+
2727 var rows []string
28- if withBreak && headLeftPadding < 0 {
29- rows = append (rows , result , contentPadding + content )
28+ if withBreak {
29+ rows = append (rows , head )
3030 } else {
31- rows = append (rows , result + content )
31+ // no break -> head is on the same row
32+ // as first content line
33+ headRowPadding := strings .Repeat (" " , maxHeadLength - bareHeadLength )
34+ rowLen := min (contentRowLen , len (content ))
35+ rows = append (rows , head + headRowPadding + content [:rowLen ])
36+ content = content [rowLen :]
3237 }
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 :])
38+
39+ rowPadding := strings .Repeat (" " , maxHeadLength )
40+ for content != "" {
41+ rowLen := min (contentRowLen , len (content ))
42+ rows = append (rows , rowPadding + content [:rowLen ])
43+ content = content [rowLen :]
3844 }
45+
3946 return strings .Join (rows , "\n " )
4047}
0 commit comments