Debian Codegraph @

pkg/twwarp/wrap.go

raw
1 // Copyright 2014 Oleku Konko All rights reserved.
2 // Use of this source code is governed by a MIT
3 // license that can be found in the LICENSE file.
4
5 // This module is a Table Writer API for the Go Programming Language.
6 // The protocols were written in pure Go and works on windows and unix systems
7
8 package twwarp
9
10 import (
11 "math"
12 "strings"
13 "unicode"
14
15 "github.com/clipperhouse/uax29/v2/graphemes"
16 "github.com/olekukonko/tablewriter/pkg/twwidth"
17 )
18
19 const (
20 nl = "\n"
21 sp = " "
22 )
23
24 const defaultPenalty = 1e5
25
26 func SplitWords(s string) []string {
27 words := make([]string, 0, len(s)/5)
28 var wordBegin int
29 wordPending := false
30 for i, c := range s {
31 if unicode.IsSpace(c) {
32 if wordPending {
33 words = append(words, s[wordBegin:i])
34 wordPending = false
35 }
36 continue
37 }
38 if !wordPending {
39 wordBegin = i
40 wordPending = true
41 }
42 }
43 if wordPending {
44 words = append(words, s[wordBegin:])
45 }
46 return words
47 }
48
49 // WrapString wraps s into a paragraph of lines of length lim, with minimal
50 // raggedness.
51 func WrapString(s string, lim int) ([]string, int) {
52 if s == sp {
53 return []string{sp}, lim
54 }
55 words := SplitWords(s)
56 if len(words) == 0 {
57 return []string{""}, lim
58 }
59 var lines []string
60 max := 0
61 for _, v := range words {
62 max = twwidth.Width(v)
63 if max > lim {
64 lim = max
65 }
66 }
67 for _, line := range WrapWords(words, 1, lim, defaultPenalty) {
68 lines = append(lines, strings.Join(line, sp))
69 }
70 return lines, lim
71 }
72
73 // WrapStringWithSpaces wraps a string into lines of a specified display width while preserving
74 // leading and trailing spaces. It splits the input string into words, condenses internal multiple
75 // spaces to a single space, and wraps the content to fit within the given width limit, measured
76 // using Unicode-aware display width. The function is used in the logging library to format log
77 // messages for consistent output. It returns the wrapped lines as a slice of strings and the
78 // adjusted width limit, which may increase if a single word exceeds the input limit. Thread-safe
79 // as it does not modify shared state.
80 func WrapStringWithSpaces(s string, lim int) ([]string, int) {
81 if len(s) == 0 {
82 return []string{""}, lim
83 }
84 if strings.TrimSpace(s) == "" { // All spaces
85 if twwidth.Width(s) <= lim {
86 return []string{s}, twwidth.Width(s)
87 }
88 // For very long all-space strings, "wrap" by truncating to the limit.
89 if lim > 0 {
90 substring, _ := stringToDisplayWidth(s, lim)
91 return []string{substring}, lim
92 }
93 return []string{""}, lim
94 }
95
96 var leadingSpaces, trailingSpaces, coreContent string
97 firstNonSpace := strings.IndexFunc(s, func(r rune) bool { return !unicode.IsSpace(r) })
98 leadingSpaces = s[:firstNonSpace]
99 lastNonSpace := strings.LastIndexFunc(s, func(r rune) bool { return !unicode.IsSpace(r) })
100 trailingSpaces = s[lastNonSpace+1:]
101 coreContent = s[firstNonSpace : lastNonSpace+1]
102
103 if coreContent == "" {
104 return []string{leadingSpaces + trailingSpaces}, lim
105 }
106
107 words := SplitWords(coreContent)
108 if len(words) == 0 {
109 return []string{leadingSpaces + trailingSpaces}, lim
110 }
111
112 var lines []string
113 currentLim := lim
114
115 maxCoreWordWidth := 0
116 for _, v := range words {
117 w := twwidth.Width(v)
118 if w > maxCoreWordWidth {
119 maxCoreWordWidth = w
120 }
121 }
122
123 if maxCoreWordWidth > currentLim {
124 currentLim = maxCoreWordWidth
125 }
126
127 wrappedWordLines := WrapWords(words, 1, currentLim, defaultPenalty)
128
129 for i, lineWords := range wrappedWordLines {
130 joinedLine := strings.Join(lineWords, sp)
131 finalLine := leadingSpaces + joinedLine
132 if i == len(wrappedWordLines)-1 { // Last line
133 finalLine += trailingSpaces
134 }
135 lines = append(lines, finalLine)
136 }
137 return lines, currentLim
138 }
139
140 // stringToDisplayWidth returns a substring of s that has a display width
141 // as close as possible to, but not exceeding, targetWidth.
142 // It returns the substring and its actual display width.
143 func stringToDisplayWidth(s string, targetWidth int) (substring string, actualWidth int) {
144 if targetWidth <= 0 {
145 return "", 0
146 }
147
148 var currentWidth int
149 var endIndex int // Tracks the byte index in the original string
150
151 g := graphemes.FromString(s)
152 for g.Next() {
153 grapheme := g.Value()
154 graphemeWidth := twwidth.Width(grapheme)
155
156 if currentWidth+graphemeWidth > targetWidth {
157 break
158 }
159
160 currentWidth += graphemeWidth
161 endIndex = g.End()
162 }
163 return s[:endIndex], currentWidth
164 }
165
166 // WrapWords is the low-level line-breaking algorithm, useful if you need more
167 // control over the details of the text wrapping process. For most uses,
168 // WrapString will be sufficient and more convenient.
169 //
170 // WrapWords splits a list of words into lines with minimal "raggedness",
171 // treating each rune as one unit, accounting for spc units between adjacent
172 // words on each line, and attempting to limit lines to lim units. Raggedness
173 // is the total error over all lines, where error is the square of the
174 // difference of the length of the line and lim. Too-long lines (which only
175 // happen when a single word is longer than lim units) have pen penalty units
176 // added to the error.
177 func WrapWords(words []string, spc, lim, pen int) [][]string {
178 n := len(words)
179 if n == 0 {
180 return nil
181 }
182 lengths := make([]int, n)
183 for i := 0; i < n; i++ {
184 lengths[i] = twwidth.Width(words[i])
185 }
186 nbrk := make([]int, n)
187 cost := make([]int, n)
188 for i := range cost {
189 cost[i] = math.MaxInt32
190 }
191 remainderLen := lengths[n-1] // Uses updated lengths
192 for i := n - 1; i >= 0; i-- {
193 if i < n-1 {
194 remainderLen += spc + lengths[i]
195 }
196 // the last word has no following break to choose, so it must end the chain
197 if remainderLen <= lim || i == n-1 {
198 cost[i] = 0
199 nbrk[i] = n
200 continue
201 }
202 phraseLen := lengths[i]
203 for j := i + 1; j < n; j++ {
204 if j > i+1 {
205 phraseLen += spc + lengths[j-1]
206 }
207 d := lim - phraseLen
208 c := d*d + cost[j]
209 if phraseLen > lim {
210 c += pen // too-long lines get a worse penalty
211 }
212 if c < cost[i] {
213 cost[i] = c
214 nbrk[i] = j
215 }
216 }
217 }
218 var lines [][]string
219 i := 0
220 for i < n {
221 lines = append(lines, words[i:nbrk[i]])
222 i = nbrk[i]
223 }
224 return lines
225 }
226
227 // getLines decomposes a multiline string into a slice of strings.
228 func getLines(s string) []string {
229 return strings.Split(s, nl)
230 }