Top Related Projects
🎨 Terminal color rendering library, support 8/16 colors, 256 colors, RGB color rendering output, support Print/Sprintf methods, compatible with Windows. GO CLI 控制台颜色渲染工具库,支持16色,256色,RGB色彩渲染输出,使用类似于 Print/Sprintf,兼容并支持 Windows 环境的色彩渲染
Advanced ANSI style & color support for your terminal applications
Golang terminal dashboard
Quick Overview
Lipgloss is a style library for terminal applications written in Go. It provides a simple and expressive API for styling text, creating boxes, and applying other visual effects to terminal output.
Pros
- Expressive API: Lipgloss offers a clean and intuitive API for applying styles to text, making it easy to create visually appealing terminal interfaces.
- Cross-platform Compatibility: The library works across different operating systems and terminal emulators, ensuring consistent styling across various environments.
- Customizable Styles: Users can easily create and apply custom styles to suit their specific needs, allowing for a high degree of design flexibility.
- Actively Maintained: The project is actively maintained by the Charm team, with regular updates and bug fixes.
Cons
- Limited Functionality: While Lipgloss provides a solid set of styling capabilities, it may not offer the full range of features found in more comprehensive terminal UI libraries.
- Dependency on Go: As a Go-based library, Lipgloss may not be as accessible to developers working in other programming languages.
- Learning Curve: The library's expressive API may have a slight learning curve for developers unfamiliar with Go or terminal styling.
- Performance Considerations: Depending on the complexity of the styles and the amount of text being rendered, Lipgloss may have some performance implications in high-throughput applications.
Code Examples
Here are a few examples of how to use Lipgloss in your Go projects:
- Applying Styles to Text:
import "github.com/charmbracelet/lipgloss"
text := lipgloss.NewStyle().
Foreground(lipgloss.Color("205")).
Background(lipgloss.Color("12")).
Padding(1, 2).
Render("Hello, Lipgloss!")
- Creating Boxes:
box := lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
Padding(1, 2).
Render("This is a box!")
- Combining Styles:
import "github.com/charmbracelet/lipgloss"
title := lipgloss.NewStyle().
Foreground(lipgloss.Color("205")).
Bold(true).
Render("My App")
subtitle := lipgloss.NewStyle().
Foreground(lipgloss.Color("4")).
Italic(true).
Render("A Lipgloss Example")
fmt.Println(lipgloss.JoinHorizontal(lipgloss.Center, title, subtitle))
- Applying Gradients:
gradient := lipgloss.NewStyle().
Foreground(lipgloss.AdaptiveColor{
Light: "205",
Dark: "12",
}).
Render("Gradient Text")
Getting Started
To get started with Lipgloss, you can install the library using Go's package manager:
go get github.com/charmbracelet/lipgloss
Once installed, you can import the library and start using it in your Go projects. Here's a simple example that demonstrates how to apply styles to text:
package main
import (
"fmt"
"github.com/charmbracelet/lipgloss"
)
func main() {
styled := lipgloss.NewStyle().
Foreground(lipgloss.Color("205")).
Background(lipgloss.Color("12")).
Padding(1, 2).
Render("Hello, Lipgloss!")
fmt.Println(styled)
}
To learn more about Lipgloss and its features, you can refer to the project's README and the documentation.
Competitor Comparisons
🎨 Terminal color rendering library, support 8/16 colors, 256 colors, RGB color rendering output, support Print/Sprintf methods, compatible with Windows. GO CLI 控制台颜色渲染工具库,支持16色,256色,RGB色彩渲染输出,使用类似于 Print/Sprintf,兼容并支持 Windows 环境的色彩渲染
Pros of Color
- More comprehensive color manipulation functions (RGB, HSL, CMYK)
- Supports a wider range of color formats and systems
- Includes color conversion utilities
Cons of Color
- Less focus on overall text styling and layout
- May have a steeper learning curve for basic use cases
- Lacks advanced text formatting features
Code Comparison
Lipgloss:
style := lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("#FAFAFA")).
Background(lipgloss.Color("#7D56F4"))
fmt.Println(style.Render("Hello, World!"))
Color:
text := color.Style{color.FgWhite, color.BgBlue, color.OpBold}.
Sprintf("Hello, World!")
fmt.Println(text)
Summary
Lipgloss focuses on overall text styling and layout, offering a more comprehensive solution for creating styled terminal UIs. It provides an intuitive API for combining various text styles and colors.
Color, on the other hand, specializes in color manipulation and offers more advanced color-related functions. It's better suited for applications that require detailed color processing but may be overkill for simple text styling needs.
Choose Lipgloss for elegant terminal UI styling with less complexity, or Color for more advanced color manipulation and a wider range of color formats.
Advanced ANSI style & color support for your terminal applications
Pros of termenv
- More focused on terminal environment detection and color support
- Provides direct access to low-level terminal capabilities
- Smaller and more lightweight library
Cons of termenv
- Less feature-rich for styling and layout compared to lipgloss
- Requires more manual work to create complex styled output
- Limited built-in styling functions
Code Comparison
termenv:
output := termenv.String("Hello, World!")
fmt.Println(output.Foreground(termenv.ColorProfile().Color("204")))
lipgloss:
style := lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("#04B575")).
Padding(1, 2)
fmt.Println(style.Render("Hello, World!"))
termenv focuses on providing low-level terminal capabilities and color support, while lipgloss offers a higher-level API for creating styled and formatted output. termenv is more lightweight and gives direct access to terminal features, but requires more manual work for complex styling. lipgloss, on the other hand, provides a more comprehensive set of styling and layout functions, making it easier to create sophisticated terminal UIs at the cost of a larger API surface.
Golang terminal dashboard
Pros of termui
- More comprehensive UI toolkit with pre-built widgets
- Better suited for complex, interactive terminal applications
- Supports real-time updates and event handling
Cons of termui
- Steeper learning curve due to more complex API
- Less flexibility for custom styling compared to lipgloss
- Heavier dependency with more code to include in projects
Code Comparison
termui example:
ui.NewPar("Hello World!")
ui.NewGauge()
ui.NewBarChart()
lipgloss example:
lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("#FAFAFA")).
Render("Hello World!")
termui focuses on providing ready-made UI components, while lipgloss emphasizes flexible styling of text-based elements. termui is better for building complex terminal UIs with various widgets, whereas lipgloss excels at creating custom-styled text output with a simpler API.
termui offers a more comprehensive solution for interactive terminal applications but comes with a steeper learning curve. lipgloss, on the other hand, provides a lightweight and flexible approach to styling text output, making it easier to integrate into existing projects for enhanced visual appeal.
Choose termui for feature-rich terminal applications with multiple interactive elements, and lipgloss for projects that require custom text styling with minimal overhead.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Lip Gloss
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"
var style = lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("#FAFAFA")).
Background(lipgloss.Color("#7D56F4")).
PaddingTop(2).
PaddingLeft(4).
Width(22)
fmt.Println(style.Render("Hello, kitty"))
Colors
Lip Gloss supports the following color profiles:
ANSI 16 colors (4-bit)
lipgloss.Color("5") // magenta
lipgloss.Color("9") // red
lipgloss.Color("12") // light blue
ANSI 256 Colors (8-bit)
lipgloss.Color("86") // aqua
lipgloss.Color("201") // hot pink
lipgloss.Color("202") // orange
True Color (16,777,216 colors; 24-bit)
lipgloss.Color("#0000FF") // good ol' 100% blue
lipgloss.Color("#04B575") // a green
lipgloss.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 outside the gamut of the current palette will be automatically coerced to their closest available value.
Adaptive Colors
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 the appropriate color will be chosen at runtime.
Complete Colors
CompleteColor specifies exact values for True Color, ANSI256, and ANSI color profiles.
lipgloss.CompleteColor{TrueColor: "#0000FF", ANSI256: "86", ANSI: "5"}
Automatic color degradation will not be performed in this case and it will be based on the color specified.
Complete Adaptive Colors
You can use CompleteColor
with AdaptiveColor
to specify the exact values for
light 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"},
}
Inline Formatting
Lip Gloss supports the usual ANSI text formatting options:
var style = lipgloss.NewStyle().
Bold(true).
Italic(true).
Faint(true).
Blink(true).
Strikethrough(true).
Underline(true).
Reverse(true)
Block-Level Formatting
Lip Gloss also supports rules for block-level formatting:
// Padding
var style = lipgloss.NewStyle().
PaddingTop(2).
PaddingRight(4).
PaddingBottom(2).
PaddingLeft(4)
// Margins
var style = lipgloss.NewStyle().
MarginTop(2).
MarginRight(4).
MarginBottom(2).
MarginLeft(4)
There is also shorthand syntax for margins and padding, which follows the same format as CSS:
// 2 cells on all sides
lipgloss.NewStyle().Padding(2)
// 2 cells on the top and bottom, 4 cells on the left and right
lipgloss.NewStyle().Margin(2, 4)
// 1 cell on the top, 4 cells on the sides, 2 cells on the bottom
lipgloss.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 left
lipgloss.NewStyle().Margin(2, 4, 3, 1)
Aligning Text
You can align paragraphs of text to the left, right, or center.
var style = lipgloss.NewStyle().
Width(24).
Align(lipgloss.Left). // align it left
Align(lipgloss.Right). // no wait, align it right
Align(lipgloss.Center) // just kidding, align it in the center
Width and Height
Setting a minimum width and height is simple and straightforward.
var style = lipgloss.NewStyle().
SetString("Whatâs for lunch?").
Width(24).
Height(32).
Foreground(lipgloss.Color("63"))
Borders
Adding borders is easy:
// Add a purple, rectangular border
var style = lipgloss.NewStyle().
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("63"))
// Set a rounded, yellow-on-purple border to the top and left
var anotherStyle = lipgloss.NewStyle().
BorderStyle(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("228")).
BorderBackground(lipgloss.Color("63")).
BorderTop(true).
BorderLeft(true)
// Make your own border
var myCuteBorder = lipgloss.Border{
Top: "._.:*:",
Bottom: "._.:*:",
Left: "|*",
Right: "|*",
TopLeft: "*",
TopRight: "*",
BottomLeft: "*",
BottomRight: "*",
}
There are also shorthand functions for defining borders, which follow a similar pattern to the margin and padding shorthand functions.
// Add a thick border to the top and bottom
lipgloss.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 see the docs.
Copying Styles
Just use assignment:
style := lipgloss.NewStyle().Foreground(lipgloss.Color("219"))
copiedStyle := style // this is a true copy
wildStyle := style.Blink(true) // this is also true copy, with blink added
Since Style
data structures contains only primitive types, assigning a style
to another effectively creates a new copy of the style without mutating the
original.
Inheritance
Styles can inherit rules from other styles. When inheriting, only unset rules on the receiver are inherited.
var styleA = 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:
var styleB = lipgloss.NewStyle().
Foreground(lipgloss.Color("201")).
Inherit(styleA)
Unsetting Rules
All rules can be unset:
var style = lipgloss.NewStyle().
Bold(true). // make it bold
UnsetBold(). // jk don't make it bold
Background(lipgloss.Color("227")). // yellow background
UnsetBackground() // never mind
When a rule is unset, it won't be inherited or copied.
Enforcing Rules
Sometimes, such as when developing a component, you want to make sure style
definitions respect their intended purpose in the UI. This is where Inline
and MaxWidth
, and MaxHeight
come in:
// Force rendering onto a single line, ignoring margins, padding, and borders.
someStyle.Inline(true).Render("yadda yadda")
// Also limit rendering to five cells
someStyle.Inline(true).MaxWidth(5).Render("yadda yadda")
// Limit rendering to a 5x5 cell block
someStyle.MaxWidth(5).MaxHeight(5).Render("yadda yadda")
Tabs
The tab character (\t
) is rendered differently in different terminals (often
as 8 spaces, sometimes 4). Because of this inconsistency, Lip Gloss converts
tabs to 4 spaces at render time. This behavior can be changed on a per-style
basis, however:
style := lipgloss.NewStyle() // tabs will render as 4 spaces, the default
style = style.TabWidth(2) // render tabs as 2 spaces
style = style.TabWidth(0) // remove tabs entirely
style = style.TabWidth(lipgloss.NoTabConversion) // leave tabs intact
Rendering
Generally, you just call the Render(string...)
method on a lipgloss.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:
var style = lipgloss.NewStyle().SetString("ä½ å¥½ï¼ç«åªã").Bold(true)
fmt.Println(style) // ä½ å¥½ï¼ç«åªã
Custom Renderers
Custom renderers allow you to render to a specific outputs. This is particularly important when you want to render to different outputs and correctly detect the color profile and dark background status for each, such as in a server-client situation.
func myLittleHandler(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 with Wish see the SSH example.
Utilities
In addition to pure styling, Lip Gloss also ships with some utilities to help assemble your layouts.
Joining Paragraphs
Horizontally and vertically joining paragraphs is a cinch.
// Horizontally join three paragraphs along their bottom edges
lipgloss.JoinHorizontal(lipgloss.Bottom, paragraphA, paragraphB, paragraphC)
// Vertically join two paragraphs along their center axes
lipgloss.JoinVertical(lipgloss.Center, paragraphA, paragraphB)
// Horizontally join three paragraphs, with the shorter ones aligning 20%
// from the top of the tallest
lipgloss.JoinHorizontal(0.2, paragraphA, paragraphB, paragraphC)
Measuring Width and Height
Sometimes youâll want to know the width and height of text blocks when building your layouts.
// Render a block of text.
var style = lipgloss.NewStyle().
Width(40).
Padding(2)
var block string = 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)
Placing Text in Whitespace
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, see the docs.
Rendering Tables
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.
t := table.New().
Border(lipgloss.NormalBorder()).
BorderStyle(lipgloss.NewStyle().Foreground(lipgloss.Color("99"))).
StyleFunc(func(row, col int) lipgloss.Style {
switch {
case row == 0:
return HeaderStyle
case row%2 == 0:
return EvenRowStyle
default:
return OddRowStyle
}
}).
Headers("LANGUAGE", "FORMAL", "INFORMAL").
Rows(rows...)
// You can also add tables row-by-row
t.Row("English", "You look absolutely fabulous.", "How's it going?")
Print the table.
fmt.Println(t)
For more on tables see the docs and examples.
Rendering Lists
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 using
lipgloss.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")
func DuckDuckGooseEnumerator(l list.Items, i int) string {
if l.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()
for i := 0; i < repeat; i++ {
l.Item("Lip Gloss")
}
Rendering Trees
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 using
lipgloss.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 are DefaultEnumerator
and RoundedEnumerator
.
If you need, you can also build trees incrementally:
t := tree.New()
for i := 0; i < repeat; i++ {
t.Child("Lip Gloss")
}
FAQ
Why are things misaligning? Why are borders at the wrong widths?
This is most likely due to your locale and encoding, particularly with
regard to Chinese, Japanese, and Korean (for example, zh_CN.UTF-8
or ja_JP.UTF-8
). The most direct way to fix this is to set
RUNEWIDTH_EASTASIAN=0
in your environment.
For details see https://github.com/charmbracelet/lipgloss/issues/40.
Why isn't Lip Gloss displaying colors?
Lip Gloss automatically degrades colors to the best available option in the given 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 with
SetColorProfile
.
import (
"github.com/charmbracelet/lipgloss"
"github.com/muesli/termenv"
)
lipgloss.SetColorProfile(termenv.TrueColor)
Note: this option limits the flexibility of your application and can cause ANSI escape codes to be output in cases where that might not be desired. Take careful note of your use case and environment before choosing to force a color profile.
What about Bubble Tea?
Lip Gloss doesnât replace Bubble Tea. Rather, it is an excellent Bubble Tea companion. It was designed to make assembling terminal user interface views as simple and fun as possible so that you can focus on building your application instead of concerning yourself with low-level layout details.
In simple terms, you can use Lip Gloss to help build your Bubble Tea views.
Under the Hood
Lip Gloss is built on the excellent Termenv and Reflow libraries which deal with color and ANSI-aware text operations, respectively. For many use cases Termenv and Reflow will be sufficient for your needs.
Rendering Markdown
For a more document-centric rendering solution with support for things like lists, tables, and syntax-highlighted code have a look at Glamour, the stylesheet-based Markdown renderer.
Feedback
Weâd love to hear your thoughts on this project. Feel free to drop us a note!
License
Part of Charm.
Charmçç±å¼æº ⢠Charm loves open source
Top Related Projects
🎨 Terminal color rendering library, support 8/16 colors, 256 colors, RGB color rendering output, support Print/Sprintf methods, compatible with Windows. GO CLI 控制台颜色渲染工具库,支持16色,256色,RGB色彩渲染输出,使用类似于 Print/Sprintf,兼容并支持 Windows 环境的色彩渲染
Advanced ANSI style & color support for your terminal applications
Golang terminal dashboard
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot