### Example WASM build and serve setup Source: https://github.com/gdamore/tcell/blob/main/README-wasm.md A comprehensive example demonstrating the setup for building and serving a Tcell WASM application, including copying files and starting a local HTTP server. ```sh mkdir -p /tmp/tcell-wasm cp webfiles/tcell.html webfiles/tcell.js webfiles/termstyle.css webfiles/beep.wav /tmp/tcell-wasm/ cp -R webfiles/ghostty-web /tmp/tcell-wasm/ cp "$(go env GOROOT)/lib/wasm/wasm_exec.js" /tmp/tcell-wasm/ GOOS=js GOARCH=wasm go build -o /tmp/tcell-wasm/main.wasm ./demos/unicode python3 -m http.server -d /tmp/tcell-wasm 8080 ``` -------------------------------- ### Initialize Screen, Draw Boxes, and Handle Events Source: https://github.com/gdamore/tcell/blob/main/TUTORIAL.md This is the main function for the tcell demo application. It initializes the screen, sets up styles, draws initial content, and enters an event loop to handle user interactions. Use this as a starting point for tcell applications. ```go package main import ( "fmt" "log" "github.com/gdamore/tcell/v3" "github.com/gdamore/tcell/v3/color" ) func drawText(s tcell.Screen, x1, y1, x2, y2 int, style tcell.Style, text string) { row := y1 col := x1 var width int for text != "" { text, width = s.Put(col, row, text, style) col += width if col >= x2 { row++ col = x1 } if row > y2 { break } if width == 0 { // incomplete grapheme at end of string break } } } func drawBox(s tcell.Screen, x1, y1, x2, y2 int, style tcell.Style, text string) { if y2 < y1 { y1, y2 = y2, y1 } if x2 < x1 { x1, x2 = x2, x1 } // Fill background for row := y1; row <= y2; row++ { for col := x1; col <= x2; col++ { s.Put(col, row, " ", style) } } // Draw borders for col := x1; col <= x2; col++ { s.Put(col, y1, string(tcell.RuneHLine), style) s.Put(col, y2, string(tcell.RuneHLine), style) } for row := y1 + 1; row < y2; row++ { s.Put(x1, row, string(tcell.RuneVLine), style) s.Put(x2, row, string(tcell.RuneVLine), style) } // Only draw corners if necessary if y1 != y2 && x1 != x2 { s.Put(x1, y1, string(tcell.RuneULCorner), style) s.Put(x2, y1, string(tcell.RuneURCorner), style) s.Put(x1, y2, string(tcell.RuneLLCorner), style) s.Put(x2, y2, string(tcell.RuneLRCorner), style) } drawText(s, x1+1, y1+1, x2-1, y2-1, style, text) } func main() { defStyle := tcell.StyleDefault.Background(color.Reset).Foreground(color.Reset) boxStyle := tcell.StyleDefault.Foreground(color.White).Background(color.Purple) // Initialize screen s, err := tcell.NewScreen() if err != nil { log.Fatalf("%+v", err) } if err := s.Init(); err != nil { log.Fatalf("%+v", err) } s.SetStyle(defStyle) s.EnableMouse() s.EnablePaste() s.Clear() // Draw initial boxes drawBox(s, 1, 1, 42, 7, boxStyle, "Click and drag to draw a box") drawBox(s, 5, 9, 32, 14, boxStyle, "Press C to reset") quit := func() { // You have to catch panics in a defer, clean up, // and re-raise them - otherwise your application can // die without leaving any diagnostic trace. maybePanic := recover() s.Fini() if maybePanic != nil { panic(maybePanic) } } defer quit() // Here's how to get the screen size when you need it. // xmax, ymax := s.Size() // Here's an example of how to inject a keystroke where it will // be picked up by a future read of the event queue. Note that // care should be used to avoid blocking writes to the queue if // this is done from the same thread that is responsible for reading // the queue, or else a single-party deadlock might occur. // s.EventQ() <- tcell.NewEventKey(tcell.KeyRune, rune('a'), 0) // Event loop ox, oy := -1, -1 for { // Update screen s.Show() // Poll event (this can be in a select statement as well) ev := <-s.EventQ() // Process event switch ev := ev.(type) { case *tcell.EventResize: s.Sync() case *tcell.EventKey: if ev.Key() == tcell.KeyEscape || ev.Key() == tcell.KeyCtrlC { return } else if ev.Key() == tcell.KeyCtrlL { s.Sync() } else if ev.Str() == "C" || ev.Str() == "c" { s.Clear() } case *tcell.EventMouse: x, y := ev.Position() switch ev.Buttons() { case tcell.Button1, tcell.Button2: if ox < 0 { ox, oy = x, y // record location when click started } case tcell.ButtonNone: if ox >= 0 { label := fmt.Sprintf("%d,%d to %d,%d", ox, oy, x, y) drawBox(s, ox, oy, x, y, boxStyle, label) ox, oy = -1, -1 } } } } } ``` -------------------------------- ### Bracketed Paste Handling Source: https://context7.com/gdamore/tcell/llms.txt Enable bracketed paste mode to receive pasted text as a sequence of EventKey events, delimited by EventPaste start and end events. Use a strings.Builder for efficient string concatenation. ```go s.EnablePaste() var pasting bool var pasteBuf strings.Builder case *tcell.EventPaste: if ev.Start() { pasting = true pasteBuf.Reset() } else { pasting = false fmt.Printf("Pasted: %q\n", pasteBuf.String()) } ``` -------------------------------- ### Copy wasm_exec.js Source: https://github.com/gdamore/tcell/blob/main/README-wasm.md Copy the necessary wasm_exec.js file from your Go installation to the project directory. ```sh cp "$(go env GOROOT)/lib/wasm/wasm_exec.js" ./ ``` -------------------------------- ### Handle Terminal Resize Events in Go Source: https://context7.com/gdamore/tcell/llms.txt Handle tcell EventResize to get terminal dimensions and redraw the UI. Call Sync() after handling the event. SetSize requests a specific terminal size, but support varies. ```go case *tcell.EventResize: w, h := ev.Size() pw, ph := ev.PixelSize() // pixel dimensions if supported (0,0 otherwise) fmt.Printf("Resized: %dx%d cells (%dx%d px)\n", w, h, pw, ph) s.Sync() redrawUI(s) // Request a specific size (may not be honored) s.SetSize(120, 40) ``` -------------------------------- ### Initialize and Lifecycle Management in Tcell Source: https://context7.com/gdamore/tcell/llms.txt Demonstrates initializing a new screen, setting a default style, clearing the screen, and querying terminal capabilities. Ensure `Fini()` is deferred to restore the terminal state. ```go package main import ( "fmt" "os" "github.com/gdamore/tcell/v3" "github.com/gdamore/tcell/v3/color" ) func main() { s, err := tcell.NewScreen() if err != nil { fmt.Fprintf(os.Stderr, "NewScreen: %v\n", err) os.Exit(1) } if err = s.Init(); err != nil { fmt.Fprintf(os.Stderr, "Init: %v\n", err) os.Exit(1) } defer s.Fini() // restores terminal on exit // Set global default style s.SetStyle(tcell.StyleDefault. Background(color.Black). Foreground(color.White)) s.Clear() // Query capabilities w, h := s.Size() fmt.Printf("Terminal: %d x %d, %d colors\n", w, h, s.Colors()) termName, termVer := s.Terminal() fmt.Printf("Terminal emulator: %q version %q\n", termName, termVer) } ``` -------------------------------- ### Complete Tcell Application Source: https://context7.com/gdamore/tcell/llms.txt This Go program demonstrates a full Tcell application. It initializes a screen, sets up event handling for keyboard and mouse input, handles screen resizing, and includes a timer for periodic updates. Use the ESC key to quit. ```go package main import ( "fmt" "os" "time" "github.com/gdamore/tcell/v3" "github.com/gdamore/tcell/v3/color" ) func draw(s tcell.Screen, msg string, mouseX, mouseY int) { s.Clear() w, h := s.Size() // Title bar title := "Tcell Demo — ESC to quit" titleStyle := tcell.StyleDefault.Background(color.Navy).Foreground(color.White).Bold(true) s.Fill(' ', titleStyle) s.PutStrStyled(0, 0, title, titleStyle) // Center message x := (w - len(msg)) / 2 s.PutStrStyled(x, h/2, msg, tcell.StyleDefault.Foreground(color.Lime).Bold(true)) // Mouse position indicator cursor := fmt.Sprintf("Mouse: (%d, %d)", mouseX, mouseY) s.PutStr(0, h-1, cursor) s.ShowCursor(w/2, h/2+2) s.Show() } func main() { s, err := tcell.NewScreen() if err != nil { fmt.Fprintln(os.Stderr, err); os.Exit(1) } if err = s.Init(); err != nil { fmt.Fprintln(os.Stderr, err); os.Exit(1) } defer s.Fini() s.SetStyle(tcell.StyleDefault.Background(color.Black).Foreground(color.White)) s.EnableMouse(tcell.MouseMotionEvents) s.EnablePaste() msg := "Hello from Tcell v3!" mouseX, mouseY := 0, 0 draw(s, msg, mouseX, mouseY) for { select { case ev := <-s.EventQ(): switch ev := ev.(type) { case *tcell.EventKey: switch ev.Key() { case tcell.KeyEscape, tcell.KeyCtrlC: return case tcell.KeyCtrlL: s.Sync() case tcell.KeyRune: msg = "Last key: " + ev.Str() } case *tcell.EventMouse: mouseX, mouseY = ev.Position() case *tcell.EventResize: s.Sync() } draw(s, msg, mouseX, mouseY) case <-time.After(5 * time.Second): msg = "Idle..." draw(s, msg, mouseX, mouseY) } } } ``` -------------------------------- ### Initialize Tcell Screen Source: https://github.com/gdamore/tcell/blob/main/TUTORIAL.md Initializes a new Tcell screen, sets the default style, and clears the screen. Error handling for initialization is included. ```go s, err := tcell.NewScreen() if err != nil { log.Fatalf("%+v", err) } if err := s.Init(); err != nil { log.Fatalf("%+v", err) } // Set default text style defStyle := tcell.StyleDefault.Background(color.Reset).Foreground(color.Reset) s.SetStyle(defStyle) // Clear screen s.Clear() ``` -------------------------------- ### Test Tcell Applications with ShimScreen in Go Source: https://context7.com/gdamore/tcell/llms.txt Use ShimScreen to inject a replacement Screen implementation for headless unit testing. Combined with the vt emulator, this allows testing TUI applications without a physical terminal. Initialize the screen, set its size, exercise the widget, and inspect the cell buffer. ```go // In test code: import "github.com/gdamore/tcell/v3" func TestMyWidget(t *testing.T) { sim := tcell.NewSimulationScreen("UTF-8") tcell.ShimScreen(sim) s, _ := tcell.NewScreen() // returns sim s.Init() s.SetSize(80, 24) // Exercise your widget myWidget.Draw(s) s.Show() // Inspect the cell buffer str, style, _ := s.Get(0, 0) if str != "Expected" { t.Fatalf("got %q", str) } _ = style } ``` -------------------------------- ### Copy ghostty-web files Source: https://github.com/gdamore/tcell/blob/main/README-wasm.md Copy the ghostty-web directory, which contains required browser runtime files, to the directory you intend to serve. ```sh cp -R webfiles/ghostty-web /path/to/dir/to/serve/ ``` -------------------------------- ### Clipboard Interaction (OSC 52) Source: https://context7.com/gdamore/tcell/llms.txt Interact with the system clipboard using OSC 52 sequences, provided the terminal supports it and has permission. Responses to GetClipboard arrive as EventClipboard. ```go // Clipboard (OSC 52 — terminal permission required) if s.HasClipboard() { s.SetClipboard([]byte("text to copy")) s.GetClipboard() // response arrives as *EventClipboard } case *tcell.EventClipboard: fmt.Printf("Clipboard: %s\n", ev.Data()) ``` -------------------------------- ### Handle Keyboard Events (EventKey) Source: https://context7.com/gdamore/tcell/llms.txt Process printable characters, special keys, and modifier states. Check keyboard protocol for advanced features like press/release and repeat counts. ```go case *tcell.EventKey: switch ev.Key() { case tcell.KeyRune: // Printable character — possibly multi-byte / composed grapheme fmt.Printf("Typed: %q\n", ev.Str()) case tcell.KeyUp: // Arrow key case tcell.KeyF1: // Function key case tcell.KeyCtrlC: // Legacy Ctrl+C (in legacy mode only) // In advanced mode use: ev.Key()==KeyRune && ev.Modifiers()&ModCtrl != 0 } // Check modifiers mod := ev.Modifiers() if mod&tcell.ModCtrl != 0 { fmt.Printf("Ctrl+%s\n", ev.Str()) } if mod&tcell.ModAlt != 0 { fmt.Printf("Alt+%s\n", ev.Str()) } // Keyboard protocol in use switch s.KeyboardProtocol() { case tcell.KittyKeyboard: // Full key press/release, unambiguous modifiers fmt.Printf("press=%v physical=%v repeat=%d\n", ev.Pressed(), ev.Physical(), ev.Repeat()) case tcell.LegacyKeyboard: // VT100-style, press only, limited modifiers } // Human-readable key name fmt.Println(ev.Name()) // e.g. "Ctrl+A", "Shift+F1", "Rune[x]" ``` ```go case *tcell.EventKey: if pasting && ev.Key() == tcell.KeyRune { pasteBuf.WriteString(ev.Str()) } ``` -------------------------------- ### Tcell Color API Usage Source: https://context7.com/gdamore/tcell/llms.txt Shows how to use the color subpackage for palette colors, W3C named colors, and RGB true-color construction. Includes methods for converting to RGB, CSS, name, and checking color properties. ```go import "github.com/gdamore/tcell/v3/color" // Palette colors (ANSI/XTerm) fg := color.Red // XTerm palette index 9 bg := color.Navy // XTerm palette index 4 // W3C named true colors c := color.CornflowerBlue // 0x6495ED // Force true color (bypass terminal theme) tc := color.CadetBlue.TrueColor() // IsRGB | IsValid | 0x5F9EA0 // Construct RGB colors orange := color.NewRGBColor(255, 165, 0) hex := color.NewHexColor(0xFF8C00) // DarkOrange // From hex string or W3C name named := color.GetColor("tomato") parsed := color.GetColor("#FF6347") // Palette index (0-255) p := color.PaletteColor(196) // bright red // Inspect r, g, b := orange.RGB() // 255, 165, 0 css := orange.CSS() // "#FFA500" name := color.Red.Name() // "red" isRGB := orange.IsRGB() // true valid := orange.Valid() // true // Convert from image/color import ic "image/color" imgC := ic.RGBA{R: 0, G: 128, B: 255, A: 255} tcellC := color.FromImageColor(imgC) ``` -------------------------------- ### Build Tcell for WASM Source: https://github.com/gdamore/tcell/blob/main/README-wasm.md Use these environment variables and command to build the Tcell project for WebAssembly. ```sh GOOS=js GOARCH=wasm go build -o yourfile.wasm ``` -------------------------------- ### Resize Events and SetSize Source: https://context7.com/gdamore/tcell/llms.txt Handles terminal resize events by calling Sync() and redrawing the screen. SetSize requests a terminal resize, though support varies. ```APIDOC ## EventResize ### Description Sent whenever the terminal dimensions change. Applications should call `Sync()` and redraw. ### Example ```go case *tcell.EventResize: w, h := ev.Size() pw, ph := ev.PixelSize() // pixel dimensions if supported (0,0 otherwise) fmt.Printf("Resized: %dx%d cells (%dx%d px)\n", w, h, pw, ph) s.Sync() redrawUI(s) ``` ## SetSize ### Description Requests a terminal resize (support varies widely by terminal/platform). ### Example ```go // Request a specific size (may not be honored) s.SetSize(120, 40) ``` ``` -------------------------------- ### ShimScreen (Testing) Source: https://context7.com/gdamore/tcell/llms.txt Provides a ShimScreen implementation for headless unit testing of TUI applications by injecting a replacement Screen. ```APIDOC ## ShimScreen ### Description Injects a replacement `Screen` implementation returned by the next call to `NewScreen`. This is combined with the `vt` emulator package to enable headless unit testing of TUI applications. ### Parameters - `sim` (`tcell.Screen`) - The replacement `Screen` implementation to use. ### Example ```go // In test code: import "github.com/gdamore/tcell/v3" func TestMyWidget(t *testing.T) { sim := tcell.NewSimulationScreen("UTF-8") tcell.ShimScreen(sim) s, _ := tcell.NewScreen() // returns sim s.Init() s.SetSize(80, 24) // Exercise your widget myWidget.Draw(s) s.Show() // Inspect the cell buffer str, style, _ := s.Get(0, 0) if str != "Expected" { t.Fatalf("got %q", str) } _ = style } ``` ``` -------------------------------- ### Serve Tcell WASM application with Go Source: https://github.com/gdamore/tcell/blob/main/README-wasm.md A Go program to serve the Tcell WASM application files from a specified directory on port 8080. ```golang // server.go package main import ( "log" "net/http" ) func main() { log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/path/to/dir/to/serve/")), )) } ``` -------------------------------- ### Handle Mouse Events (EventMouse) Source: https://context7.com/gdamore/tcell/llms.txt Enable and configure mouse reporting for click, drag, and motion events. Coordinates can be in character cells or pixels. Remember to disable mouse reporting when no longer needed. ```go // Enable mouse reporting before the event loop s.EnableMouse(tcell.MouseMotionEvents) // click + drag + motion // s.EnableMouse(tcell.MouseButtonEvents) // clicks only // s.EnableMouse(tcell.MouseDragEvents | tcell.MousePixelEvents) // drag + pixel coords // In the event loop: case *tcell.EventMouse: x, y := ev.Position() btn := ev.Buttons() switch { case btn&tcell.ButtonPrimary != 0: // left click fmt.Printf("Left click at (%d, %d)\n", x, y) case btn&tcell.ButtonSecondary != 0: // right click fmt.Printf("Right click at (%d, %d)\n", x, y) case btn&tcell.ButtonMiddle != 0: // middle click fmt.Printf("Middle click at (%d, %d)\n", x, y) case btn&tcell.WheelUp != 0: fmt.Println("Scroll up") case btn&tcell.WheelDown != 0: fmt.Println("Scroll down") case btn == tcell.ButtonNone: fmt.Printf("Mouse move at (%d, %d)\n", x, y) // requires MotionEvents } // Disable when no longer needed s.DisableMouse() ``` -------------------------------- ### Tcell Style Construction Source: https://context7.com/gdamore/tcell/llms.txt Demonstrates building immutable styles using chained builder methods. StyleDefault is the zero value. Attributes like bold, underline, italic, strikethrough, foreground, background, and URL can be set. ```go // Chain builder methods bold := tcell.StyleDefault.Bold(true) header := tcell.StyleDefault. Foreground(color.White). Background(color.Navy). Bold(true). Underline(tcell.UnderlineStyleSolid, color.Yellow) // Italic + strikethrough warning := tcell.StyleDefault. Foreground(color.Red). Italic(true). StrikeThrough(true) // Curly underline (modern terminals) curly := tcell.StyleDefault.Underline(tcell.UnderlineStyleCurly, color.Red) // Hyperlink (OSC 8 — supported by modern terminals) link := tcell.StyleDefault. Foreground(color.Blue). Url("https://example.com"). UrlId("link-1") // Inspect a style id, url := link.GetUrl() fmt.Printf("URL: %s (id=%s)\n", url, id) // Reset all attributes, keeping colors plain := header.Normal() ``` -------------------------------- ### Set Terminal Title, Show Notifications, and Beep in Go Source: https://context7.com/gdamore/tcell/llms.txt Set the terminal window title using SetTitle. Show desktop notifications with ShowNotification, which uses OSC 777 and is supported by terminals like Kitty. Use Beep for an audible/visual bell, checking for errors if the terminal does not support it. ```go // Set the terminal window/tab title s.SetTitle("My TUI App — v1.0") // Desktop notification (OSC 777 — supported by Kitty, some others) s.ShowNotification("Build complete", "All tests passed ✓") // Audible/visual bell if err := s.Beep(); err != nil { // terminal does not support beep } ``` -------------------------------- ### Draw Styled String on Tcell Screen Source: https://github.com/gdamore/tcell/blob/main/TUTORIAL.md An alternative to drawing individual characters, this shows how to draw a styled string at a given position using PutStrStyled. ```go s.PutStrStyled(0, 0, "Hi!", defStyle) ``` -------------------------------- ### Draw Characters on Tcell Screen Source: https://github.com/gdamore/tcell/blob/main/TUTORIAL.md Demonstrates drawing individual characters at specific coordinates on the Tcell screen using the Put method. ```go s.Put(0, 0, "H", defStyle) s.Put(1, 0, "i", defStyle) s.Put(2, 0, "!", defStyle) ``` -------------------------------- ### Handle Tcell Resize Events Source: https://github.com/gdamore/tcell/blob/main/TUTORIAL.md Applications receive an EventResize when initialized or when the terminal is resized. The new dimensions are available via the Size() method. ```go switch ev := ev.(type) { case *tcell.EventResize: w, h := ev.Size() logMessage(fmt.Sprintf("Resized to %dx%d", w, h)) } ``` -------------------------------- ### Register Rune Fallbacks for Character Encoding in Go Source: https://context7.com/gdamore/tcell/llms.txt Register ASCII substitutes for characters that cannot be displayed on terminals lacking full Unicode support. This allows graceful degradation instead of displaying '?'. Use UnregisterRuneFallback to remove a specific fallback. ```go // Register ASCII fallback for box-drawing characters s.RegisterRuneFallback('└', "\") s.RegisterRuneFallback('┘', "/") s.RegisterRuneFallback('┌', "/") s.RegisterRuneFallback('┐', "\") s.RegisterRuneFallback('─', "-") s.RegisterRuneFallback('│', "|") // Remove a fallback s.UnregisterRuneFallback('└') ``` -------------------------------- ### Handle Tcell Key Events Source: https://github.com/gdamore/tcell/blob/main/TUTORIAL.md Key events are dispatched when a key is pressed. This snippet shows how to extract modifiers, key type, and the string representation of the key. ```go switch ev := ev.(type) { case *tcell.EventKey: mod, key, ch := ev.Mod(), ev.Key(), ev.Str() logMessage(fmt.Sprintf("EventKey Modifiers: %d Key: %d Str: %q", mod, key, ch)) } ``` -------------------------------- ### Register and Use Character Encodings in Go Source: https://context7.com/gdamore/tcell/llms.txt For POSIX terminals in non-UTF-8 locales, explicitly register character set encodings. The encoding sub-package registers common encodings automatically. SetEncodingFallback controls behavior for unknown charsets. GetEncoding retrieves a registered encoding. ```go import ( "golang.org/x/text/encoding/charmap" "github.com/gdamore/tcell/v3" _ "github.com/gdamore/tcell/v3/encoding" // registers all encodings ) // Or register individually: tcell.RegisterEncoding("ISO8859-15", charmap.ISO8859_15) tcell.RegisterEncoding("8859-15", charmap.ISO8859_15) // alias // Control fallback behavior when locale charset is unknown tcell.SetEncodingFallback(tcell.EncodingFallbackUTF8) // tcell.EncodingFallbackASCII — fall back to 7-bit ASCII // tcell.EncodingFallbackFail — return nil (fail hard) enc := tcell.GetEncoding("iso8859-15") ``` -------------------------------- ### Focus Events Handling Source: https://context7.com/gdamore/tcell/llms.txt Enable and handle focus events to react when the terminal window gains or loses focus. This is useful for pausing animations or toggling cursor visibility. ```go s.EnableFocus() case *tcell.EventFocus: if ev.Focused { s.ShowCursor(curX, curY) } else { s.HideCursor() } s.DisableFocus() ``` -------------------------------- ### Terminal Title, Notifications, and Beep Source: https://context7.com/gdamore/tcell/llms.txt APIs for setting the terminal window title, showing desktop notifications, and triggering an audible/visual bell. ```APIDOC ## SetTitle ### Description Sets the terminal window or tab title. ### Parameters - `title` (string) - The desired title for the terminal window/tab. ### Example ```go // Set the terminal window/tab title s.SetTitle("My TUI App — v1.0") ``` ## ShowNotification ### Description Displays a desktop notification. This uses OSC 777, supported by Kitty and some other terminals. ### Parameters - `title` (string) - The title of the notification. - `body` (string) - The main text content of the notification. ### Example ```go // Desktop notification (OSC 777 — supported by Kitty, some others) s.ShowNotification("Build complete", "All tests passed ✓") ``` ## Beep ### Description Triggers an audible or visual bell. Returns an error if the terminal does not support this feature. ### Example ```go // Audible/visual bell if err := s.Beep(); err != nil { // terminal does not support beep } ``` ``` -------------------------------- ### Tcell Event Loop Source: https://context7.com/gdamore/tcell/llms.txt Reads terminal events from the EventQ channel. Handles key presses, mouse events, resize, paste, focus, and clipboard events. The loop terminates when Escape or Ctrl+C is pressed, or when Fini() is called. ```go for { ev := <-s.EventQ() switch ev := ev.(type) { case *tcell.EventKey: if ev.Key() == tcell.KeyEscape || ev.Key() == tcell.KeyCtrlC { s.Fini() return } if ev.Key() == tcell.KeyRune { fmt.Printf("Rune: %q Modifiers: %v\n", ev.Str(), ev.Modifiers()) } fmt.Printf("Key: %s Pressed: %v Repeat: %d\n", ev.Name(), ev.Pressed(), ev.Repeat()) case *tcell.EventMouse: x, y := ev.Position() btn := ev.Buttons() fmt.Printf("Mouse at (%d,%d) buttons=%v mods=%v\n", x, y, btn, ev.Modifiers()) case *tcell.EventResize: w, h := ev.Size() fmt.Printf("Resize: %d x %d\n", w, h) s.Sync() // repaint on resize case *tcell.EventPaste: if ev.Start() { fmt.Println("Paste started") } else { fmt.Println("Paste ended") } case *tcell.EventFocus: fmt.Printf("Focus: %v\n", ev.Focused) case *tcell.EventClipboard: fmt.Printf("Clipboard data: %s\n", ev.Data()) } } ``` -------------------------------- ### Writing Styled and Wide Characters in Tcell Source: https://context7.com/gdamore/tcell/llms.txt Illustrates writing styled text, wide characters (like emojis), and individual cells with combining characters. Use `Show()` to update the physical terminal. ```go // Write styled text at a specific position style := tcell.StyleDefault. Foreground(color.CadetBlue.TrueColor()). Background(color.White). Bold(true) s.PutStrStyled(5, 3, "Hello, World!", style) // Write an emoji (wide character, occupies 2 cells) remain, width := s.Put(0, 0, "😀 wide char demo", tcell.StyleDefault) // width == 2 for the emoji; remain contains the rest of the string // Low-level per-cell API with combining characters s.SetContent(10, 5, 'e', []rune{0x0301}, tcell.StyleDefault) // é with combining acute // Fill entire screen with a character and style s.Fill('░', tcell.StyleDefault.Foreground(color.Gray)) // Clear (shorthand for Fill(' ', StyleDefault)) s.Clear() // Flush changes to the physical terminal s.Show() // Force full redraw (e.g., after resize or corruption) s.Sync() ``` -------------------------------- ### Suspend and Resume Tcell Application in Go Source: https://context7.com/gdamore/tcell/llms.txt Suspend temporarily restores the terminal to its original state, allowing sub-shells or external editors to run. Resume returns the application to raw TUI mode. A full repaint (Sync()) is recommended after resuming. ```go // Temporarily give up the terminal (e.g., to run $EDITOR) if err := s.Suspend(); err == nil { cmd := exec.Command(os.Getenv("EDITOR"), filename) cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr cmd.Run() s.Resume() s.Sync() // full repaint after returning } ``` -------------------------------- ### Handle Tcell Mouse Events Source: https://github.com/gdamore/tcell/blob/main/TUTORIAL.md Mouse events are delivered when mouse actions occur, provided EnableMouse has been called. This code extracts modifiers, button states, and mouse coordinates. ```go switch ev := ev.(type) { case *tcell.EventMouse: mod := ev.Modifiers() btns := ev.Buttons() x, y := ev.Position() logMessage(fmt.Sprintf("EventMouse Modifiers: %d Buttons: %d Position: %d,%d", mod, btns, x, y)) } ``` -------------------------------- ### Cursor Control Source: https://context7.com/gdamore/tcell/llms.txt Control cursor visibility and style. Supports positioning, hiding, and setting various blinking/steady styles for block, underline, and bar cursors, optionally with color. ```go // Position the cursor s.ShowCursor(10, 5) // Hide the cursor s.HideCursor() // Blinking bar cursor (common in editors), colored s.SetCursorStyle(tcell.CursorStyleBlinkingBar, color.Lime) // Steady block cursor s.SetCursorStyle(tcell.CursorStyleSteadyBlock) // Available cursor styles: // tcell.CursorStyleDefault // tcell.CursorStyleBlinkingBlock // tcell.CursorStyleSteadyBlock // tcell.CursorStyleBlinkingUnderline // tcell.CursorStyleSteadyUnderline // tcell.CursorStyleBlinkingBar // tcell.CursorStyleSteadyBar ``` -------------------------------- ### Rune Fallback Registration Source: https://context7.com/gdamore/tcell/llms.txt Registers ASCII substitutes for Unicode characters that a terminal may not support, ensuring graceful degradation of the display. ```APIDOC ## RegisterRuneFallback ### Description Registers an ASCII substitute for a Unicode rune that cannot be displayed by the terminal. ### Parameters - `r` (rune) - The Unicode rune to register a fallback for. - `fallback` (string) - The ASCII string to use as a fallback. ### Example ```go // Register ASCII fallback for box-drawing characters s.RegisterRuneFallback('└', "\") s.RegisterRuneFallback('┘', "/") s.RegisterRuneFallback('┌', "/") s.RegisterRuneFallback('┐', "\") s.RegisterRuneFallback('─', "-") s.RegisterRuneFallback('│', "|") ``` ## UnregisterRuneFallback ### Description Removes a previously registered rune fallback. ### Parameters - `r` (rune) - The Unicode rune whose fallback should be removed. ### Example ```go // Remove a fallback s.UnregisterRuneFallback('└') ``` ``` -------------------------------- ### Encoding Registration Source: https://context7.com/gdamore/tcell/llms.txt Manages character set encoding registration for POSIX terminals in non-UTF-8 locales. ```APIDOC ## RegisterEncoding ### Description Registers a character set encoding for use with POSIX terminals in non-UTF-8 locales. ### Parameters - `name` (string) - The name of the encoding (e.g., "ISO8859-15"). - `encoding` (tcell.Encoding) - The encoding object. ### Example ```go import ( "golang.org/x/text/encoding/charmap" "github.com/gdamore/tcell/v3" _ "github.com/gdamore/tcell/v3/encoding" // registers all encodings ) // Or register individually: tcell.RegisterEncoding("ISO8859-15", charmap.ISO8859_15) tcell.RegisterEncoding("8859-15", charmap.ISO8859_15) // alias ``` ## SetEncodingFallback ### Description Controls the fallback behavior when the locale charset is unknown. ### Parameters - `fallback` (tcell.EncodingFallback) - The fallback behavior to set (e.g., `tcell.EncodingFallbackUTF8`, `tcell.EncodingFallbackASCII`, `tcell.EncodingFallbackFail`). ### Example ```go // Control fallback behavior when locale charset is unknown tcell.SetEncodingFallback(tcell.EncodingFallbackUTF8) // tcell.EncodingFallbackASCII — fall back to 7-bit ASCII // tcell.EncodingFallbackFail — return nil (fail hard) ``` ## GetEncoding ### Description Retrieves a registered encoding by its name. ### Parameters - `name` (string) - The name of the encoding to retrieve. ### Returns - `tcell.Encoding` - The encoding object, or nil if not found. ### Example ```go enc := tcell.GetEncoding("iso8859-15") ``` ``` -------------------------------- ### Suspend and Resume Source: https://context7.com/gdamore/tcell/llms.txt Allows temporarily suspending the tcell application to run external commands and then resuming the TUI. ```APIDOC ## Suspend ### Description Restores the terminal to its original state, allowing for the execution of sub-shells or external editors. ### Example ```go // Temporarily give up the terminal (e.g., to run $EDITOR) if err := s.Suspend(); err == nil { cmd := exec.Command(os.Getenv("EDITOR"), filename) cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr cmd.Run() s.Resume() s.Sync() // full repaint after returning } ``` ## Resume ### Description Returns the terminal to raw TUI mode after being suspended. ``` -------------------------------- ### Reading Cell Contents and Attributes in Tcell Source: https://context7.com/gdamore/tcell/llms.txt Shows how to retrieve the content, style, and display width of a cell at a given position. You can also check for specific text attributes like bold or underline. ```go str, style, width := s.Get(5, 3) fg := style.GetForeground() bg := style.GetBackground() fmt.Printf("Cell at (5,3): %q width=%d fg=%v bg=%v\n", str, width, fg, bg) // Check text attributes if style.HasBold() { fmt.Println("bold") } if style.HasUnderline() { fmt.Printf("underline style: %v\n", style.GetUnderlineStyle()) } ``` -------------------------------- ### Configure WASM file path in tcell.js Source: https://github.com/gdamore/tcell/blob/main/README-wasm.md Modify the `wasmFilePath` constant in `tcell.js` to point to your compiled WASM file. ```js const wasmFilePath = "yourfile.wasm" ``` -------------------------------- ### Tcell Text Wrapping Function Source: https://github.com/gdamore/tcell/blob/main/TUTORIAL.md A utility function to draw text within a specified rectangular area, handling word wrapping and line breaks. ```go func drawText(s tcell.Screen, x1, y1, x2, y2 int, style tcell.Style, text string) { row := y1 col := x1 var width int for text != "" { text, width = s.Put(col, row, text, style) col += width if col >= x2 { row++ col = x1 } if row > y2 { break } if width == 0 { // incomplete grapheme at end of string break } } } ``` -------------------------------- ### Set terminal dimensions in HTML Source: https://github.com/gdamore/tcell/blob/main/README-wasm.md Override default terminal dimensions by setting `data-cols` and `data-rows` attributes on the `#terminal` element. ```html

```

--------------------------------

### Tcell Event Loop

Source: https://github.com/gdamore/tcell/blob/main/TUTORIAL.md

The main event loop for a Tcell application. It continuously updates the screen, polls for events, and processes them, including handling resize and exit conditions.

```go
quit := func() {
    s.Fini()
    os.Exit(0)
}
for {
    // Update screen
    s.Show()

    // Poll event (can be used in select statement as well)
    ev := <-s.EventQ()

    // Process event
    switch ev := ev.(type) {
    case *tcell.EventResize:
        s.Sync()
    case *tcell.EventKey:
        if ev.Key() == tcell.KeyEscape || ev.Key() == tcell.KeyCtrlC {
            quit()
        }
    }
}
```

--------------------------------

### Embed Tcell WASM application using iframe

Source: https://github.com/gdamore/tcell/blob/main/README-wasm.md

Use an iframe HTML tag to embed the Tcell WASM application into an existing webpage.

```html

```

--------------------------------

### Lock and Unlock Screen Regions in Go

Source: https://context7.com/gdamore/tcell/llms.txt

Use LockRegion to prevent tcell from overwriting a specific rectangular area. This is useful for rendering direct-to-TTY content like sixel graphics. The region must be unlocked to resume normal drawing.

```go
// Lock the region under a sixel image so tcell won't overdraw it
s.LockRegion(imgX, imgY, imgWidth, imgHeight, true)

// ... render sixel/image data directly to the TTY ...

// Unlock and resume normal drawing when the image is cleared
s.LockRegion(imgX, imgY, imgWidth, imgHeight, false)
```

--------------------------------

### Cell Locking (LockRegion)

Source: https://context7.com/gdamore/tcell/llms.txt

Prevents tcell from overwriting a rectangular area, useful for rendering content directly to the TTY underneath the tcell screen.

```APIDOC
## LockRegion

### Description
Prevents tcell from overwriting a rectangular area. This is needed when rendering sixel graphics or other direct-to-TTY content underneath the tcell screen.

### Parameters
- `x` (int) - The starting X coordinate of the region.
- `y` (int) - The starting Y coordinate of the region.
- `width` (int) - The width of the region.
- `height` (int) - The height of the region.
- `lock` (bool) - `true` to lock the region, `false` to unlock.

### Example
```go
// Lock the region under a sixel image so tcell won't overdraw it
s.LockRegion(imgX, imgY, imgWidth, imgHeight, true)

// ... render sixel/image data directly to the TTY ...

// Unlock and resume normal drawing when the image is cleared
s.LockRegion(imgX, imgY, imgWidth, imgHeight, false)
```
```

=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.