vendor/github.com/charmbracelet/lipgloss/README.md
765 lines · 20453 bytes
1# Lip Gloss
2
3<p>
4 <a href="https://stuff.charm.sh/lipgloss/lipgloss-mascot-2k.png"><img width="340" alt="Lip Gloss title treatment" src="https://github.com/charmbracelet/lipgloss/assets/25087/147cadb1-4254-43ec-ae6b-8d6ca7b029a1"></a><br>
5 <a href="https://github.com/charmbracelet/lipgloss/releases"><img src="https://img.shields.io/github/release/charmbracelet/lipgloss.svg" alt="Latest Release"></a>
6 <a href="https://pkg.go.dev/github.com/charmbracelet/lipgloss?tab=doc"><img src="https://godoc.org/github.com/golang/gddo?status.svg" alt="GoDoc"></a>
7 <a href="https://github.com/charmbracelet/lipgloss/actions"><img src="https://github.com/charmbracelet/lipgloss/workflows/build/badge.svg" alt="Build Status"></a>
8 <a href="https://www.phorm.ai/query?projectId=a0e324b6-b706-4546-b951-6671ea60c13f"><img src="https://stuff.charm.sh/misc/phorm-badge.svg" alt="phorm.ai"></a>
9</p>
10
11Style definitions for nice terminal layouts. Built with TUIs in mind.
12
13
14
15Lip Gloss takes an expressive, declarative approach to terminal rendering.
16Users familiar with CSS will feel at home with Lip Gloss.
17
18```go
19
20import "github.com/charmbracelet/lipgloss"
21
22var style = lipgloss.NewStyle().
23 Bold(true).
24 Foreground(lipgloss.Color("#FAFAFA")).
25 Background(lipgloss.Color("#7D56F4")).
26 PaddingTop(2).
27 PaddingLeft(4).
28 Width(22)
29
30fmt.Println(style.Render("Hello, kitty"))
31```
32
33## Colors
34
35Lip Gloss supports the following color profiles:
36
37### ANSI 16 colors (4-bit)
38
39```go
40lipgloss.Color("5") // magenta
41lipgloss.Color("9") // red
42lipgloss.Color("12") // light blue
43```
44
45### ANSI 256 Colors (8-bit)
46
47```go
48lipgloss.Color("86") // aqua
49lipgloss.Color("201") // hot pink
50lipgloss.Color("202") // orange
51```
52
53### True Color (16,777,216 colors; 24-bit)
54
55```go
56lipgloss.Color("#0000FF") // good ol' 100% blue
57lipgloss.Color("#04B575") // a green
58lipgloss.Color("#3C3C3C") // a dark gray
59```
60
61...as well as a 1-bit ASCII profile, which is black and white only.
62
63The terminal's color profile will be automatically detected, and colors outside
64the gamut of the current palette will be automatically coerced to their closest
65available value.
66
67### Adaptive Colors
68
69You can also specify color options for light and dark backgrounds:
70
71```go
72lipgloss.AdaptiveColor{Light: "236", Dark: "248"}
73```
74
75The terminal's background color will automatically be detected and the
76appropriate color will be chosen at runtime.
77
78### Complete Colors
79
80CompleteColor specifies exact values for True Color, ANSI256, and ANSI color
81profiles.
82
83```go
84lipgloss.CompleteColor{TrueColor: "#0000FF", ANSI256: "86", ANSI: "5"}
85```
86
87Automatic color degradation will not be performed in this case and it will be
88based on the color specified.
89
90### Complete Adaptive Colors
91
92You can use `CompleteColor` with `AdaptiveColor` to specify the exact values for
93light and dark backgrounds without automatic color degradation.
94
95```go
96lipgloss.CompleteAdaptiveColor{
97 Light: CompleteColor{TrueColor: "#d7ffae", ANSI256: "193", ANSI: "11"},
98 Dark: CompleteColor{TrueColor: "#d75fee", ANSI256: "163", ANSI: "5"},
99}
100```
101
102## Inline Formatting
103
104Lip Gloss supports the usual ANSI text formatting options:
105
106```go
107var style = lipgloss.NewStyle().
108 Bold(true).
109 Italic(true).
110 Faint(true).
111 Blink(true).
112 Strikethrough(true).
113 Underline(true).
114 Reverse(true)
115```
116
117## Block-Level Formatting
118
119Lip Gloss also supports rules for block-level formatting:
120
121```go
122// Padding
123var style = lipgloss.NewStyle().
124 PaddingTop(2).
125 PaddingRight(4).
126 PaddingBottom(2).
127 PaddingLeft(4)
128
129// Margins
130var style = lipgloss.NewStyle().
131 MarginTop(2).
132 MarginRight(4).
133 MarginBottom(2).
134 MarginLeft(4)
135```
136
137There is also shorthand syntax for margins and padding, which follows the same
138format as CSS:
139
140```go
141// 2 cells on all sides
142lipgloss.NewStyle().Padding(2)
143
144// 2 cells on the top and bottom, 4 cells on the left and right
145lipgloss.NewStyle().Margin(2, 4)
146
147// 1 cell on the top, 4 cells on the sides, 2 cells on the bottom
148lipgloss.NewStyle().Padding(1, 4, 2)
149
150// Clockwise, starting from the top: 2 cells on the top, 4 on the right, 3 on
151// the bottom, and 1 on the left
152lipgloss.NewStyle().Margin(2, 4, 3, 1)
153```
154
155## Aligning Text
156
157You can align paragraphs of text to the left, right, or center.
158
159```go
160var style = lipgloss.NewStyle().
161 Width(24).
162 Align(lipgloss.Left). // align it left
163 Align(lipgloss.Right). // no wait, align it right
164 Align(lipgloss.Center) // just kidding, align it in the center
165```
166
167## Width and Height
168
169Setting a minimum width and height is simple and straightforward.
170
171```go
172var style = lipgloss.NewStyle().
173 SetString("What’s for lunch?").
174 Width(24).
175 Height(32).
176 Foreground(lipgloss.Color("63"))
177```
178
179## Borders
180
181Adding borders is easy:
182
183```go
184// Add a purple, rectangular border
185var style = lipgloss.NewStyle().
186 BorderStyle(lipgloss.NormalBorder()).
187 BorderForeground(lipgloss.Color("63"))
188
189// Set a rounded, yellow-on-purple border to the top and left
190var anotherStyle = lipgloss.NewStyle().
191 BorderStyle(lipgloss.RoundedBorder()).
192 BorderForeground(lipgloss.Color("228")).
193 BorderBackground(lipgloss.Color("63")).
194 BorderTop(true).
195 BorderLeft(true)
196
197// Make your own border
198var myCuteBorder = lipgloss.Border{
199 Top: "._.:*:",
200 Bottom: "._.:*:",
201 Left: "|*",
202 Right: "|*",
203 TopLeft: "*",
204 TopRight: "*",
205 BottomLeft: "*",
206 BottomRight: "*",
207}
208```
209
210There are also shorthand functions for defining borders, which follow a similar
211pattern to the margin and padding shorthand functions.
212
213```go
214// Add a thick border to the top and bottom
215lipgloss.NewStyle().
216 Border(lipgloss.ThickBorder(), true, false)
217
218// Add a double border to the top and left sides. Rules are set clockwise
219// from top.
220lipgloss.NewStyle().
221 Border(lipgloss.DoubleBorder(), true, false, false, true)
222```
223
224For more on borders see [the docs][docs].
225
226## Copying Styles
227
228Just use assignment:
229
230```go
231style := lipgloss.NewStyle().Foreground(lipgloss.Color("219"))
232
233copiedStyle := style // this is a true copy
234
235wildStyle := style.Blink(true) // this is also true copy, with blink added
236
237```
238
239Since `Style` data structures contains only primitive types, assigning a style
240to another effectively creates a new copy of the style without mutating the
241original.
242
243## Inheritance
244
245Styles can inherit rules from other styles. When inheriting, only unset rules
246on the receiver are inherited.
247
248```go
249var styleA = lipgloss.NewStyle().
250 Foreground(lipgloss.Color("229")).
251 Background(lipgloss.Color("63"))
252
253// Only the background color will be inherited here, because the foreground
254// color will have been already set:
255var styleB = lipgloss.NewStyle().
256 Foreground(lipgloss.Color("201")).
257 Inherit(styleA)
258```
259
260## Unsetting Rules
261
262All rules can be unset:
263
264```go
265var style = lipgloss.NewStyle().
266 Bold(true). // make it bold
267 UnsetBold(). // jk don't make it bold
268 Background(lipgloss.Color("227")). // yellow background
269 UnsetBackground() // never mind
270```
271
272When a rule is unset, it won't be inherited or copied.
273
274## Enforcing Rules
275
276Sometimes, such as when developing a component, you want to make sure style
277definitions respect their intended purpose in the UI. This is where `Inline`
278and `MaxWidth`, and `MaxHeight` come in:
279
280```go
281// Force rendering onto a single line, ignoring margins, padding, and borders.
282someStyle.Inline(true).Render("yadda yadda")
283
284// Also limit rendering to five cells
285someStyle.Inline(true).MaxWidth(5).Render("yadda yadda")
286
287// Limit rendering to a 5x5 cell block
288someStyle.MaxWidth(5).MaxHeight(5).Render("yadda yadda")
289```
290
291## Tabs
292
293The tab character (`\t`) is rendered differently in different terminals (often
294as 8 spaces, sometimes 4). Because of this inconsistency, Lip Gloss converts
295tabs to 4 spaces at render time. This behavior can be changed on a per-style
296basis, however:
297
298```go
299style := lipgloss.NewStyle() // tabs will render as 4 spaces, the default
300style = style.TabWidth(2) // render tabs as 2 spaces
301style = style.TabWidth(0) // remove tabs entirely
302style = style.TabWidth(lipgloss.NoTabConversion) // leave tabs intact
303```
304
305## Rendering
306
307Generally, you just call the `Render(string...)` method on a `lipgloss.Style`:
308
309```go
310style := lipgloss.NewStyle().Bold(true).SetString("Hello,")
311fmt.Println(style.Render("kitty.")) // Hello, kitty.
312fmt.Println(style.Render("puppy.")) // Hello, puppy.
313```
314
315But you could also use the Stringer interface:
316
317```go
318var style = lipgloss.NewStyle().SetString("你好,猫咪。").Bold(true)
319fmt.Println(style) // 你好,猫咪。
320```
321
322### Custom Renderers
323
324Custom renderers allow you to render to a specific outputs. This is
325particularly important when you want to render to different outputs and
326correctly detect the color profile and dark background status for each, such as
327in a server-client situation.
328
329```go
330func myLittleHandler(sess ssh.Session) {
331 // Create a renderer for the client.
332 renderer := lipgloss.NewRenderer(sess)
333
334 // Create a new style on the renderer.
335 style := renderer.NewStyle().Background(lipgloss.AdaptiveColor{Light: "63", Dark: "228"})
336
337 // Render. The color profile and dark background state will be correctly detected.
338 io.WriteString(sess, style.Render("Heyyyyyyy"))
339}
340```
341
342For an example on using a custom renderer over SSH with [Wish][wish] see the
343[SSH example][ssh-example].
344
345## Utilities
346
347In addition to pure styling, Lip Gloss also ships with some utilities to help
348assemble your layouts.
349
350### Joining Paragraphs
351
352Horizontally and vertically joining paragraphs is a cinch.
353
354```go
355// Horizontally join three paragraphs along their bottom edges
356lipgloss.JoinHorizontal(lipgloss.Bottom, paragraphA, paragraphB, paragraphC)
357
358// Vertically join two paragraphs along their center axes
359lipgloss.JoinVertical(lipgloss.Center, paragraphA, paragraphB)
360
361// Horizontally join three paragraphs, with the shorter ones aligning 20%
362// from the top of the tallest
363lipgloss.JoinHorizontal(0.2, paragraphA, paragraphB, paragraphC)
364```
365
366### Measuring Width and Height
367
368Sometimes you’ll want to know the width and height of text blocks when building
369your layouts.
370
371```go
372// Render a block of text.
373var style = lipgloss.NewStyle().
374 Width(40).
375 Padding(2)
376var block string = style.Render(someLongString)
377
378// Get the actual, physical dimensions of the text block.
379width := lipgloss.Width(block)
380height := lipgloss.Height(block)
381
382// Here's a shorthand function.
383w, h := lipgloss.Size(block)
384```
385
386### Placing Text in Whitespace
387
388Sometimes you’ll simply want to place a block of text in whitespace.
389
390```go
391// Center a paragraph horizontally in a space 80 cells wide. The height of
392// the block returned will be as tall as the input paragraph.
393block := lipgloss.PlaceHorizontal(80, lipgloss.Center, fancyStyledParagraph)
394
395// Place a paragraph at the bottom of a space 30 cells tall. The width of
396// the text block returned will be as wide as the input paragraph.
397block := lipgloss.PlaceVertical(30, lipgloss.Bottom, fancyStyledParagraph)
398
399// Place a paragraph in the bottom right corner of a 30x80 cell space.
400block := lipgloss.Place(30, 80, lipgloss.Right, lipgloss.Bottom, fancyStyledParagraph)
401```
402
403You can also style the whitespace. For details, see [the docs][docs].
404
405## Rendering Tables
406
407Lip Gloss ships with a table rendering sub-package.
408
409```go
410import "github.com/charmbracelet/lipgloss/table"
411```
412
413Define some rows of data.
414
415```go
416rows := [][]string{
417 {"Chinese", "您好", "你好"},
418 {"Japanese", "こんにちは", "やあ"},
419 {"Arabic", "أهلين", "أهلا"},
420 {"Russian", "Здравствуйте", "Привет"},
421 {"Spanish", "Hola", "¿Qué tal?"},
422}
423```
424
425Use the table package to style and render the table.
426
427```go
428t := table.New().
429 Border(lipgloss.NormalBorder()).
430 BorderStyle(lipgloss.NewStyle().Foreground(lipgloss.Color("99"))).
431 StyleFunc(func(row, col int) lipgloss.Style {
432 switch {
433 case row == 0:
434 return HeaderStyle
435 case row%2 == 0:
436 return EvenRowStyle
437 default:
438 return OddRowStyle
439 }
440 }).
441 Headers("LANGUAGE", "FORMAL", "INFORMAL").
442 Rows(rows...)
443
444// You can also add tables row-by-row
445t.Row("English", "You look absolutely fabulous.", "How's it going?")
446```
447
448Print the table.
449
450```go
451fmt.Println(t)
452```
453
454
455
456For more on tables see [the docs](https://pkg.go.dev/github.com/charmbracelet/lipgloss?tab=doc) and [examples](https://github.com/charmbracelet/lipgloss/tree/master/examples/table).
457
458## Rendering Lists
459
460Lip Gloss ships with a list rendering sub-package.
461
462```go
463import "github.com/charmbracelet/lipgloss/list"
464```
465
466Define a new list.
467
468```go
469l := list.New("A", "B", "C")
470```
471
472Print the list.
473
474```go
475fmt.Println(l)
476
477// • A
478// • B
479// • C
480```
481
482Lists have the ability to nest.
483
484```go
485l := list.New(
486 "A", list.New("Artichoke"),
487 "B", list.New("Baking Flour", "Bananas", "Barley", "Bean Sprouts"),
488 "C", list.New("Cashew Apple", "Cashews", "Coconut Milk", "Curry Paste", "Currywurst"),
489 "D", list.New("Dill", "Dragonfruit", "Dried Shrimp"),
490 "E", list.New("Eggs"),
491 "F", list.New("Fish Cake", "Furikake"),
492 "J", list.New("Jicama"),
493 "K", list.New("Kohlrabi"),
494 "L", list.New("Leeks", "Lentils", "Licorice Root"),
495)
496```
497
498Print the list.
499
500```go
501fmt.Println(l)
502```
503
504<p align="center">
505<img width="600" alt="image" src="https://github.com/charmbracelet/lipgloss/assets/42545625/0dc9f440-0748-4151-a3b0-7dcf29dfcdb0">
506</p>
507
508Lists can be customized via their enumeration function as well as using
509`lipgloss.Style`s.
510
511```go
512enumeratorStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("99")).MarginRight(1)
513itemStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("212")).MarginRight(1)
514
515l := list.New(
516 "Glossier",
517 "Claire’s Boutique",
518 "Nyx",
519 "Mac",
520 "Milk",
521 ).
522 Enumerator(list.Roman).
523 EnumeratorStyle(enumeratorStyle).
524 ItemStyle(itemStyle)
525```
526
527Print the list.
528
529<p align="center">
530<img width="600" alt="List example" src="https://github.com/charmbracelet/lipgloss/assets/42545625/360494f1-57fb-4e13-bc19-0006efe01561">
531</p>
532
533In addition to the predefined enumerators (`Arabic`, `Alphabet`, `Roman`, `Bullet`, `Tree`),
534you may also define your own custom enumerator:
535
536```go
537l := list.New("Duck", "Duck", "Duck", "Duck", "Goose", "Duck", "Duck")
538
539func DuckDuckGooseEnumerator(l list.Items, i int) string {
540 if l.At(i).Value() == "Goose" {
541 return "Honk →"
542 }
543 return ""
544}
545
546l = l.Enumerator(DuckDuckGooseEnumerator)
547```
548
549Print the list:
550
551<p align="center">
552<img width="600" alt="image" src="https://github.com/charmbracelet/lipgloss/assets/42545625/157aaf30-140d-4948-9bb4-dfba46e5b87e">
553</p>
554
555If you need, you can also build lists incrementally:
556
557```go
558l := list.New()
559
560for i := 0; i < repeat; i++ {
561 l.Item("Lip Gloss")
562}
563```
564
565## Rendering Trees
566
567Lip Gloss ships with a tree rendering sub-package.
568
569```go
570import "github.com/charmbracelet/lipgloss/tree"
571```
572
573Define a new tree.
574
575```go
576t := tree.Root(".").
577 Child("A", "B", "C")
578```
579
580Print the tree.
581
582```go
583fmt.Println(t)
584
585// .
586// ├── A
587// ├── B
588// └── C
589```
590
591Trees have the ability to nest.
592
593```go
594t := tree.Root(".").
595 Child("macOS").
596 Child(
597 tree.New().
598 Root("Linux").
599 Child("NixOS").
600 Child("Arch Linux (btw)").
601 Child("Void Linux"),
602 ).
603 Child(
604 tree.New().
605 Root("BSD").
606 Child("FreeBSD").
607 Child("OpenBSD"),
608 )
609```
610
611Print the tree.
612
613```go
614fmt.Println(t)
615```
616
617<p align="center">
618<img width="663" alt="Tree Example (simple)" src="https://github.com/user-attachments/assets/5ef14eb8-a5d4-4f94-8834-e15d1e714f89">
619</p>
620
621Trees can be customized via their enumeration function as well as using
622`lipgloss.Style`s.
623
624```go
625enumeratorStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("63")).MarginRight(1)
626rootStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("35"))
627itemStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("212"))
628
629t := tree.
630 Root("⁜ Makeup").
631 Child(
632 "Glossier",
633 "Fenty Beauty",
634 tree.New().Child(
635 "Gloss Bomb Universal Lip Luminizer",
636 "Hot Cheeks Velour Blushlighter",
637 ),
638 "Nyx",
639 "Mac",
640 "Milk",
641 ).
642 Enumerator(tree.RoundedEnumerator).
643 EnumeratorStyle(enumeratorStyle).
644 RootStyle(rootStyle).
645 ItemStyle(itemStyle)
646```
647
648Print the tree.
649
650<p align="center">
651<img width="663" alt="Tree Example (makeup)" src="https://github.com/user-attachments/assets/06d12d87-744a-4c89-bd98-45de9094a97e">
652</p>
653
654The predefined enumerators for trees are `DefaultEnumerator` and `RoundedEnumerator`.
655
656If you need, you can also build trees incrementally:
657
658```go
659t := tree.New()
660
661for i := 0; i < repeat; i++ {
662 t.Child("Lip Gloss")
663}
664```
665
666---
667
668## FAQ
669
670<details>
671<summary>
672Why are things misaligning? Why are borders at the wrong widths?
673</summary>
674<p>This is most likely due to your locale and encoding, particularly with
675regard to Chinese, Japanese, and Korean (for example, <code>zh_CN.UTF-8</code>
676or <code>ja_JP.UTF-8</code>). The most direct way to fix this is to set
677<code>RUNEWIDTH_EASTASIAN=0</code> in your environment.</p>
678
679<p>For details see <a href="https://github.com/charmbracelet/lipgloss/issues/40">https://github.com/charmbracelet/lipgloss/issues/40.</a></p>
680</details>
681
682<details>
683<summary>
684Why isn't Lip Gloss displaying colors?
685</summary>
686<p>Lip Gloss automatically degrades colors to the best available option in the
687given terminal, and if output's not a TTY it will remove color output entirely.
688This is common when running tests, CI, or when piping output elsewhere.</p>
689
690<p>If necessary, you can force a color profile in your tests with
691<a href="https://pkg.go.dev/github.com/charmbracelet/lipgloss#SetColorProfile"><code>SetColorProfile</code></a>.</p>
692
693```go
694import (
695 "github.com/charmbracelet/lipgloss"
696 "github.com/muesli/termenv"
697)
698
699lipgloss.SetColorProfile(termenv.TrueColor)
700```
701
702_Note:_ this option limits the flexibility of your application and can cause
703ANSI escape codes to be output in cases where that might not be desired. Take
704careful note of your use case and environment before choosing to force a color
705profile.
706
707</details>
708
709## What about [Bubble Tea][tea]?
710
711Lip Gloss doesn’t replace Bubble Tea. Rather, it is an excellent Bubble Tea
712companion. It was designed to make assembling terminal user interface views as
713simple and fun as possible so that you can focus on building your application
714instead of concerning yourself with low-level layout details.
715
716In simple terms, you can use Lip Gloss to help build your Bubble Tea views.
717
718[tea]: https://github.com/charmbracelet/tea
719
720## Under the Hood
721
722Lip Gloss is built on the excellent [Termenv][termenv] and [Reflow][reflow]
723libraries which deal with color and ANSI-aware text operations, respectively.
724For many use cases Termenv and Reflow will be sufficient for your needs.
725
726[termenv]: https://github.com/muesli/termenv
727[reflow]: https://github.com/muesli/reflow
728
729## Rendering Markdown
730
731For a more document-centric rendering solution with support for things like
732lists, tables, and syntax-highlighted code have a look at [Glamour][glamour],
733the stylesheet-based Markdown renderer.
734
735[glamour]: https://github.com/charmbracelet/glamour
736
737## Contributing
738
739See [contributing][contribute].
740
741[contribute]: https://github.com/charmbracelet/lipgloss/contribute
742
743## Feedback
744
745We’d love to hear your thoughts on this project. Feel free to drop us a note!
746
747- [Twitter](https://twitter.com/charmcli)
748- [The Fediverse](https://mastodon.social/@charmcli)
749- [Discord](https://charm.sh/chat)
750
751## License
752
753[MIT](https://github.com/charmbracelet/lipgloss/raw/master/LICENSE)
754
755---
756
757Part of [Charm](https://charm.sh).
758
759<a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-badge.jpg" width="400"></a>
760
761Charm热爱开源 • Charm loves open source
762
763[docs]: https://pkg.go.dev/github.com/charmbracelet/lipgloss?tab=doc
764[wish]: https://github.com/charmbracelet/wish
765[ssh-example]: examples/ssh