Debian Codegraph @

tw/fn.go

raw
1 // Package tw provides utility functions for text formatting, width calculation, and string manipulation
2 // specifically tailored for table rendering, including handling ANSI escape codes and Unicode text.
3 package tw
4
5 import (
6 "math"
7 "strconv"
8 "strings"
9 "unicode"
10 "unicode/utf8"
11
12 "github.com/olekukonko/tablewriter/pkg/twwidth"
13 // For mathematical operations like ceiling
14 // For string-to-number conversions
15 // For string manipulation utilities
16 // For Unicode character classification
17 // For UTF-8 rune handling
18 )
19
20 // Title normalizes and uppercases a label string for use in headers.
21 // It replaces underscores and certain dots with spaces and trims whitespace.
22 func Title(name string) string {
23 origLen := len(name)
24 rs := []rune(name)
25 for i, r := range rs {
26 switch r {
27 case '_':
28 rs[i] = ' ' // Replace underscores with spaces
29 case '.':
30 // Replace dots with spaces unless they are between numeric or space characters
31 if (i != 0 && !IsIsNumericOrSpace(rs[i-1])) || (i != len(rs)-1 && !IsIsNumericOrSpace(rs[i+1])) {
32 rs[i] = ' '
33 }
34 }
35 }
36 name = string(rs)
37 name = strings.TrimSpace(name)
38 // If the input was non-empty but trimmed to empty, return a single space
39 if len(name) == 0 && origLen > 0 {
40 name = " "
41 }
42 // Convert to uppercase for header formatting
43 return strings.ToUpper(name)
44 }
45
46 // PadCenter centers a string within a specified width using a padding character.
47 // Extra padding is split between left and right, with slight preference to left if uneven.
48 func PadCenter(s, pad string, width int) string {
49 gap := width - twwidth.Width(s)
50 if gap > 0 {
51 // Calculate left and right padding; ceil ensures left gets extra if gap is odd
52 gapLeft := int(math.Ceil(float64(gap) / 2))
53 gapRight := gap - gapLeft
54 return strings.Repeat(pad, gapLeft) + s + strings.Repeat(pad, gapRight)
55 }
56 // If no padding needed or string is too wide, return as is
57 return s
58 }
59
60 // PadRight left-aligns a string within a specified width, filling remaining space on the right with padding.
61 func PadRight(s, pad string, width int) string {
62 gap := width - twwidth.Width(s)
63 if gap > 0 {
64 // Append padding to the right
65 return s + strings.Repeat(pad, gap)
66 }
67 // If no padding needed or string is too wide, return as is
68 return s
69 }
70
71 // PadLeft right-aligns a string within a specified width, filling remaining space on the left with padding.
72 func PadLeft(s, pad string, width int) string {
73 gap := width - twwidth.Width(s)
74 if gap > 0 {
75 // Prepend padding to the left
76 return strings.Repeat(pad, gap) + s
77 }
78 // If no padding needed or string is too wide, return as is
79 return s
80 }
81
82 // Pad aligns a string within a specified width using a padding character.
83 // It truncates if the string is wider than the target width.
84 func Pad(s, padChar string, totalWidth int, alignment Align) string {
85 sDisplayWidth := twwidth.Width(s)
86 if sDisplayWidth > totalWidth {
87 return twwidth.Truncate(s, totalWidth) // Only truncate if necessary
88 }
89 switch alignment {
90 case AlignLeft:
91 return PadRight(s, padChar, totalWidth)
92 case AlignRight:
93 return PadLeft(s, padChar, totalWidth)
94 case AlignCenter:
95 return PadCenter(s, padChar, totalWidth)
96 default:
97 return PadRight(s, padChar, totalWidth)
98 }
99 }
100
101 // IsIsNumericOrSpace checks if a rune is a digit or space character.
102 // Used in formatting logic to determine safe character replacements.
103 func IsIsNumericOrSpace(r rune) bool {
104 return ('0' <= r && r <= '9') || r == ' '
105 }
106
107 // IsNumeric checks if a string represents a valid integer or floating-point number.
108 func IsNumeric(s string) bool {
109 s = strings.TrimSpace(s)
110 if s == "" {
111 return false
112 }
113 // Try parsing as integer first
114 if _, err := strconv.Atoi(s); err == nil {
115 return true
116 }
117 // Then try parsing as float
118 _, err := strconv.ParseFloat(s, 64)
119 return err == nil
120 }
121
122 // SplitCamelCase splits a camelCase or PascalCase or snake_case string into separate words.
123 // It detects transitions between uppercase, lowercase, digits, and other characters.
124 func SplitCamelCase(src string) (entries []string) {
125 // Validate UTF-8 input; return as single entry if invalid
126 if !utf8.ValidString(src) {
127 return []string{src}
128 }
129 entries = []string{}
130 var runes [][]rune
131 lastClass := 0
132 class := 0
133 // Classify each rune into categories: lowercase (1), uppercase (2), digit (3), other (4)
134 for _, r := range src {
135 switch {
136 case unicode.IsLower(r):
137 class = 1
138 case unicode.IsUpper(r):
139 class = 2
140 case unicode.IsDigit(r):
141 class = 3
142 default:
143 class = 4
144 }
145 // Group consecutive runes of the same class together
146 if class == lastClass {
147 runes[len(runes)-1] = append(runes[len(runes)-1], r)
148 } else {
149 runes = append(runes, []rune{r})
150 }
151 lastClass = class
152 }
153 // Adjust for cases where an uppercase letter is followed by lowercase (e.g., CamelCase)
154 for i := 0; i < len(runes)-1; i++ {
155 if unicode.IsUpper(runes[i][0]) && unicode.IsLower(runes[i+1][0]) {
156 // Move the last uppercase rune to the next group for proper word splitting
157 runes[i+1] = append([]rune{runes[i][len(runes[i])-1]}, runes[i+1]...)
158 runes[i] = runes[i][:len(runes[i])-1]
159 }
160 }
161 // Convert rune groups to strings, excluding empty, underscore or whitespace-only groups
162 for _, s := range runes {
163 str := string(s)
164 if len(s) > 0 && strings.TrimSpace(str) != "" && str != "_" {
165 entries = append(entries, str)
166 }
167 }
168 return
169 }
170
171 // Or provides a ternary-like operation for strings, returning 'valid' if cond is true, else 'inValid'.
172 func Or(cond bool, valid, inValid string) string {
173 if cond {
174 return valid
175 }
176 return inValid
177 }
178
179 // Max returns the greater of two integers.
180 func Max(a, b int) int {
181 if a > b {
182 return a
183 }
184 return b
185 }
186
187 // Min returns the smaller of two integers.
188 func Min(a, b int) int {
189 if a < b {
190 return a
191 }
192 return b
193 }
194
195 // BreakPoint finds the rune index where the display width of a string first exceeds the specified limit.
196 // It returns the number of runes if the entire string fits, or 0 if nothing fits.
197 func BreakPoint(s string, limit int) int {
198 // If limit is 0 or negative, nothing can fit
199 if limit <= 0 {
200 return 0
201 }
202 // Empty string has a breakpoint of 0
203 if s == "" {
204 return 0
205 }
206
207 currentWidth := 0
208 runeCount := 0
209 // Iterate over runes, accumulating display width
210 for _, r := range s {
211 runeWidth := twwidth.Width(string(r)) // Calculate width of individual rune
212 if currentWidth+runeWidth > limit {
213 // Adding this rune would exceed the limit; breakpoint is before this rune
214 if currentWidth == 0 {
215 // First rune is too wide; allow breaking after it if limit > 0
216 if runeWidth > limit && limit > 0 {
217 return 1
218 }
219 return 0
220 }
221 return runeCount
222 }
223 currentWidth += runeWidth
224 runeCount++
225 }
226
227 // Entire string fits within the limit
228 return runeCount
229 }
230
231 func MakeAlign(l int, align Align) Alignment {
232 aa := make(Alignment, l)
233 for i := 0; i < l; i++ {
234 aa[i] = align
235 }
236 return aa
237 }