vendor/github.com/charmbracelet/lipgloss/style.go
587 lines · 13074 bytes
1package lipgloss
2
3import (
4 "strings"
5 "unicode"
6
7 "github.com/charmbracelet/x/ansi"
8 "github.com/muesli/termenv"
9)
10
11const tabWidthDefault = 4
12
13// Property for a key.
14type propKey int64
15
16// Available properties.
17const (
18 // Boolean props come first.
19 boldKey propKey = 1 << iota
20 italicKey
21 underlineKey
22 strikethroughKey
23 reverseKey
24 blinkKey
25 faintKey
26 underlineSpacesKey
27 strikethroughSpacesKey
28 colorWhitespaceKey
29
30 // Non-boolean props.
31 foregroundKey
32 backgroundKey
33 widthKey
34 heightKey
35 alignHorizontalKey
36 alignVerticalKey
37
38 // Padding.
39 paddingTopKey
40 paddingRightKey
41 paddingBottomKey
42 paddingLeftKey
43
44 // Margins.
45 marginTopKey
46 marginRightKey
47 marginBottomKey
48 marginLeftKey
49 marginBackgroundKey
50
51 // Border runes.
52 borderStyleKey
53
54 // Border edges.
55 borderTopKey
56 borderRightKey
57 borderBottomKey
58 borderLeftKey
59
60 // Border foreground colors.
61 borderTopForegroundKey
62 borderRightForegroundKey
63 borderBottomForegroundKey
64 borderLeftForegroundKey
65
66 // Border background colors.
67 borderTopBackgroundKey
68 borderRightBackgroundKey
69 borderBottomBackgroundKey
70 borderLeftBackgroundKey
71
72 inlineKey
73 maxWidthKey
74 maxHeightKey
75 tabWidthKey
76
77 transformKey
78)
79
80// props is a set of properties.
81type props int64
82
83// set sets a property.
84func (p props) set(k propKey) props {
85 return p | props(k)
86}
87
88// unset unsets a property.
89func (p props) unset(k propKey) props {
90 return p &^ props(k)
91}
92
93// has checks if a property is set.
94func (p props) has(k propKey) bool {
95 return p&props(k) != 0
96}
97
98// NewStyle returns a new, empty Style. While it's syntactic sugar for the
99// Style{} primitive, it's recommended to use this function for creating styles
100// in case the underlying implementation changes. It takes an optional string
101// value to be set as the underlying string value for this style.
102func NewStyle() Style {
103 return renderer.NewStyle()
104}
105
106// NewStyle returns a new, empty Style. While it's syntactic sugar for the
107// Style{} primitive, it's recommended to use this function for creating styles
108// in case the underlying implementation changes. It takes an optional string
109// value to be set as the underlying string value for this style.
110func (r *Renderer) NewStyle() Style {
111 s := Style{r: r}
112 return s
113}
114
115// Style contains a set of rules that comprise a style as a whole.
116type Style struct {
117 r *Renderer
118 props props
119 value string
120
121 // we store bool props values here
122 attrs int
123
124 // props that have values
125 fgColor TerminalColor
126 bgColor TerminalColor
127
128 width int
129 height int
130
131 alignHorizontal Position
132 alignVertical Position
133
134 paddingTop int
135 paddingRight int
136 paddingBottom int
137 paddingLeft int
138
139 marginTop int
140 marginRight int
141 marginBottom int
142 marginLeft int
143 marginBgColor TerminalColor
144
145 borderStyle Border
146 borderTopFgColor TerminalColor
147 borderRightFgColor TerminalColor
148 borderBottomFgColor TerminalColor
149 borderLeftFgColor TerminalColor
150 borderTopBgColor TerminalColor
151 borderRightBgColor TerminalColor
152 borderBottomBgColor TerminalColor
153 borderLeftBgColor TerminalColor
154
155 maxWidth int
156 maxHeight int
157 tabWidth int
158
159 transform func(string) string
160}
161
162// joinString joins a list of strings into a single string separated with a
163// space.
164func joinString(strs ...string) string {
165 return strings.Join(strs, " ")
166}
167
168// SetString sets the underlying string value for this style. To render once
169// the underlying string is set, use the Style.String. This method is
170// a convenience for cases when having a stringer implementation is handy, such
171// as when using fmt.Sprintf. You can also simply define a style and render out
172// strings directly with Style.Render.
173func (s Style) SetString(strs ...string) Style {
174 s.value = joinString(strs...)
175 return s
176}
177
178// Value returns the raw, unformatted, underlying string value for this style.
179func (s Style) Value() string {
180 return s.value
181}
182
183// String implements stringer for a Style, returning the rendered result based
184// on the rules in this style. An underlying string value must be set with
185// Style.SetString prior to using this method.
186func (s Style) String() string {
187 return s.Render()
188}
189
190// Copy returns a copy of this style, including any underlying string values.
191//
192// Deprecated: to copy just use assignment (i.e. a := b). All methods also
193// return a new style.
194func (s Style) Copy() Style {
195 return s
196}
197
198// Inherit overlays the style in the argument onto this style by copying each explicitly
199// set value from the argument style onto this style if it is not already explicitly set.
200// Existing set values are kept intact and not overwritten.
201//
202// Margins, padding, and underlying string values are not inherited.
203func (s Style) Inherit(i Style) Style {
204 for k := boldKey; k <= transformKey; k <<= 1 {
205 if !i.isSet(k) {
206 continue
207 }
208
209 switch k { //nolint:exhaustive
210 case marginTopKey, marginRightKey, marginBottomKey, marginLeftKey:
211 // Margins are not inherited
212 continue
213 case paddingTopKey, paddingRightKey, paddingBottomKey, paddingLeftKey:
214 // Padding is not inherited
215 continue
216 case backgroundKey:
217 // The margins also inherit the background color
218 if !s.isSet(marginBackgroundKey) && !i.isSet(marginBackgroundKey) {
219 s.set(marginBackgroundKey, i.bgColor)
220 }
221 }
222
223 if s.isSet(k) {
224 continue
225 }
226
227 s.setFrom(k, i)
228 }
229 return s
230}
231
232// Render applies the defined style formatting to a given string.
233func (s Style) Render(strs ...string) string {
234 if s.r == nil {
235 s.r = renderer
236 }
237 if s.value != "" {
238 strs = append([]string{s.value}, strs...)
239 }
240
241 var (
242 str = joinString(strs...)
243
244 p = s.r.ColorProfile()
245 te = p.String()
246 teSpace = p.String()
247 teWhitespace = p.String()
248
249 bold = s.getAsBool(boldKey, false)
250 italic = s.getAsBool(italicKey, false)
251 underline = s.getAsBool(underlineKey, false)
252 strikethrough = s.getAsBool(strikethroughKey, false)
253 reverse = s.getAsBool(reverseKey, false)
254 blink = s.getAsBool(blinkKey, false)
255 faint = s.getAsBool(faintKey, false)
256
257 fg = s.getAsColor(foregroundKey)
258 bg = s.getAsColor(backgroundKey)
259
260 width = s.getAsInt(widthKey)
261 height = s.getAsInt(heightKey)
262 horizontalAlign = s.getAsPosition(alignHorizontalKey)
263 verticalAlign = s.getAsPosition(alignVerticalKey)
264
265 topPadding = s.getAsInt(paddingTopKey)
266 rightPadding = s.getAsInt(paddingRightKey)
267 bottomPadding = s.getAsInt(paddingBottomKey)
268 leftPadding = s.getAsInt(paddingLeftKey)
269
270 colorWhitespace = s.getAsBool(colorWhitespaceKey, true)
271 inline = s.getAsBool(inlineKey, false)
272 maxWidth = s.getAsInt(maxWidthKey)
273 maxHeight = s.getAsInt(maxHeightKey)
274
275 underlineSpaces = s.getAsBool(underlineSpacesKey, false) || (underline && s.getAsBool(underlineSpacesKey, true))
276 strikethroughSpaces = s.getAsBool(strikethroughSpacesKey, false) || (strikethrough && s.getAsBool(strikethroughSpacesKey, true))
277
278 // Do we need to style whitespace (padding and space outside
279 // paragraphs) separately?
280 styleWhitespace = reverse
281
282 // Do we need to style spaces separately?
283 useSpaceStyler = (underline && !underlineSpaces) || (strikethrough && !strikethroughSpaces) || underlineSpaces || strikethroughSpaces
284
285 transform = s.getAsTransform(transformKey)
286 )
287
288 if transform != nil {
289 str = transform(str)
290 }
291
292 if s.props == 0 {
293 return s.maybeConvertTabs(str)
294 }
295
296 // Enable support for ANSI on the legacy Windows cmd.exe console. This is a
297 // no-op on non-Windows systems and on Windows runs only once.
298 enableLegacyWindowsANSI()
299
300 if bold {
301 te = te.Bold()
302 }
303 if italic {
304 te = te.Italic()
305 }
306 if underline {
307 te = te.Underline()
308 }
309 if reverse {
310 teWhitespace = teWhitespace.Reverse()
311 te = te.Reverse()
312 }
313 if blink {
314 te = te.Blink()
315 }
316 if faint {
317 te = te.Faint()
318 }
319
320 if fg != noColor {
321 te = te.Foreground(fg.color(s.r))
322 if styleWhitespace {
323 teWhitespace = teWhitespace.Foreground(fg.color(s.r))
324 }
325 if useSpaceStyler {
326 teSpace = teSpace.Foreground(fg.color(s.r))
327 }
328 }
329
330 if bg != noColor {
331 te = te.Background(bg.color(s.r))
332 if colorWhitespace {
333 teWhitespace = teWhitespace.Background(bg.color(s.r))
334 }
335 if useSpaceStyler {
336 teSpace = teSpace.Background(bg.color(s.r))
337 }
338 }
339
340 if underline {
341 te = te.Underline()
342 }
343 if strikethrough {
344 te = te.CrossOut()
345 }
346
347 if underlineSpaces {
348 teSpace = teSpace.Underline()
349 }
350 if strikethroughSpaces {
351 teSpace = teSpace.CrossOut()
352 }
353
354 // Potentially convert tabs to spaces
355 str = s.maybeConvertTabs(str)
356 // carriage returns can cause strange behaviour when rendering.
357 str = strings.ReplaceAll(str, "\r\n", "\n")
358
359 // Strip newlines in single line mode
360 if inline {
361 str = strings.ReplaceAll(str, "\n", "")
362 }
363
364 // Word wrap
365 if !inline && width > 0 {
366 wrapAt := width - leftPadding - rightPadding
367 str = ansi.Wrap(str, wrapAt, "")
368 }
369
370 // Render core text
371 {
372 var b strings.Builder
373
374 l := strings.Split(str, "\n")
375 for i := range l {
376 if useSpaceStyler {
377 // Look for spaces and apply a different styler
378 for _, r := range l[i] {
379 if unicode.IsSpace(r) {
380 b.WriteString(teSpace.Styled(string(r)))
381 continue
382 }
383 b.WriteString(te.Styled(string(r)))
384 }
385 } else {
386 b.WriteString(te.Styled(l[i]))
387 }
388 if i != len(l)-1 {
389 b.WriteRune('\n')
390 }
391 }
392
393 str = b.String()
394 }
395
396 // Padding
397 if !inline { //nolint:nestif
398 if leftPadding > 0 {
399 var st *termenv.Style
400 if colorWhitespace || styleWhitespace {
401 st = &teWhitespace
402 }
403 str = padLeft(str, leftPadding, st)
404 }
405
406 if rightPadding > 0 {
407 var st *termenv.Style
408 if colorWhitespace || styleWhitespace {
409 st = &teWhitespace
410 }
411 str = padRight(str, rightPadding, st)
412 }
413
414 if topPadding > 0 {
415 str = strings.Repeat("\n", topPadding) + str
416 }
417
418 if bottomPadding > 0 {
419 str += strings.Repeat("\n", bottomPadding)
420 }
421 }
422
423 // Height
424 if height > 0 {
425 str = alignTextVertical(str, verticalAlign, height, nil)
426 }
427
428 // Set alignment. This will also pad short lines with spaces so that all
429 // lines are the same length, so we run it under a few different conditions
430 // beyond alignment.
431 {
432 numLines := strings.Count(str, "\n")
433
434 if !(numLines == 0 && width == 0) {
435 var st *termenv.Style
436 if colorWhitespace || styleWhitespace {
437 st = &teWhitespace
438 }
439 str = alignTextHorizontal(str, horizontalAlign, width, st)
440 }
441 }
442
443 if !inline {
444 str = s.applyBorder(str)
445 str = s.applyMargins(str, inline)
446 }
447
448 // Truncate according to MaxWidth
449 if maxWidth > 0 {
450 lines := strings.Split(str, "\n")
451
452 for i := range lines {
453 lines[i] = ansi.Truncate(lines[i], maxWidth, "")
454 }
455
456 str = strings.Join(lines, "\n")
457 }
458
459 // Truncate according to MaxHeight
460 if maxHeight > 0 {
461 lines := strings.Split(str, "\n")
462 height := min(maxHeight, len(lines))
463 if len(lines) > 0 {
464 str = strings.Join(lines[:height], "\n")
465 }
466 }
467
468 return str
469}
470
471func (s Style) maybeConvertTabs(str string) string {
472 tw := tabWidthDefault
473 if s.isSet(tabWidthKey) {
474 tw = s.getAsInt(tabWidthKey)
475 }
476 switch tw {
477 case -1:
478 return str
479 case 0:
480 return strings.ReplaceAll(str, "\t", "")
481 default:
482 return strings.ReplaceAll(str, "\t", strings.Repeat(" ", tw))
483 }
484}
485
486func (s Style) applyMargins(str string, inline bool) string {
487 var (
488 topMargin = s.getAsInt(marginTopKey)
489 rightMargin = s.getAsInt(marginRightKey)
490 bottomMargin = s.getAsInt(marginBottomKey)
491 leftMargin = s.getAsInt(marginLeftKey)
492
493 styler termenv.Style
494 )
495
496 bgc := s.getAsColor(marginBackgroundKey)
497 if bgc != noColor {
498 styler = styler.Background(bgc.color(s.r))
499 }
500
501 // Add left and right margin
502 str = padLeft(str, leftMargin, &styler)
503 str = padRight(str, rightMargin, &styler)
504
505 // Top/bottom margin
506 if !inline {
507 _, width := getLines(str)
508 spaces := strings.Repeat(" ", width)
509
510 if topMargin > 0 {
511 str = styler.Styled(strings.Repeat(spaces+"\n", topMargin)) + str
512 }
513 if bottomMargin > 0 {
514 str += styler.Styled(strings.Repeat("\n"+spaces, bottomMargin))
515 }
516 }
517
518 return str
519}
520
521// Apply left padding.
522func padLeft(str string, n int, style *termenv.Style) string {
523 return pad(str, -n, style)
524}
525
526// Apply right padding.
527func padRight(str string, n int, style *termenv.Style) string {
528 return pad(str, n, style)
529}
530
531// pad adds padding to either the left or right side of a string.
532// Positive values add to the right side while negative values
533// add to the left side.
534func pad(str string, n int, style *termenv.Style) string {
535 if n == 0 {
536 return str
537 }
538
539 sp := strings.Repeat(" ", abs(n))
540 if style != nil {
541 sp = style.Styled(sp)
542 }
543
544 b := strings.Builder{}
545 l := strings.Split(str, "\n")
546
547 for i := range l {
548 switch {
549 // pad right
550 case n > 0:
551 b.WriteString(l[i])
552 b.WriteString(sp)
553 // pad left
554 default:
555 b.WriteString(sp)
556 b.WriteString(l[i])
557 }
558
559 if i != len(l)-1 {
560 b.WriteRune('\n')
561 }
562 }
563
564 return b.String()
565}
566
567func max(a, b int) int { //nolint:unparam,predeclared
568 if a > b {
569 return a
570 }
571 return b
572}
573
574func min(a, b int) int { //nolint:predeclared
575 if a < b {
576 return a
577 }
578 return b
579}
580
581func abs(a int) int {
582 if a < 0 {
583 return -a
584 }
585
586 return a
587}