- Notifications
You must be signed in to change notification settings - Fork243
Style definitions for nice terminal layouts 👄
License
charmbracelet/lipgloss
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Style definitions for nice terminal layouts. Built with TUIs in mind.
Lip Gloss takes an expressive, declarative approach to terminal rendering.Users familiar with CSS will feel at home with Lip Gloss.
import"github.com/charmbracelet/lipgloss"varstyle=lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#FAFAFA")).Background(lipgloss.Color("#7D56F4")).PaddingTop(2).PaddingLeft(4).Width(22)fmt.Println(style.Render("Hello, kitty"))
Lip Gloss supports the following color profiles:
lipgloss.Color("5")// magentalipgloss.Color("9")// redlipgloss.Color("12")// light blue
lipgloss.Color("86")// aqualipgloss.Color("201")// hot pinklipgloss.Color("202")// orange
lipgloss.Color("#0000FF")// good ol' 100% bluelipgloss.Color("#04B575")// a greenlipgloss.Color("#3C3C3C")// a dark gray
...as well as a 1-bit ASCII profile, which is black and white only.
The terminal's color profile will be automatically detected, and colors outsidethe gamut of the current palette will be automatically coerced to their closestavailable value.
You can also specify color options for light and dark backgrounds:
lipgloss.AdaptiveColor{Light:"236",Dark:"248"}
The terminal's background color will automatically be detected and theappropriate color will be chosen at runtime.
CompleteColor specifies exact values for True Color, ANSI256, and ANSI colorprofiles.
lipgloss.CompleteColor{TrueColor:"#0000FF",ANSI256:"86",ANSI:"5"}
Automatic color degradation will not be performed in this case and it will bebased on the color specified.
You can useCompleteColor
withAdaptiveColor
to specify the exact values forlight and dark backgrounds without automatic color degradation.
lipgloss.CompleteAdaptiveColor{Light:CompleteColor{TrueColor:"#d7ffae",ANSI256:"193",ANSI:"11"},Dark:CompleteColor{TrueColor:"#d75fee",ANSI256:"163",ANSI:"5"},}
Lip Gloss supports the usual ANSI text formatting options:
varstyle=lipgloss.NewStyle().Bold(true).Italic(true).Faint(true).Blink(true).Strikethrough(true).Underline(true).Reverse(true)
Lip Gloss also supports rules for block-level formatting:
// Paddingvarstyle=lipgloss.NewStyle().PaddingTop(2).PaddingRight(4).PaddingBottom(2).PaddingLeft(4)// Marginsvarstyle=lipgloss.NewStyle().MarginTop(2).MarginRight(4).MarginBottom(2).MarginLeft(4)
There is also shorthand syntax for margins and padding, which follows the sameformat as CSS:
// 2 cells on all sideslipgloss.NewStyle().Padding(2)// 2 cells on the top and bottom, 4 cells on the left and rightlipgloss.NewStyle().Margin(2,4)// 1 cell on the top, 4 cells on the sides, 2 cells on the bottomlipgloss.NewStyle().Padding(1,4,2)// Clockwise, starting from the top: 2 cells on the top, 4 on the right, 3 on// the bottom, and 1 on the leftlipgloss.NewStyle().Margin(2,4,3,1)
You can align paragraphs of text to the left, right, or center.
varstyle=lipgloss.NewStyle().Width(24).Align(lipgloss.Left).// align it leftAlign(lipgloss.Right).// no wait, align it rightAlign(lipgloss.Center)// just kidding, align it in the center
Setting a minimum width and height is simple and straightforward.
varstyle=lipgloss.NewStyle().SetString("What’s for lunch?").Width(24).Height(32).Foreground(lipgloss.Color("63"))
Adding borders is easy:
// Add a purple, rectangular bordervarstyle=lipgloss.NewStyle().BorderStyle(lipgloss.NormalBorder()).BorderForeground(lipgloss.Color("63"))// Set a rounded, yellow-on-purple border to the top and leftvaranotherStyle=lipgloss.NewStyle().BorderStyle(lipgloss.RoundedBorder()).BorderForeground(lipgloss.Color("228")).BorderBackground(lipgloss.Color("63")).BorderTop(true).BorderLeft(true)// Make your own bordervarmyCuteBorder= lipgloss.Border{Top:"._.:*:",Bottom:"._.:*:",Left:"|*",Right:"|*",TopLeft:"*",TopRight:"*",BottomLeft:"*",BottomRight:"*",}
There are also shorthand functions for defining borders, which follow a similarpattern to the margin and padding shorthand functions.
// Add a thick border to the top and bottomlipgloss.NewStyle().Border(lipgloss.ThickBorder(),true,false)// Add a double border to the top and left sides. Rules are set clockwise// from top.lipgloss.NewStyle().Border(lipgloss.DoubleBorder(),true,false,false,true)
For more on borders seethe docs.
Just use assignment:
style:=lipgloss.NewStyle().Foreground(lipgloss.Color("219"))copiedStyle:=style// this is a true copywildStyle:=style.Blink(true)// this is also true copy, with blink added
SinceStyle
data structures contains only primitive types, assigning a styleto another effectively creates a new copy of the style without mutating theoriginal.
Styles can inherit rules from other styles. When inheriting, only unset ruleson the receiver are inherited.
varstyleA=lipgloss.NewStyle().Foreground(lipgloss.Color("229")).Background(lipgloss.Color("63"))// Only the background color will be inherited here, because the foreground// color will have been already set:varstyleB=lipgloss.NewStyle().Foreground(lipgloss.Color("201")).Inherit(styleA)
All rules can be unset:
varstyle=lipgloss.NewStyle().Bold(true).// make it boldUnsetBold().// jk don't make it boldBackground(lipgloss.Color("227")).// yellow backgroundUnsetBackground()// never mind
When a rule is unset, it won't be inherited or copied.
Sometimes, such as when developing a component, you want to make sure styledefinitions respect their intended purpose in the UI. This is whereInline
andMaxWidth
, andMaxHeight
come in:
// Force rendering onto a single line, ignoring margins, padding, and borders.someStyle.Inline(true).Render("yadda yadda")// Also limit rendering to five cellssomeStyle.Inline(true).MaxWidth(5).Render("yadda yadda")// Limit rendering to a 5x5 cell blocksomeStyle.MaxWidth(5).MaxHeight(5).Render("yadda yadda")
The tab character (\t
) is rendered differently in different terminals (oftenas 8 spaces, sometimes 4). Because of this inconsistency, Lip Gloss convertstabs to 4 spaces at render time. This behavior can be changed on a per-stylebasis, however:
style:=lipgloss.NewStyle()// tabs will render as 4 spaces, the defaultstyle=style.TabWidth(2)// render tabs as 2 spacesstyle=style.TabWidth(0)// remove tabs entirelystyle=style.TabWidth(lipgloss.NoTabConversion)// leave tabs intact
Generally, you just call theRender(string...)
method on alipgloss.Style
:
style:=lipgloss.NewStyle().Bold(true).SetString("Hello,")fmt.Println(style.Render("kitty."))// Hello, kitty.fmt.Println(style.Render("puppy."))// Hello, puppy.
But you could also use the Stringer interface:
varstyle=lipgloss.NewStyle().SetString("你好,猫咪。").Bold(true)fmt.Println(style)// 你好,猫咪。
Custom renderers allow you to render to a specific outputs. This isparticularly important when you want to render to different outputs andcorrectly detect the color profile and dark background status for each, such asin a server-client situation.
funcmyLittleHandler(sess ssh.Session) {// Create a renderer for the client.renderer:=lipgloss.NewRenderer(sess)// Create a new style on the renderer.style:=renderer.NewStyle().Background(lipgloss.AdaptiveColor{Light:"63",Dark:"228"})// Render. The color profile and dark background state will be correctly detected.io.WriteString(sess,style.Render("Heyyyyyyy"))}
For an example on using a custom renderer over SSH withWish see theSSH example.
In addition to pure styling, Lip Gloss also ships with some utilities to helpassemble your layouts.
Horizontally and vertically joining paragraphs is a cinch.
// Horizontally join three paragraphs along their bottom edgeslipgloss.JoinHorizontal(lipgloss.Bottom,paragraphA,paragraphB,paragraphC)// Vertically join two paragraphs along their center axeslipgloss.JoinVertical(lipgloss.Center,paragraphA,paragraphB)// Horizontally join three paragraphs, with the shorter ones aligning 20%// from the top of the tallestlipgloss.JoinHorizontal(0.2,paragraphA,paragraphB,paragraphC)
Sometimes you’ll want to know the width and height of text blocks when buildingyour layouts.
// Render a block of text.varstyle=lipgloss.NewStyle().Width(40).Padding(2)varblockstring=style.Render(someLongString)// Get the actual, physical dimensions of the text block.width:=lipgloss.Width(block)height:=lipgloss.Height(block)// Here's a shorthand function.w,h:=lipgloss.Size(block)
Sometimes you’ll simply want to place a block of text in whitespace.
// Center a paragraph horizontally in a space 80 cells wide. The height of// the block returned will be as tall as the input paragraph.block:=lipgloss.PlaceHorizontal(80,lipgloss.Center,fancyStyledParagraph)// Place a paragraph at the bottom of a space 30 cells tall. The width of// the text block returned will be as wide as the input paragraph.block:=lipgloss.PlaceVertical(30,lipgloss.Bottom,fancyStyledParagraph)// Place a paragraph in the bottom right corner of a 30x80 cell space.block:=lipgloss.Place(30,80,lipgloss.Right,lipgloss.Bottom,fancyStyledParagraph)
You can also style the whitespace. For details, seethe docs.
Lip Gloss ships with a table rendering sub-package.
import"github.com/charmbracelet/lipgloss/table"
Define some rows of data.
rows:= [][]string{ {"Chinese","您好","你好"}, {"Japanese","こんにちは","やあ"}, {"Arabic","أهلين","أهلا"}, {"Russian","Здравствуйте","Привет"}, {"Spanish","Hola","¿Qué tal?"},}
Use the table package to style and render the table.
var (purple=lipgloss.Color("99")gray=lipgloss.Color("245")lightGray=lipgloss.Color("241")headerStyle=lipgloss.NewStyle().Foreground(purple).Bold(true).Align(lipgloss.Center)cellStyle=lipgloss.NewStyle().Padding(0,1).Width(14)oddRowStyle=cellStyle.Foreground(gray)evenRowStyle=cellStyle.Foreground(lightGray))t:=table.New().Border(lipgloss.NormalBorder()).BorderStyle(lipgloss.NewStyle().Foreground(purple)).StyleFunc(func(row,colint) lipgloss.Style {switch {caserow==table.HeaderRow:returnheaderStylecaserow%2==0:returnevenRowStyledefault:returnoddRowStyle } }).Headers("LANGUAGE","FORMAL","INFORMAL").Rows(rows...)// You can also add tables row-by-rowt.Row("English","You look absolutely fabulous.","How's it going?")
Print the table.
fmt.Println(t)
Warning
TableRows
need to be declared beforeOffset
otherwise it does nothing.
There are helpers to generate tables in markdown or ASCII style:
table.New().Border(lipgloss.MarkdownBorder()).BorderTop(false).BorderBottom(false)
| LANGUAGE | FORMAL | INFORMAL ||----------|--------------|-----------|| Chinese | Nǐn hǎo | Nǐ hǎo || French | Bonjour | Salut || Russian | Zdravstvuyte | Privet || Spanish | Hola | ¿Qué tal? |
table.New().Border(lipgloss.ASCIIBorder())
+----------+--------------+-----------+| LANGUAGE | FORMAL | INFORMAL |+----------+--------------+-----------+| Chinese | Nǐn hǎo | Nǐ hǎo || French | Bonjour | Salut || Russian | Zdravstvuyte | Privet || Spanish | Hola | ¿Qué tal? |+----------+--------------+-----------+
For more on tables seethe docs andexamples.
Lip Gloss ships with a list rendering sub-package.
import"github.com/charmbracelet/lipgloss/list"
Define a new list.
l:=list.New("A","B","C")
Print the list.
fmt.Println(l)// • A// • B// • C
Lists have the ability to nest.
l:=list.New("A",list.New("Artichoke"),"B",list.New("Baking Flour","Bananas","Barley","Bean Sprouts"),"C",list.New("Cashew Apple","Cashews","Coconut Milk","Curry Paste","Currywurst"),"D",list.New("Dill","Dragonfruit","Dried Shrimp"),"E",list.New("Eggs"),"F",list.New("Fish Cake","Furikake"),"J",list.New("Jicama"),"K",list.New("Kohlrabi"),"L",list.New("Leeks","Lentils","Licorice Root"),)
Print the list.
fmt.Println(l)
Lists can be customized via their enumeration function as well as usinglipgloss.Style
s.
enumeratorStyle:=lipgloss.NewStyle().Foreground(lipgloss.Color("99")).MarginRight(1)itemStyle:=lipgloss.NewStyle().Foreground(lipgloss.Color("212")).MarginRight(1)l:=list.New("Glossier","Claire’s Boutique","Nyx","Mac","Milk", ).Enumerator(list.Roman).EnumeratorStyle(enumeratorStyle).ItemStyle(itemStyle)
Print the list.
In addition to the predefined enumerators (Arabic
,Alphabet
,Roman
,Bullet
,Tree
),you may also define your own custom enumerator:
l:=list.New("Duck","Duck","Duck","Duck","Goose","Duck","Duck")funcDuckDuckGooseEnumerator(l list.Items,iint)string {ifl.At(i).Value()=="Goose" {return"Honk →" }return""}l=l.Enumerator(DuckDuckGooseEnumerator)
Print the list:
If you need, you can also build lists incrementally:
l:=list.New()fori:=0;i<repeat;i++ {l.Item("Lip Gloss")}
Lip Gloss ships with a tree rendering sub-package.
import"github.com/charmbracelet/lipgloss/tree"
Define a new tree.
t:=tree.Root(".").Child("A","B","C")
Print the tree.
fmt.Println(t)// .// ├── A// ├── B// └── C
Trees have the ability to nest.
t:=tree.Root(".").Child("macOS").Child(tree.New().Root("Linux").Child("NixOS").Child("Arch Linux (btw)").Child("Void Linux"), ).Child(tree.New().Root("BSD").Child("FreeBSD").Child("OpenBSD"), )
Print the tree.
fmt.Println(t)
Trees can be customized via their enumeration function as well as usinglipgloss.Style
s.
enumeratorStyle:=lipgloss.NewStyle().Foreground(lipgloss.Color("63")).MarginRight(1)rootStyle:=lipgloss.NewStyle().Foreground(lipgloss.Color("35"))itemStyle:=lipgloss.NewStyle().Foreground(lipgloss.Color("212"))t:=tree.Root("⁜ Makeup").Child("Glossier","Fenty Beauty",tree.New().Child("Gloss Bomb Universal Lip Luminizer","Hot Cheeks Velour Blushlighter", ),"Nyx","Mac","Milk", ).Enumerator(tree.RoundedEnumerator).EnumeratorStyle(enumeratorStyle).RootStyle(rootStyle).ItemStyle(itemStyle)
Print the tree.
The predefined enumerators for trees areDefaultEnumerator
andRoundedEnumerator
.
If you need, you can also build trees incrementally:
t:=tree.New()fori:=0;i<repeat;i++ {t.Child("Lip Gloss")}
Why are things misaligning? Why are borders at the wrong widths?
This is most likely due to your locale and encoding, particularly withregard to Chinese, Japanese, and Korean (for example,zh_CN.UTF-8
orja_JP.UTF-8
). The most direct way to fix this is to setRUNEWIDTH_EASTASIAN=0
in your environment.
For details seehttps://github.com/charmbracelet/lipgloss/issues/40.
Why isn't Lip Gloss displaying colors?
Lip Gloss automatically degrades colors to the best available option in thegiven terminal, and if output's not a TTY it will remove color output entirely.This is common when running tests, CI, or when piping output elsewhere.
If necessary, you can force a color profile in your tests withSetColorProfile
.
import ("github.com/charmbracelet/lipgloss""github.com/muesli/termenv")lipgloss.SetColorProfile(termenv.TrueColor)
Note: this option limits the flexibility of your application and can causeANSI escape codes to be output in cases where that might not be desired. Takecareful note of your use case and environment before choosing to force a colorprofile.
What aboutBubble Tea?
Lip Gloss doesn’t replace Bubble Tea. Rather, it is an excellent Bubble Teacompanion. It was designed to make assembling terminal user interface views assimple and fun as possible so that you can focus on building your applicationinstead of concerning yourself with low-level layout details.
In simple terms, you can use Lip Gloss to help build your Bubble Tea views.
Lip Gloss is built on the excellentTermenv andReflowlibraries which deal with color and ANSI-aware text operations, respectively.For many use cases Termenv and Reflow will be sufficient for your needs.
For a more document-centric rendering solution with support for things likelists, tables, and syntax-highlighted code have a look atGlamour,the stylesheet-based Markdown renderer.
Seecontributing.
We’d love to hear your thoughts on this project. Feel free to drop us a note!
Part ofCharm.
Charm热爱开源 • Charm loves open source
About
Style definitions for nice terminal layouts 👄