vendor/github.com/charmbracelet/lipgloss/style.go

585 lines · 12931 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
357	// Strip newlines in single line mode
358	if inline {
359		str = strings.ReplaceAll(str, "\n", "")
360	}
361
362	// Word wrap
363	if !inline && width > 0 {
364		wrapAt := width - leftPadding - rightPadding
365		str = ansi.Wrap(str, wrapAt, "")
366	}
367
368	// Render core text
369	{
370		var b strings.Builder
371
372		l := strings.Split(str, "\n")
373		for i := range l {
374			if useSpaceStyler {
375				// Look for spaces and apply a different styler
376				for _, r := range l[i] {
377					if unicode.IsSpace(r) {
378						b.WriteString(teSpace.Styled(string(r)))
379						continue
380					}
381					b.WriteString(te.Styled(string(r)))
382				}
383			} else {
384				b.WriteString(te.Styled(l[i]))
385			}
386			if i != len(l)-1 {
387				b.WriteRune('\n')
388			}
389		}
390
391		str = b.String()
392	}
393
394	// Padding
395	if !inline { //nolint:nestif
396		if leftPadding > 0 {
397			var st *termenv.Style
398			if colorWhitespace || styleWhitespace {
399				st = &teWhitespace
400			}
401			str = padLeft(str, leftPadding, st)
402		}
403
404		if rightPadding > 0 {
405			var st *termenv.Style
406			if colorWhitespace || styleWhitespace {
407				st = &teWhitespace
408			}
409			str = padRight(str, rightPadding, st)
410		}
411
412		if topPadding > 0 {
413			str = strings.Repeat("\n", topPadding) + str
414		}
415
416		if bottomPadding > 0 {
417			str += strings.Repeat("\n", bottomPadding)
418		}
419	}
420
421	// Height
422	if height > 0 {
423		str = alignTextVertical(str, verticalAlign, height, nil)
424	}
425
426	// Set alignment. This will also pad short lines with spaces so that all
427	// lines are the same length, so we run it under a few different conditions
428	// beyond alignment.
429	{
430		numLines := strings.Count(str, "\n")
431
432		if !(numLines == 0 && width == 0) {
433			var st *termenv.Style
434			if colorWhitespace || styleWhitespace {
435				st = &teWhitespace
436			}
437			str = alignTextHorizontal(str, horizontalAlign, width, st)
438		}
439	}
440
441	if !inline {
442		str = s.applyBorder(str)
443		str = s.applyMargins(str, inline)
444	}
445
446	// Truncate according to MaxWidth
447	if maxWidth > 0 {
448		lines := strings.Split(str, "\n")
449
450		for i := range lines {
451			lines[i] = ansi.Truncate(lines[i], maxWidth, "")
452		}
453
454		str = strings.Join(lines, "\n")
455	}
456
457	// Truncate according to MaxHeight
458	if maxHeight > 0 {
459		lines := strings.Split(str, "\n")
460		height := min(maxHeight, len(lines))
461		if len(lines) > 0 {
462			str = strings.Join(lines[:height], "\n")
463		}
464	}
465
466	return str
467}
468
469func (s Style) maybeConvertTabs(str string) string {
470	tw := tabWidthDefault
471	if s.isSet(tabWidthKey) {
472		tw = s.getAsInt(tabWidthKey)
473	}
474	switch tw {
475	case -1:
476		return str
477	case 0:
478		return strings.ReplaceAll(str, "\t", "")
479	default:
480		return strings.ReplaceAll(str, "\t", strings.Repeat(" ", tw))
481	}
482}
483
484func (s Style) applyMargins(str string, inline bool) string {
485	var (
486		topMargin    = s.getAsInt(marginTopKey)
487		rightMargin  = s.getAsInt(marginRightKey)
488		bottomMargin = s.getAsInt(marginBottomKey)
489		leftMargin   = s.getAsInt(marginLeftKey)
490
491		styler termenv.Style
492	)
493
494	bgc := s.getAsColor(marginBackgroundKey)
495	if bgc != noColor {
496		styler = styler.Background(bgc.color(s.r))
497	}
498
499	// Add left and right margin
500	str = padLeft(str, leftMargin, &styler)
501	str = padRight(str, rightMargin, &styler)
502
503	// Top/bottom margin
504	if !inline {
505		_, width := getLines(str)
506		spaces := strings.Repeat(" ", width)
507
508		if topMargin > 0 {
509			str = styler.Styled(strings.Repeat(spaces+"\n", topMargin)) + str
510		}
511		if bottomMargin > 0 {
512			str += styler.Styled(strings.Repeat("\n"+spaces, bottomMargin))
513		}
514	}
515
516	return str
517}
518
519// Apply left padding.
520func padLeft(str string, n int, style *termenv.Style) string {
521	return pad(str, -n, style)
522}
523
524// Apply right padding.
525func padRight(str string, n int, style *termenv.Style) string {
526	return pad(str, n, style)
527}
528
529// pad adds padding to either the left or right side of a string.
530// Positive values add to the right side while negative values
531// add to the left side.
532func pad(str string, n int, style *termenv.Style) string {
533	if n == 0 {
534		return str
535	}
536
537	sp := strings.Repeat(" ", abs(n))
538	if style != nil {
539		sp = style.Styled(sp)
540	}
541
542	b := strings.Builder{}
543	l := strings.Split(str, "\n")
544
545	for i := range l {
546		switch {
547		// pad right
548		case n > 0:
549			b.WriteString(l[i])
550			b.WriteString(sp)
551		// pad left
552		default:
553			b.WriteString(sp)
554			b.WriteString(l[i])
555		}
556
557		if i != len(l)-1 {
558			b.WriteRune('\n')
559		}
560	}
561
562	return b.String()
563}
564
565func max(a, b int) int { //nolint:unparam
566	if a > b {
567		return a
568	}
569	return b
570}
571
572func min(a, b int) int {
573	if a < b {
574		return a
575	}
576	return b
577}
578
579func abs(a int) int {
580	if a < 0 {
581		return -a
582	}
583
584	return a
585}