### Basic Writer Setup Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Initialize a new colorprofile writer using standard output and environment variables. ```go import ( "fmt" "os" "github.com/charmbracelet/colorprofile" ) func main() { w := colorprofile.NewWriter(os.Stdout, os.Environ()) // Use fmt.Fprintf with the writer fmt.Fprintf(w, "This is \x1b[38;2;255;0;0mred text\x1b[m\n") } ``` -------------------------------- ### Example 24-Bit Foreground Colors Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/ansi-reference.md Examples of setting red, green, and blue foreground colors using 24-bit sequences. ```text \x1b[38;2;255;0;0m Red foreground \x1b[38;2;0;255;0m Green foreground \x1b[38;2;0;0;255m Blue foreground ``` -------------------------------- ### Detect color profile usage examples Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/detection.md Demonstrates how to detect color profiles for standard output, standard error, and custom environment configurations. ```go import ( "fmt" "os" "github.com/charmbracelet/colorprofile" ) // Detect for stdout p := colorprofile.Detect(os.Stdout, os.Environ()) fmt.Printf("Detected profile: %s\n", p) // Detect for stderr p = colorprofile.Detect(os.Stderr, os.Environ()) fmt.Printf("Stderr profile: %s\n", p) // Use custom environment (for testing) env := []string{"TERM=xterm-256color", "COLORTERM="} p = colorprofile.Detect(os.Stdout, env) fmt.Printf("Custom env profile: %s\n", p) ``` -------------------------------- ### Install Terminfo in Dockerfile Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Ensure the terminfo database is available within a Docker container for accurate color detection. ```dockerfile FROM ubuntu:latest # Container inherits TERM from host # But may lack terminfo database # Solution: Install terminfo in Dockerfile RUN apt-get update && apt-get install -y ncurses-bin # Now colorprofile can query terminfo ``` -------------------------------- ### SGR Parameter Examples Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/behavior-reference.md Common SGR parameter sequences for text styling and color. ```text \x1b[m Reset all attributes \x1b[0m Reset all attributes \x1b[1m Bold \x1b[31m Foreground red \x1b[38;5;196m 256-color foreground (color 196) \x1b[38;2;255;0;0m TrueColor red (RGB) \x1b[48;2;0;255;0m TrueColor green background \x1b[1;31;42m Bold, red foreground, green background ``` -------------------------------- ### Environment Variable Boolean Examples Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/behavior-reference.md Shell commands demonstrating how various environment variable settings are interpreted as boolean values. ```bash export NO_COLOR=0 # Treats as FALSE (colors enabled) export NO_COLOR= # Treats as FALSE (empty, not set) unset NO_COLOR # FALSE (not set at all) export NO_COLOR=1 # TRUE export NO_COLOR=yes # TRUE ``` -------------------------------- ### Check ANSICON Version Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Verify the installed version of the ANSICON console emulator. ```bash # Check ANSICON version echo $ANSICON_VER ``` -------------------------------- ### Detecting Tmux Color Profile Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/detection.md Example usage of the Tmux function to determine color support based on environment variables. ```go import ( "fmt" "os" "github.com/charmbracelet/colorprofile" ) // When inside tmux env := os.Environ() p := colorprofile.Tmux(env) fmt.Printf("Tmux profile: %s\n", p) // When not in tmux env = []string{"TERM=xterm"} p = colorprofile.Tmux(env) fmt.Printf("Not in tmux: %s\n", p) // Output: NoTTY ``` -------------------------------- ### Writer.Write() Usage Example Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/behavior-reference.md Demonstrates how the Writer returns the length of the input buffer regardless of the actual bytes written to the underlying buffer after downsampling. ```go var buf bytes.Buffer w := &colorprofile.Writer{ Forward: &buf, Profile: colorprofile.ASCII, } input := []byte("\x1b[31mRed\x1b[m") // 12 bytes n, err := w.Write(input) fmt.Println(n) // 12 (input length) fmt.Println(buf.String()) // "Red" (3 bytes) fmt.Println(buf.Len()) // 3 (actual bytes written to Forward) ``` -------------------------------- ### Downsampling Behavior by Profile Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/behavior-reference.md Examples of how TrueColor input is converted across different color profiles. ```text Input: \x1b[38;2;255;0;0mRed\x1b[m Output: \x1b[38;2;255;0;0mRed\x1b[m (unchanged) ``` ```text Input: \x1b[38;2;255;0;0mRed\x1b[m Output: \x1b[38;5;196mRed\x1b[m (converted to 256-color) ``` ```text Input: \x1b[38;2;255;0;0mRed\x1b[m Output: \x1b[31mRed\x1b[m (converted to 4-bit red) ``` ```text Input: \x1b[38;2;255;0;0mRed\x1b[m Output: Red (all codes stripped) ``` -------------------------------- ### NO_COLOR Precedence Behavior Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/behavior-reference.md Examples showing how the NO_COLOR environment variable affects terminal profile detection. ```text TERM=xterm-256color, NO_COLOR=1 → Detected profile: ASCII (colors disabled) → But bold/italic/underline still work TERM=dumb, NO_COLOR=1 → Detected profile: NoTTY (already no colors) → NO_COLOR has no additional effect ``` -------------------------------- ### Comparison Operations Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/behavior-reference.md Examples of comparison operations between different color profiles. ```text ASCII < ANSI256 TrueColor > ANSI ANSI == ANSI ANSI256 <= TrueColor ``` -------------------------------- ### Create and Configure Writer Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/types.md Initializes a new writer and demonstrates modifying the profile at runtime. ```go w := colorprofile.NewWriter(os.Stdout, os.Environ()) ``` ```go w.Profile = colorprofile.ANSI256 ``` -------------------------------- ### Integrate with Standard log Package Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Configures the standard library log package to use a colorprofile writer for output. ```go import ( "log" "os" "github.com/charmbracelet/colorprofile" ) func main() { w := colorprofile.NewWriter(os.Stderr, os.Environ()) logger := log.New(w, "[APP] ", log.LstdFlags) logger.Printf("\x1b[31mError message\x1b[m") } ``` -------------------------------- ### Detecting Profiles and Writing Colors in Go Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/exports-summary.md Demonstrates how to detect terminal color profiles from environment variables and use the writer to output ANSI-encoded colors. ```go import ( "fmt" "os" "image/color" "github.com/charmbracelet/colorprofile" ) // Detect profile p := colorprofile.Detect(os.Stdout, os.Environ()) fmt.Printf("Profile: %s\n", p) // Create a Writer w := colorprofile.NewWriter(os.Stdout, os.Environ()) fmt.Fprintf(w, "\x1b[31mRed\x1b[m\n") // Convert colors c := color.RGBA{255, 0, 0, 255} converted := p.Convert(c) ``` -------------------------------- ### Initialize NewWriter Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/writer.md Creates a writer for stdout with automatic profile detection. ```go import ( "os" "github.com/charmbracelet/colorprofile" ) // Create a writer for stdout with automatic profile detection w := colorprofile.NewWriter(os.Stdout, os.Environ()) // Write ANSI escape sequences; they'll be automatically downsampled fmt.Fprintf(w, "\x1b[38;2;107;80;255mColorful text\x1b[m\n") ``` -------------------------------- ### View project file structure Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/README.md Displays the directory layout of the colorprofile project documentation. ```text output/ ├── README.md (this file) ├── api-reference/ │ ├── profile.md Profile type and methods │ ├── writer.md Writer type and methods │ └── detection.md Detection functions (Detect, Env, Terminfo, Tmux) ├── types.md Type definitions and interfaces ├── exports-summary.md Complete API inventory ├── configuration.md Environment variables and configuration ├── architecture.md Internal design and algorithms ├── behavior-reference.md Detailed behavior specifications ├── ansi-reference.md ANSI escape sequences and downsampling ├── usage-examples.md Code examples and patterns └── terminal-support-guide.md Terminal capabilities and compatibility ``` -------------------------------- ### Implement Custom Logging Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Wraps a colorprofile writer within a custom struct to provide formatted logging methods. ```go type Logger struct { writer *colorprofile.Writer } func NewLogger() *Logger { return &Logger{ writer: colorprofile.NewWriter(os.Stderr, os.Environ()), } } func (l *Logger) Error(msg string) { fmt.Fprintf(l.writer, "\x1b[31m[ERROR]\x1b[m %s\n", msg) } func (l *Logger) Info(msg string) { fmt.Fprintf(l.writer, "\x1b[32m[INFO]\x1b[m %s\n", msg) } ``` -------------------------------- ### Platform Build Tags Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/architecture.md Build constraints used to separate Unix-like and Windows implementations. ```go //go:build !windows ``` ```go //go:build windows ``` -------------------------------- ### Convert Colors to ANSI Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/types.md Demonstrates converting TrueColor to indexed or basic ANSI color types. ```go import ( "image/color" "github.com/charmbracelet/colorprofile" "github.com/charmbracelet/x/ansi" ) // TrueColor input trueColor := color.RGBA{R: 0x6b, G: 0x50, B: 0xff, A: 0xff} // Convert to ANSI256 returns IndexedColor converted := colorprofile.ANSI256.Convert(trueColor) if ic, ok := converted.(ansi.IndexedColor); ok { fmt.Printf("Indexed color: %d\n", ic) } // Convert to ANSI returns BasicColor converted = colorprofile.ANSI.Convert(trueColor) if bc, ok := converted.(ansi.BasicColor); ok { fmt.Printf("Basic color: %d\n", bc) } ``` -------------------------------- ### Handle Nil Color Conversion Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/ansi-reference.md Demonstrates that converting colors to an ASCII profile returns nil when no color support is available. ```go // For ASCII profile converted := colorprofile.ASCII.Convert(color.RGBA{255, 0, 0, 255}) // Returns nil (no color support) ``` -------------------------------- ### Profile.String() Method Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/profile.md Returns the string representation of a Profile. ```go func (p Profile) String() string ``` ```go p := colorprofile.TrueColor fmt.Println(p.String()) // Output: TrueColor p = colorprofile.ANSI fmt.Println(p.String()) // Output: ANSI ``` -------------------------------- ### Implement io.Writer Interface Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/exports-summary.md Any type implementing this interface can be wrapped by colorprofile.Writer. ```go type Writer interface { Write(p []byte) (n int, err error) } ``` -------------------------------- ### Profile.Convert() Method Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/profile.md Converts a color to a format supported by the profile, returning nil for profiles without color support. ```go func (p Profile) Convert(c color.Color) (cc color.Color) ``` ```go import ( "image/color" "github.com/charmbracelet/colorprofile" ) // Define a true color c := color.RGBA{0x6b, 0x50, 0xff, 0xff} // #6b50ff (purple) // Convert to 256-color palette ansi256Color := colorprofile.ANSI256.Convert(c) // Result: ansi.IndexedColor (approximately 55 or 63) // Convert to 16-color palette ansiColor := colorprofile.ANSI.Convert(c) // Result: ansi.BasicColor (color 5 - magenta) // TrueColor returns the original trueColor := colorprofile.TrueColor.Convert(c) // Result: color.RGBA{0x6b, 0x50, 0xff, 0xff} // ASCII and NoTTY return nil noColor := colorprofile.ASCII.Convert(c) // Result: nil ``` -------------------------------- ### Import Path for colorprofile Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/exports-summary.md The package import path for the colorprofile library. ```go github.com/charmbracelet/colorprofile ``` -------------------------------- ### Define Writer.Write method Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/writer.md Signature for the Write method. ```go func (w *Writer) Write(p []byte) (int, error) ``` -------------------------------- ### Fallback for Non-TTY Environments Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Checks the profile type to determine if colors are supported or if a plain text fallback is required. ```go w := colorprofile.NewWriter(os.Stdout, os.Environ()) if w.Profile == colorprofile.NoTTY { // Output is not a TTY, use plain text writer instead fmt.Fprintf(os.Stdout, "Plain text message\n") } else { // Can use colors fmt.Fprintf(w, "\x1b[32mGreen message\x1b[m\n") } ``` -------------------------------- ### Handle Different Profiles Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Uses a switch statement to handle logic based on the detected color profile. ```go import "github.com/charmbracelet/colorprofile" p := colorprofile.Detect(os.Stdout, os.Environ()) switch p { case colorprofile.TrueColor: fmt.Println("Full 24-bit color support") case colorprofile.ANSI256: fmt.Println("256-color support") case colorprofile.ANSI: fmt.Println("16-color support") case colorprofile.ASCII: fmt.Println("No colors (text only)") case colorprofile.NoTTY: fmt.Println("Non-TTY output (no colors)") } ``` -------------------------------- ### Windows Build Version Detection Logic Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/configuration.md Maps Windows NT build versions to specific color profile capabilities. ```text Windows Build Version -> Profile ├─ < 10586 (or major < 10) with ANSICON -> ANSI or ANSI256 ├─ < 10586 (or major < 10) without ANSICON -> NoTTY ├─ >= 10586 and < 14931 -> ANSI256 (no true color) └─ >= 14931 -> TrueColor ``` -------------------------------- ### Detect with Custom Environment Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Overrides environment variables to simulate specific terminal capabilities. ```go env := []string{ "TERM=xterm-256color", "COLORTERM=truecolor", } p := colorprofile.Detect(os.Stdout, env) ``` -------------------------------- ### Query terminfo for TrueColor capabilities Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Use infocmp to verify if the current terminal or a specific entry supports Tc or RGB capabilities. ```bash # Check if your terminal has TrueColor capability infocmp | grep -E "Tc|RGB" # Load specific terminal infocmp xterm-256color | grep -E "Tc|RGB" ``` -------------------------------- ### Handle Write Errors in Go Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Demonstrates checking for errors when writing to a colorprofile writer. ```go w := colorprofile.NewWriter(os.Stdout, os.Environ()) n, err := w.Write([]byte("\x1b[31mRed\x1b[m\n")) if err != nil { log.Fatalf("Write failed: %v", err) } fmt.Printf("Wrote %d bytes\n", n) ``` -------------------------------- ### Configure Color Override Options Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Provide environment variables to allow users to force color output regardless of detection. ```bash # Allow users to force colors export CLICOLOR_FORCE=1 # Or use your own environment variable export MY_APP_FORCE_COLOR=1 ``` -------------------------------- ### WriteString Alternative Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Use the WriteString method for efficient string-based output. ```go w := colorprofile.NewWriter(os.Stdout, os.Environ()) // Use WriteString for string input n, err := w.WriteString("\x1b[1;32mBold green\x1b[m\n") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Detect() Algorithm Logic Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/architecture.md The primary orchestration logic for determining terminal color support. ```text 1. Check if output is TTY (term.IsTerminal or TTY_FORCE) 2. Check TERM environment variable 3. If TERM=dumb, tentatively set NoTTY 4. Get environment-based profile (envColorProfile) 5. If NO_COLOR env var: cap at ASCII 6. If CLICOLOR_FORCE: guarantee minimum ANSI 7. If TTY and not dumb: consult terminfo and tmux 8. Return max(env, terminfo, tmux) ``` -------------------------------- ### Windows Color Profile Detection Signature Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/architecture.md Function signature for Windows-specific terminal color detection logic. ```go func windowsColorProfile(env map[string]string) (Profile, bool) ``` -------------------------------- ### Multi-Byte Color Parameter Processing Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/behavior-reference.md Demonstrates how the writer processes extended color parameters and downsamples them. ```go Input: []byte("\x1b[38;2;255;0;0;1m") (RGB foreground, then bold) Processing: - Param 38: Extended foreground - Param 2: RGB format - Params 255,0,0: RGB values - Param 1: Bold Output after ANSI profile downsampling: "\x1b[31;1m" (red 4-bit + bold) ``` -------------------------------- ### Respect NO_COLOR Environment Variable Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Check if color conversion returns nil to handle cases where NO_COLOR is set or the terminal does not support colors. ```go // If colorprofile.Detect returns ASCII, respect NO_COLOR if p.Convert(someColor) == nil { // Colors were stripped due to NO_COLOR or non-color terminal // Use plain text styling (bold, italic) if available } ``` -------------------------------- ### CLICOLOR_FORCE Semantics Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/behavior-reference.md Scenarios demonstrating how CLICOLOR_FORCE upgrades terminal capabilities. ```text Scenario 1: TERM=dumb, CLICOLOR_FORCE=1 → Upgraded from NoTTY to ANSI Scenario 2: TERM=dumb, CLICOLOR_FORCE=1, COLORTERM=truecolor → Upgraded to TrueColor (maximum from COLORTERM) Scenario 3: TERM=xterm-256color, CLICOLOR_FORCE=1 → Stays ANSI256 (already >= ANSI from CLICOLOR_FORCE) Scenario 4: No TERM, CLICOLOR_FORCE=1 → Upgraded to ANSI (or higher if COLORTERM set) ``` -------------------------------- ### Changing Profile at Runtime Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Manually override the detected color profile to force specific output formats or disable colors. ```go w := colorprofile.NewWriter(os.Stdout, os.Environ()) fancy := "\x1b[38;2;107;80;255mCute puppy!!\x1b[m" // Write with detected profile fmt.Fprintf(w, "Auto: %s\n", fancy) // Override to 16-color ANSI w.Profile = colorprofile.ANSI fmt.Fprintf(w, "4-bit: %s\n", fancy) // Disable colors entirely w.Profile = colorprofile.ASCII fmt.Fprintf(w, "No color: %s\n", fancy) ``` -------------------------------- ### NewWriter() Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/writer.md Creates a new Writer instance that automatically detects the color profile based on the provided writer and environment variables. ```APIDOC ## func NewWriter(w io.Writer, environ []string) *Writer ### Description Creates a new Writer that automatically downgrades ANSI escape sequences based on the detected color profile. ### Parameters - **w** (io.Writer) - Required - The writer to wrap (typically os.Stdout or os.Stderr). - **environ** ([]string) - Required - Environment variables as a slice of "KEY=VALUE" strings, typically from os.Environ(). ### Return Type *Writer ``` -------------------------------- ### Profile.String() Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/profile.md Returns the string representation of a Profile, such as 'TrueColor', 'ANSI256', or 'ANSI'. ```APIDOC ## func (p Profile) String() string ### Description Returns the string representation of a Profile. ### Parameters - **p** (Profile) - Required - The profile to stringify ### Return Type - **string** - The name of the profile (e.g., "TrueColor", "ANSI256", "ANSI", "Ascii", "NoTTY", or "Unknown") ``` -------------------------------- ### Detect Profile from Environment Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/exports-summary.md Detects the color profile from environment variables only, assuming a TTY. ```go func Env(env []string) Profile ``` -------------------------------- ### Force TrueColor via Environment Variables Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Configure environment variables to force TrueColor output, including handling for dumb terminals. ```bash # Option 1: Set COLORTERM export COLORTERM=truecolor # Option 2: Use CLICOLOR_FORCE on dumb terminal export TERM=dumb export CLICOLOR_FORCE=1 export COLORTERM=truecolor # Result: TrueColor ``` -------------------------------- ### Profile.Convert() Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/profile.md Converts a given color to a color supported within the Profile, applying quantization where necessary. ```APIDOC ## func (p Profile) Convert(c color.Color) (cc color.Color) ### Description Converts a given color to a color supported within the Profile. Returns a color compatible with the profile, or nil if the profile does not support colors. ### Parameters - **p** (Profile) - Required - The target color profile - **c** (color.Color) - Required - The color to convert ### Return Type - **color.Color** - A color compatible with the profile, or nil for ASCII/NoTTY profiles. ``` -------------------------------- ### Define NewWriter function Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/writer.md Signature for creating a new Writer instance. ```go func NewWriter(w io.Writer, environ []string) *Writer ``` -------------------------------- ### Stub Windows Color Profile Implementation Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/architecture.md Stub implementation for non-Windows platforms where Windows-specific detection is disabled. ```go func windowsColorProfile(map[string]string) (Profile, bool) { return 0, false // Stub implementation } ``` -------------------------------- ### Standard Color Interface Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/types.md The interface used for all color inputs in the package. ```go type Color interface { RGBA() (r, g, b, a uint32) } ``` -------------------------------- ### Document Color Support Output Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Provide users with clear information regarding detected color profiles and how to override them. ```text Detected profile: TrueColor (16 million colors) Set COLORTERM=truecolor to enable true colors Set NO_COLOR=1 to disable colors entirely ``` -------------------------------- ### Using Environment-Only Detection Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Detect color capabilities based on provided environment variables without checking the TTY. ```go // Detect from environment variables without checking TTY env := []string{ "TERM=xterm-256color", "COLORTERM=truecolor", } p := colorprofile.Env(env) fmt.Printf("Env-based profile: %s\n", p) ``` -------------------------------- ### Use Writer.Write Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/writer.md Writes data to the underlying writer, downsampling ANSI color sequences based on the Writer's Profile. ```go import ( "fmt" "os" "github.com/charmbracelet/colorprofile" ) w := colorprofile.NewWriter(os.Stdout, os.Environ()) // Input with 24-bit color (TrueColor) ansiText := "\x1b[38;2;107;80;255mPurple text\x1b[m" // Write downgrades based on terminal capability w.Write([]byte(ansiText)) // If terminal supports TrueColor: outputs as-is // If terminal supports 256 colors: converts to 256-color code // If terminal supports 16 colors: converts to 4-bit ANSI color // If terminal supports no colors: strips all codes, outputs plain text ``` -------------------------------- ### func Detect(output io.Writer, env []string) Profile Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/exports-summary.md Detects the color profile based on the provided writer and environment variables. ```APIDOC ## func Detect(output io.Writer, env []string) Profile ### Description Detects the color profile based on the writer and environment variables. ### Parameters - **output** (io.Writer) - The writer to inspect - **env** ([]string) - Environment variables ### Returns - **Profile** - Detected color profile ``` -------------------------------- ### Detect() Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/detection.md Detects the color profile of a terminal based on the provided writer and environment variables. ```APIDOC ## Detect(output, env) ### Description Detects the color profile of a terminal based on the writer and environment variables. Returns one of the five profile constants: TrueColor, ANSI256, ANSI, ASCII, or NoTTY. ### Parameters - **output** (io.Writer) - Required - The writer to inspect (typically os.Stdout or os.Stderr) - **env** ([]string) - Required - Environment variables as a slice of "KEY=VALUE" strings ### Return Type - **Profile** (constant) - The detected color profile ### Example ```go import ( "fmt" "os" "github.com/charmbracelet/colorprofile" ) // Detect for stdout p := colorprofile.Detect(os.Stdout, os.Environ()) fmt.Printf("Detected profile: %s\n", p) ``` ``` -------------------------------- ### Profile.Convert Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/exports-summary.md Converts a color to the target profile's color space. ```APIDOC ## func (p Profile) Convert(c color.Color) color.Color ### Description Converts a given color to the color space supported by the profile. ### Parameters - **c** (color.Color) - Required - The source color to convert. ### Returns - **color.Color** - The converted color. ``` -------------------------------- ### Verify TrueColor support in tmux Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Check the tmux configuration for Tc or RGB capabilities using the tmux info command. ```bash tmux info | grep -E "Tc|RGB" ``` -------------------------------- ### Query Terminfo Capabilities Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/behavior-reference.md Use this command to verify which color capabilities are reported by the current terminal's terminfo entry. ```bash infocmp $TERM | grep -E "Tc|RGB" ``` -------------------------------- ### Diagnose Missing TrueColor Support Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Run these commands to inspect terminal capabilities and environment variables when colors fail to render. ```bash # Check detected profile your-app | head -1 # If app prints detection # Check TERM echo $TERM # Check COLORTERM echo $COLORTERM # Check if TTY [ -t 1 ] && echo "TTY" || echo "Not TTY" # Check terminfo infocmp | grep -E "Tc|RGB" # If in tmux tmux info | grep -E "Tc|RGB" ``` -------------------------------- ### Define Writer.WriteString method Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/writer.md Signature for the WriteString method. ```go func (w *Writer) WriteString(s string) (n int, err error) ``` -------------------------------- ### General ANSI Sequence Format Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/ansi-reference.md The standard structure for Control Sequence Introducer (CSI) commands. ```text CSI (Control Sequence Introducer) + Parameters + Command Letter ``` ```text \x1b[m ``` -------------------------------- ### Profile Constants Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/profile.md Constants representing different levels of terminal color support. ```go const ( Unknown Profile = iota // Absence of a profile NoTTY // No terminal support ASCII // No color support ANSI // 16 colors (4-bit) ANSI256 // 256 colors (8-bit) TrueColor // 16 million colors (24-bit) ) ``` -------------------------------- ### Convert Color to Profile Support Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/exports-summary.md Converts a color to one supported by the profile. ```go func (p Profile) Convert(c color.Color) color.Color ``` -------------------------------- ### Checking Terminfo Capabilities Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Query the terminfo database to determine the color support of a specific terminal identifier. ```go // Query terminfo database for specific terminal p := colorprofile.Terminfo("xterm-kitty") if p == colorprofile.TrueColor { fmt.Println("Kitty supports TrueColor via Tc/RGB capability") } ``` -------------------------------- ### Configure CLICOLOR variable Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/configuration.md Enables color output when TERM is not defined or is unrecognized. ```bash CLICOLOR= ``` ```bash unset TERM export CLICOLOR=1 # colorprofile will detect ANSI profile (if TTY) ``` -------------------------------- ### Detecting Tmux Capabilities Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Check color support specifically when running inside a tmux session. ```go // When inside tmux, check its capabilities env := os.Environ() p := colorprofile.Tmux(env) fmt.Printf("Tmux color support: %s\n", p) ``` -------------------------------- ### Set 8-Bit Background Color Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/ansi-reference.md Sets the background color using the 256-color palette. ```text \x1b[48;5;m ``` -------------------------------- ### func Env(env []string) Profile Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/detection.md Detects the color profile based solely on environment variables, assuming a TTY environment. ```APIDOC ## func Env(env []string) Profile ### Description Detects the color profile based solely on environment variables, assuming a TTY environment. This function does not inspect the actual writer or check if output is a TTY. ### Parameters - **env** ([]string) - Required - Environment variables as a slice of "KEY=VALUE" strings ### Returns - **Profile** - One of the five profile constants based on the provided environment variables. ``` -------------------------------- ### Environment Variable Splitting Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/behavior-reference.md The logic used to split environment variable strings on the first equals sign. ```go parts := strings.SplitN(e, "=", 2) ``` -------------------------------- ### Detect Google Cloud Shell Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/configuration.md Setting GOOGLE_CLOUD_SHELL to 1 upgrades the profile to TrueColor. ```text GOOGLE_CLOUD_SHELL=1 ``` -------------------------------- ### Use Writer.WriteString Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/writer.md Writes a string to the underlying writer, downsampling ANSI color sequences. ```go import ( "github.com/charmbracelet/colorprofile" "os" ) w := colorprofile.NewWriter(os.Stdout, os.Environ()) w.WriteString("\x1b[38;2;200;50;100mRed text\x1b[m\n") ``` -------------------------------- ### Profile Capability Ordering Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/behavior-reference.md The hierarchy of color profiles from least to most capable. ```text NoTTY (1) < ASCII (2) < ANSI (3) < ANSI256 (4) < TrueColor (5) ``` -------------------------------- ### Max Capability Selection Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/behavior-reference.md Using the max function to determine the highest capability among multiple profile sources. ```go // Return the maximum (most capable) profile profile := max(envProfile, max(terminfoProfile, tmuxProfile)) ``` ```go // Environment says ANSI, terminfo says TrueColor, tmux says ANSI256 // Result: TrueColor (highest capability) ``` -------------------------------- ### Define Writer Struct Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/types.md Wraps an io.Writer to perform automatic color downsampling based on a profile. ```go type Writer struct { Forward io.Writer // The underlying writer Profile Profile // The color profile for downsampling } ``` -------------------------------- ### Set 8-Bit Foreground Color Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/ansi-reference.md Use this sequence to set the foreground color using the 256-color palette index. ```text \x1b[38;5;m ``` -------------------------------- ### Configure Remote Host Terminal Environment Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Update the TERM or COLORTERM variables on a remote host to ensure proper color support. ```bash # On remote host, update TERM if needed export TERM=xterm-256color # Or add to ~/.profile or ~/.bashrc on remote host if [ -z "$COLORTERM" ]; then export COLORTERM=truecolor fi ``` -------------------------------- ### Check TTY Status with colorprofile Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Use colorprofile.Detect to determine if the output is a TTY before applying ANSI color codes. ```go if p := colorprofile.Detect(os.Stdout, os.Environ()); p == colorprofile.NoTTY { // Non-TTY output: use plain text fmt.Fprintf(os.Stdout, "Plain message\n") } else { // TTY: safe to use colors fmt.Fprintf(os.Stdout, "\x1b[32mColored message\x1b[m\n") } ``` -------------------------------- ### func (Profile) String() Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/exports-summary.md Returns the string representation of a Profile. ```APIDOC ## func (Profile) String() ### Description Returns the string representation of a Profile. ### Signature `func (p Profile) String() string` ``` -------------------------------- ### Convert Colors Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Converts an RGB color to the detected profile or a specific manual profile. ```go import ( "fmt" "image/color" "github.com/charmbracelet/colorprofile" ) // Create a 24-bit RGB color c := color.RGBA{R: 0x6b, G: 0x50, B: 0xff, A: 0xff} // Convert to detected profile p := colorprofile.Detect(os.Stdout, os.Environ()) converted := p.Convert(c) fmt.Printf("Original: %v\n", c) fmt.Printf("Converted: %v\n", converted) ``` ```go c := color.RGBA{R: 255, G: 100, B: 50, A: 255} ansi256 := colorprofile.ANSI256.Convert(c) ansi16 := colorprofile.ANSI.Convert(c) noColor := colorprofile.ASCII.Convert(c) fmt.Printf("256-color: %v\n", ansi256) fmt.Printf("16-color: %v\n", ansi16) fmt.Printf("No color: %v\n", noColor) ``` -------------------------------- ### Change Writer Profile at Runtime Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/writer.md The Profile field is exported and can be modified to change downsampling behavior dynamically. ```go import ( "fmt" "os" "github.com/charmbracelet/colorprofile" ) w := colorprofile.NewWriter(os.Stdout, os.Environ()) fancy := "\x1b[38;2;107;80;255mCute puppy!!\x1b[m" // Write with detected profile fmt.Fprintf(w, "Terminal: %s\n", fancy) // Change profile to 4-bit ANSI w.Profile = colorprofile.ANSI fmt.Fprintf(w, "4-bit: %s\n", fancy) // Change profile to no colors w.Profile = colorprofile.ASCII fmt.Fprintf(w, "No color: %s\n", fancy) // Change profile to no ANSI at all w.Profile = colorprofile.NoTTY fmt.Fprintf(w, "Plain text: %s\n", fancy) ``` -------------------------------- ### Configure TERM variable Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/configuration.md Sets the terminal type identifier to determine base color capabilities. ```bash TERM= ``` ```bash export TERM=xterm-256color # colorprofile will detect ANSI256 export TERM=alacritty # colorprofile will detect TrueColor export TERM=dumb # colorprofile will detect NoTTY (unless CLICOLOR_FORCE=1) ``` -------------------------------- ### Ascii Alias Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/profile.md Backwards compatibility alias for the ASCII profile. ```go const Ascii = ASCII ``` -------------------------------- ### Optimize Docker Environment Variables Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Set environment variables in a Dockerfile to improve terminal compatibility. ```bash # Install terminfo package RUN apt-get install -y ncurses-bin # Or explicitly set COLORTERM ENV COLORTERM=truecolor # Or use well-known terminal identifiers ENV TERM=xterm-256color ``` -------------------------------- ### Detect ConEmu ANSI Support Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/configuration.md Setting ConEmuANSI to ON enables TrueColor detection on Windows. ```text ConEmuANSI=ON ``` -------------------------------- ### Check ConEmu ANSI Support Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Verify if the terminal is running in ConEmu with ANSI support enabled. ```bash # Check if running in ConEmu with ANSI support echo $ConEmuANSI ``` -------------------------------- ### Test Writer Output Downsampling Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Verifies that the writer correctly strips ANSI codes when configured for ASCII output. ```go import ( "bytes" "testing" "github.com/charmbracelet/colorprofile" ) func TestWriterDownsampling(t *testing.T) { var buf bytes.Buffer w := &colorprofile.Writer{ Forward: &buf, Profile: colorprofile.ASCII, } input := "\x1b[31mRed\x1b[m" w.Write([]byte(input)) // Should have stripped ANSI codes output := buf.String() if output != "Red" { t.Errorf("expected 'Red', got '%s'", output) } } ``` -------------------------------- ### func Tmux(env []string) Profile Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/detection.md Detects the color profile based on tmux configuration and capabilities by querying the tmux info command. ```APIDOC ## func Tmux(env []string) Profile ### Description Detects the color profile based on tmux configuration and capabilities. It queries the `tmux info` command output to determine if tmux supports TrueColor via `Tc` or `RGB` capabilities. ### Parameters - **env** ([]string) - Required - Environment variables as a slice of "KEY=VALUE" strings. ### Return Type - **Profile** - Returns `TrueColor` if TrueColor is supported, `ANSI256` if not, or `NoTTY` if not in a tmux session. ### Example ```go import ( "fmt" "os" "github.com/charmbracelet/colorprofile" ) // When inside tmux env := os.Environ() p := colorprofile.Tmux(env) fmt.Printf("Tmux profile: %s\n", p) ``` ``` -------------------------------- ### Override Profile at Runtime Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/README.md Manually updates the profile of a writer to change or disable color output behavior. ```go w := colorprofile.NewWriter(os.Stdout, os.Environ()) w.Profile = colorprofile.ANSI // Change profile at runtime w.Profile = colorprofile.ASCII // Disable colors w.Profile = colorprofile.NoTTY // Strip all codes ``` -------------------------------- ### Set 24-Bit Background Color Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/ansi-reference.md Sets the background color using TrueColor RGB values. ```text \x1b[48;2;;;m ``` -------------------------------- ### Configure NO_COLOR variable Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/configuration.md Disables color output while preserving other text styling attributes. ```bash NO_COLOR= ``` ```bash export NO_COLOR=1 # colorprofile will detect ASCII profile instead of higher profile ``` -------------------------------- ### Prevent Double-Downsampling Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/ansi-reference.md Demonstrates the incorrect approach of manual downsampling followed by a Writer, versus the correct approach of using the Writer for automatic handling. ```go // WRONG: Double downsampling p := colorprofile.Detect(os.Stdout, os.Environ()) ansiText := "\x1b[38;2;255;0;0mRed\x1b[m" converted := p.Convert(color.RGBA{255, 0, 0, 255}) // Downsample 1 w := colorprofile.NewWriter(os.Stdout, os.Environ()) // Downsample 2 fmt.Fprintf(w, ansiText) // CORRECT: Use Writer for automatic downsampling w := colorprofile.NewWriter(os.Stdout, os.Environ()) fmt.Fprintf(w, "\x1b[38;2;255;0;0mRed\x1b[m") ``` -------------------------------- ### Automatic Color Downsampling Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/usage-examples.md Demonstrates how the writer automatically adjusts 24-bit ANSI sequences based on the terminal's detected color capabilities. ```go w := colorprofile.NewWriter(os.Stdout, os.Environ()) // This ANSI sequence with 24-bit color will automatically be downsampled // to the terminal's capability ansiText := "\x1b[38;2;107;80;255mPurple text\x1b[m" fmt.Fprintf(w, ansiText) // Output varies by terminal: // - TrueColor terminal: outputs as-is (24-bit) // - ANSI256 terminal: converts to 256-color index // - ANSI terminal: converts to 16-color palette // - ASCII terminal: strips all color codes ``` -------------------------------- ### Compare Shell Environment Variables Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Check for inconsistencies in environment variables across different shell types. ```bash # Check environment in each shell bash -c 'echo $TERM' zsh -c 'echo $TERM' fish -c 'echo $TERM' # Check COLORTERM bash -c 'echo $COLORTERM' ``` -------------------------------- ### Define Writer struct Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/writer.md The Writer struct wraps an io.Writer and holds the color profile configuration. ```go type Writer struct { Forward io.Writer // The underlying writer Profile Profile // The color profile to use for downgrading } ``` -------------------------------- ### Configure CLICOLOR_FORCE variable Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/configuration.md Forces color output even for dumb terminals or non-TTY output. ```bash CLICOLOR_FORCE= ``` ```bash export TERM=dumb export CLICOLOR_FORCE=1 # colorprofile will detect ANSI instead of NoTTY export TERM=dumb export CLICOLOR_FORCE=1 export COLORTERM=truecolor # colorprofile will detect TrueColor ``` -------------------------------- ### Handle Legacy Terminals Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/ansi-reference.md Detects terminal capabilities; terminals with TERM=dumb or TERM=unknown return NoTTY and strip all ANSI codes. ```text TERM=dumb or TERM=unknown → colorprofile.Detect() returns NoTTY → Writer strips all codes ``` -------------------------------- ### Convert Colors to Profile Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/README.md Converts a color.RGBA value to the format supported by the detected terminal profile. ```go c := color.RGBA{R: 255, G: 0, B: 0, A: 255} p := colorprofile.Detect(os.Stdout, os.Environ()) converted := p.Convert(c) ``` -------------------------------- ### Identify TrueColor via TERM variable Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md List of terminal emulator names that are automatically recognized as supporting TrueColor based on their TERM environment variable prefix. ```text TERM=alacritty → TrueColor TERM=contour → TrueColor TERM=foot → TrueColor TERM=ghostty → TrueColor TERM=kitty → TrueColor TERM=rio → TrueColor TERM=st → TrueColor TERM=wezterm → TrueColor ``` -------------------------------- ### Combine Multiple ANSI Attributes Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/ansi-reference.md Demonstrates combining bold, foreground, and background attributes in a single sequence. ```text \x1b[1;31;42m Bold, Red foreground, Green background ``` -------------------------------- ### Detect Color Profile from Environment Variables Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/detection.md Determines the color profile using a slice of environment variable strings. This function assumes a TTY environment and does not inspect an io.Writer. ```go func Env(env []string) Profile ``` ```go import ( "fmt" "github.com/charmbracelet/colorprofile" ) env := []string{"TERM=xterm-256color"} p := colorprofile.Env(env) fmt.Printf("Profile from env: %s\n", p) ``` -------------------------------- ### Set 8-Bit Underline Color Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/ansi-reference.md Sets the underline color using the 256-color palette. ```text \x1b[58;5;m ``` -------------------------------- ### Extended Color Sequences Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/ansi-reference.md Shows the structure for 256-color index and RGB TrueColor foreground definitions. ```text \x1b[38;5;196m Foreground: 256-color index 196 \x1b[38;2;255;0;0m Foreground: RGB red ``` -------------------------------- ### Define Global Color Conversion Cache Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/architecture.md The package uses a global map protected by a read-write mutex to cache color conversions for ANSI and ANSI256 profiles, optimizing performance for repeated operations. ```go var cache = map[Profile]map[color.Color]color.Color{ ANSI256: {}, ANSI: {}, } var mu sync.RWMutex ``` -------------------------------- ### Detect Windows Terminal Session Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/configuration.md Presence of the WT_SESSION environment variable upgrades the profile to TrueColor. ```text WT_SESSION= ``` -------------------------------- ### Force ANSI256 via Environment Variables Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Set terminal type or COLORTERM to force 256-color support. ```bash # Use explicit terminal type export TERM=xterm-256color # Or set COLORTERM to non-truecolor value with TERM export TERM=screen ``` -------------------------------- ### Strip Colors to ASCII Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/ansi-reference.md Removes color parameters while preserving non-color attributes like bold. ```text \x1b[38;2;255;0;0;1;42mBold red foreground, green background\x1b[m ``` ```text \x1b[1mBold red foreground, green background\x1b[m ``` -------------------------------- ### Writer.Write() Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/api-reference/writer.md Writes data to the underlying writer while downsampling ANSI color sequences based on the current Writer profile. ```APIDOC ## func (w *Writer) Write(p []byte) (int, error) ### Description Writes data to the underlying writer, downsampling ANSI color sequences based on the Writer's Profile. ### Parameters - **p** ([]byte) - Required - The bytes to write. ### Return Type (int, error) ``` -------------------------------- ### Configure COLORTERM environment variable Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Set the COLORTERM variable to explicitly signal TrueColor support to terminal applications. ```bash export COLORTERM=truecolor # or export COLORTERM=24bit ``` -------------------------------- ### Disable Colors Entirely Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/terminal-support-guide.md Use NO_COLOR or TERM=dumb to suppress color output. ```bash # Option 1: Use NO_COLOR (preserves styling) export NO_COLOR=1 # Option 2: Use TERM=dumb (unless CLICOLOR_FORCE=1) export TERM=dumb ``` -------------------------------- ### Set 24-Bit TrueColor Foreground Source: https://github.com/charmbracelet/colorprofile/blob/main/_autodocs/ansi-reference.md Use this sequence to set the foreground color using specific RGB values. ```text \x1b[38;2;;;m ```