ui

package
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 18, 2026 License: MIT Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ui provides reusable TUI components including modals, buttons, scrollbars, skeleton loaders, overlays, and text utilities.

Package ui provides shared UI components and helpers for the TUI.

Index

Constants

View Source
const (
	ModalWidthSmall  = 40 // Simple confirmations
	ModalWidthMedium = 50 // Standard modals with inputs
	ModalWidthLarge  = 60 // Modals with longer content
)

Standard modal widths

View Source
const (
	DimSequence   = "\x1b[2m"
	ResetSequence = "\x1b[0m"
)

DimSequence and ResetSequence are the raw ANSI codes used by DimStyle. Exported for testing.

View Source
const CloseButtonLabel = "×"

CloseButtonLabel is the glyph drawn on pane-header close buttons.

View Source
const RowBackgroundDefault = "\x1b[49m"

RowBackgroundDefault is the sequence that restores the terminal's default background. Rows are terminated with it so a background opened on one row cannot bleed into whatever is drawn after it.

View Source
const SkeletonTickInterval = 80 * time.Millisecond

SkeletonTickInterval is the animation frame rate (60fps feel).

Variables

View Source
var AnsiResetRe = regexp.MustCompile(`\x1b\[0?m`)

AnsiResetRe matches ANSI reset sequences (both \x1b[0m and \x1b[m).

Functions

func ApplyTerminalDefaultBackground added in v0.96.0

func ApplyTerminalDefaultBackground(line, bg string, width int) string

ApplyTerminalDefaultBackground renders default-background cells with bg. Explicit application backgrounds still win; resets to the terminal default are followed by bg so embedding the row inside another styled surface cannot expose that surface's background.

func BytePosToRunePos

func BytePosToRunePos(s string, bytePos int) int

BytePosToRunePos converts a byte position to a rune position.

func CalculateModalWidth

func CalculateModalWidth(content string, minWidth, maxWidth int) int

CalculateModalWidth returns an appropriate width based on content. Ensures width is within min/max bounds.

func CarryRowBackground added in v0.98.0

func CarryRowBackground(line, inherited string) (out, trailing string, touched bool)

CarryRowBackground makes one captured row self-contained.

tmux emits `capture-pane -e` as a single continuous SGR stream and writes only the delta, so a row whose predecessor left a background active begins with that background still open and never repeats it. Sidecar renders rows independently — it slices them apart, truncates them, pads them and joins them into a styled surface — which loses that carried state and lets a background smear across cells that should not have it.

It returns the row with the inherited background re-opened at its front, the background left active at its end (the caller's inherited value for the next row), and whether the row touches the background at all. A row that reports touched must be terminated with RowBackgroundDefault once the caller has finished truncating and padding it.

func ClampModalWidth

func ClampModalWidth(width, screenWidth int) int

ClampModalWidth clamps a width value between min and max screen bounds.

func CloseButtonWidth added in v1.0.0

func CloseButtonWidth() int

CloseButtonWidth is the columns the close control occupies at rest. Hover must not change it, or the tab strip would reflow under the pointer.

func ComposeHeaderClose added in v1.0.0

func ComposeHeaderClose(tabsRow string, width int, hovered bool) string

ComposeHeaderClose joins an already-padded tab row to the close button. tabsRow must already be TabsWidth columns; the result is Width columns.

func DimStyle

func DimStyle() lipgloss.Style

DimStyle applies a dim gray color to background content behind modals. We strip existing ANSI codes and apply gray because SGR 2 (faint) doesn't reliably combine with existing color codes in most terminals.

This is a function, not a var: styles.TextMuted is a package-level variable that ApplyTheme reassigns, so a var here would be evaluated at init — before any theme is applied — and every modal backdrop would keep dimming in the default theme's grey no matter which theme is active. See internal/themecheck.

func ElidePathSet added in v1.0.0

func ElidePathSet(paths []string, width int) ([]string, [][]Span)

ElidePathSet fits every path in paths into width cells, as ElidePath does, with one thing ElidePath cannot have: the rest of the list.

Two different files rendering as the same row is the failure this exists to prevent, and it is not a failure any single-path elision can rule out. Every budget eventually forces a choice between characters, and whichever characters a lone path picks may be exactly the ones its neighbour picked too: `internal/plugins/tasks/plugin_test.go` and `internal/plugins/tdmonitor/plugin_test.go` differ in one directory, at one character, and at 22 cells there is no room to show it unless something knows to look for it. The list knows.

So the set is elided in three passes:

  1. each path on its own, exactly as ElidePath would;
  2. a directory abbreviated more than one way in the list is drawn the shortest of those ways everywhere, so one directory reads as one thing;
  3. any two rows that still render identically are re-elided with the characters that tell them apart pinned, paid for by spending a directory the colliding rows share.

It is not a guarantee — two paths differing only inside a name longer than the whole budget cannot be told apart at that budget by anything — but it is a guarantee wherever the cells exist, and it fails by leaving rows equal rather than by inventing a path that does not exist.

func ElidePathSetWidths added in v1.0.0

func ElidePathSetWidths(paths []string, widths []int) ([]string, [][]Span)

ElidePathSetWidths is ElidePathSet for a list whose rows do not all have the same budget — a result list with a per-row suffix, say. Rows with different budgets still have to be distinguishable from each other, so the collision pass spans the whole list either way.

func ExpandTabs

func ExpandTabs(line string, tabWidth int) string

ExpandTabs replaces tabs with spaces, preserving ANSI sequences and column widths.

func FitBlock added in v0.99.0

func FitBlock(content string, w, h int) string

FitBlock returns content as exactly h rows of exactly w cells, clipping and padding each row against ANSI cell widths. It is what a renderer that owes a caller a rectangle applies to its own output, so the rectangle is the block's answer rather than something a compositor imposes on it afterwards.

func FitMessage added in v1.0.0

func FitMessage(width int, candidates ...string) string

FitMessage picks the first of candidates that fits width, falling back to the last one truncated. Wording that fits is the cheapest way to keep a box the height it budgeted for: a message that wraps costs a row nobody reserved.

func GetSelectionBgANSI

func GetSelectionBgANSI() string

GetSelectionBgANSI returns the ANSI 24-bit background code for selection highlight based on the current theme's BgTertiary color.

func InjectCharacterRangeBackground

func InjectCharacterRangeBackground(line string, startCol, endCol int) string

InjectCharacterRangeBackground applies selection background to visual columns [startCol, endCol] (inclusive) within the line. startCol and endCol are in absolute visual space (post-tab-expansion). Handles ANSI codes correctly. If endCol is -1, highlights to end of line.

func InjectSelectionBackground

func InjectSelectionBackground(s string) string

InjectSelectionBackground adds a selection background to a whole fragment, surviving any background the fragment sets for itself, and fully resets at the end so the highlight cannot leak into whatever is appended after it.

func JoinEnds added in v1.0.0

func JoinEnds(left, right string, width int) string

JoinEnds lays left and right out on one row of width cells with at least one space between them, dropping right when it would not fit and truncating left when it does not fit on its own.

func MapSpans added in v1.0.0

func MapSpans(spans []Span, start, end int) (int, int, bool)

MapSpans translates a byte range in the original string onto the elided one, reporting false when the range did not survive the elision.

func OverlayModal

func OverlayModal(background, modal string, width, height int) string

OverlayModal composites a modal on top of a dimmed background. The modal is centered, with dimmed background visible on all sides.

func PrintableKeyText added in v0.91.0

func PrintableKeyText(msg tea.KeyPressMsg) string

PrintableKeyText returns the printable text carried by a key press. KeyPressMsg.String is intended for shortcut matching and returns names such as "space" for some printable keys, so text-entry code should use this helper instead.

func RenderButtonPair

func RenderButtonPair(confirmLabel, cancelLabel string, focusIdx, hoverIdx int) string

RenderButtonPair renders a confirm/cancel button pair with proper spacing. focusIdx: 1 for confirm focused, 2 for cancel focused, 0 for neither hoverIdx: 1 for confirm hovered, 2 for cancel hovered, 0 for neither

func RenderCloseButton added in v1.0.0

func RenderCloseButton(hovered bool) string

RenderCloseButton paints the shared header close control. It uses the same rest/hover styles as every other button so a pane X does not invent a third look.

func RenderDivider

func RenderDivider(height int) string

RenderDivider renders an idle vertical handle of height cells. Compatibility wrapper for callers that have not migrated to RenderHandle.

func RenderHandle added in v1.0.0

func RenderHandle(length int, vertical bool, state HandleState) string

RenderHandle draws a 1-cell-thick handle. vertical=true: length is height; false: length is width.

func RenderScrollbar

func RenderScrollbar(params ScrollbarParams) string

RenderScrollbar returns a single-column string (newline-separated) representing a vertical scrollbar track. Returns a column of spaces if all content is visible (TotalItems <= VisibleItems) to reserve the width and prevent layout jitter. Output has exactly TrackHeight lines, each 1 character wide.

func ResolveButtonStyle

func ResolveButtonStyle(focusIdx, hoverIdx, btnIdx int) lipgloss.Style

ResolveButtonStyle returns the appropriate style based on focus and hover state. focusIdx: which button index is focused (0-based), -1 for none hoverIdx: which button index is hovered (0-based), -1 for none btnIdx: the index of the button being styled

func SGRBackground added in v0.96.0

func SGRBackground(seq string) (string, bool)

SGRBackground reports whether an SGR sequence changes the background and returns the minimal sequence that reproduces the resulting background. Callers rendering ANSI owned by another terminal application use this to distinguish an explicit colour from the terminal default without duplicating the colour-parameter parser.

func SafeByteSlice

func SafeByteSlice(s string, byteStart, byteEnd int) string

SafeByteSlice extracts a substring using byte positions, ensuring the slice boundaries fall on valid UTF-8 boundaries. Returns the substring or empty string if positions are invalid.

func ShortRoot added in v1.0.0

func ShortRoot(root string, width int) string

ShortRoot names a directory in width cells: home-relative if it is under the user's home, then the last couple of path segments, then the basename — and when even the basename is too long, the basename with its middle elided.

The last resort is a truncation rather than nothing, because a label that disappears is worse than a label that is short: this very checkout is named `sidecar-files-panel-improvements`, 32 cells against a budget of 28, and the counts row simply had no root on it at any width. Both ends of the name are kept, for the reason trimSegment keeps both: a project's worktrees share a prefix and differ in the suffix.

A search surface that does not say what it is searching is a surface that can answer "No matches found" about a directory the user is not looking at — the pane's root and the checkout on screen are routinely different in a global workspace.

func SkeletonTick

func SkeletonTick() tea.Cmd

SkeletonTick returns a command to start/continue the skeleton animation. Call this from your plugin's Start() or when enabling the skeleton.

func TruncateAnchored added in v1.0.0

func TruncateAnchored(s string, width int, hlStart, hlEnd int) (string, int, int)

TruncateAnchored fits s into width cells around the highlighted range. The match itself is never given up while it fits, and the cells left over go to the parts of the line that tell one row from another:

  • Leading context is bought only when the match and a useful amount of what follows it are already paid for (leadRoom). Below that the window starts at the match, with no leading ellipsis: in a pane budget of a dozen cells, "… " is two cells spent saying nothing, and it was two of the cells that would have carried the end of the line.
  • When what follows the match will not fit either, the middle of the remainder is elided rather than its end. Eight rows of "**File:** `internal/plugins/workspace/…`" differ only in their last few characters; a window that runs forward from the match renders all eight identically, while one that keeps the line's end tells them apart.

Positions are rune indices, in and out.

func TruncateStart

func TruncateStart(s string, width int) string

TruncateStart truncates the start of the string if it exceeds width. The suffix is kept, prefixed with "…" so a path keeps its filename end.

func TruncateString

func TruncateString(s string, width int) string

TruncateString truncates a string to the given visual width. It handles multi-byte characters and full-width characters correctly. If the string is truncated, "..." is appended (and accounted for in width). Pre-condition: width should be at least 3.

func VisualColAtRelativeX

func VisualColAtRelativeX(expandedLine string, relX int) int

VisualColAtRelativeX takes an already-expanded line and a relative X offset, walks graphemes using ansi.GraphemeWidth.DecodeSequenceInString, snaps to character boundaries, and clamps to last char if beyond end.

func VisualSubstring

func VisualSubstring(s string, startCol, endCol int) string

VisualSubstring extracts a substring by visual column range [startCol, endCol). endCol is EXCLUSIVE (one past last included column). Handles ANSI escape codes (skipped in column counting). If endCol is -1, extracts to end of string. Returns plain text (ANSI stripped) for clipboard use.

Types

type BrailleSpinner

type BrailleSpinner struct {
	// contains filtered or unexported fields
}

BrailleSpinner renders an animated braille dot pattern. It is a passive component — it does not generate its own ticks. Call Tick() from an existing SkeletonTickMsg handler to advance the frame.

func NewBrailleSpinner

func NewBrailleSpinner() BrailleSpinner

NewBrailleSpinner creates a new braille spinner (inactive by default).

func (BrailleSpinner) IsActive

func (b BrailleSpinner) IsActive() bool

IsActive returns whether the spinner is running.

func (*BrailleSpinner) Start

func (b *BrailleSpinner) Start()

Start marks the spinner as active.

func (*BrailleSpinner) Stop

func (b *BrailleSpinner) Stop()

Stop halts the animation.

func (*BrailleSpinner) Tick

func (b *BrailleSpinner) Tick()

Tick advances the animation frame. Call this from a SkeletonTickMsg handler.

func (BrailleSpinner) View

func (b BrailleSpinner) View() string

View renders the current spinner frame.

func (BrailleSpinner) ViewFill

func (b BrailleSpinner) ViewFill(width int, label string) string

ViewFill renders the spinner centered in the given width, with a label.

type Canvas added in v0.99.0

type Canvas struct {
	// contains filtered or unexported fields
}

Canvas composes pre-rendered blocks at absolute rectangles. A layout that already placed every block has one geometry; joining those blocks back together with per-row string arithmetic derives a second one, which is what makes a divider drift once the nesting is deeper than a single split.

Blitted rectangles must not overlap: a block is clipped and padded to the rectangle it was given, but a later block landing inside an earlier one is dropped, because cutting a cell range out of already-composited ANSI would have to re-derive the styling that produced it.

func NewCanvas added in v0.99.0

func NewCanvas(w, h int) *Canvas

NewCanvas returns a canvas of w columns and h rows, blank until blitted onto.

func (*Canvas) Blit added in v0.99.0

func (c *Canvas) Blit(box mouse.Rect, content string)

Blit places content in box, in canvas-relative cells. Content lines are clipped and padded to the box's width and count, so a block that renders short or long cannot move the blocks beside it; a box that starts outside the canvas is dropped rather than clipped from the left, which would cut a block mid-escape-sequence. Tabs are the block's own business: every renderer that reaches a canvas has already expanded them against its own width, and expanding them again here would be a second authority on the same cells.

func (*Canvas) String added in v0.99.0

func (c *Canvas) String() string

String renders the canvas as h rows of exactly w cells. A block that left a style open is closed at its own last cell: cell isolation is not isolation on its own, because an unclosed attribute paints the divider and every block to its right on that row.

type ConfirmDialog

type ConfirmDialog struct {
	Title        string
	Message      string
	ConfirmLabel string      // e.g., " Confirm ", " Delete ", " Yes "
	CancelLabel  string      // e.g., " Cancel ", " No "
	BorderColor  color.Color // Modal border color
	Width        int         // Modal width (default 50)
}

ConfirmDialog is a reusable confirmation modal with interactive buttons.

func NewConfirmDialog

func NewConfirmDialog(title, message string) *ConfirmDialog

NewConfirmDialog creates a dialog with sensible defaults.

func (*ConfirmDialog) ToModal

func (d *ConfirmDialog) ToModal() *modal.Modal

ToModal adapts the dialog configuration into a modal.Modal instance.

type HandleState added in v1.0.0

type HandleState int

HandleState is the pointer state of a 1-cell drag handle.

const (
	HandleIdle HandleState = iota
	HandleHover
	HandleDrag
)

func HandleStateFrom added in v1.0.0

func HandleStateFrom(hovering, dragging bool) HandleState

HandleStateFrom reports drag over hover over idle.

type HeaderClose added in v1.0.0

type HeaderClose struct {
	// TabsWidth is the columns left for the tab strip. Equals Width when the
	// button does not fit.
	TabsWidth int
	// CloseCol is the column of the button relative to the header origin.
	// -1 when the button is not drawn.
	CloseCol int
	CloseW   int
	Width    int
}

HeaderClose is the reserved right-edge close control on a pane header.

func ReserveHeaderClose added in v1.0.0

func ReserveHeaderClose(width int) HeaderClose

ReserveHeaderClose keeps the close button whole on the right and gives the rest of the row to the tab strip. A row too narrow to hold the button draws no button: a clipped X is a target whose meaning cannot be recovered.

type ScrollbarParams

type ScrollbarParams struct {
	TotalItems   int // Total logical items in the list
	ScrollOffset int // Index of first visible item (scroll offset)
	VisibleItems int // Number of items that fit in the viewport
	TrackHeight  int // Height of the scrollbar track in terminal rows
}

ScrollbarParams configures a vertical scrollbar rendering.

type SelectionPoint

type SelectionPoint struct {
	Line int // buffer line index, -1 = unset
	Col  int // visual column, -1 = unset
}

SelectionPoint represents a position as (line, col) in visual space. Col is post-tab-expansion, accounting for multi-width chars. EndCol convention: INCLUSIVE — the character under the cursor IS selected.

func (SelectionPoint) Before

func (p SelectionPoint) Before(other SelectionPoint) bool

Before returns true if p is before other in document order.

func (SelectionPoint) Valid

func (p SelectionPoint) Valid() bool

Valid returns true if the point has been set.

type SelectionState

type SelectionState struct {
	Active      bool
	Rectangular bool
	Start       SelectionPoint
	End         SelectionPoint
	Anchor      SelectionPoint
	ViewRect    mouse.Rect
}

SelectionState holds all selection state for a single selectable region.

func (*SelectionState) Clear

func (s *SelectionState) Clear()

Clear resets all fields, Start/End/Anchor to {-1,-1}.

func (*SelectionState) ExtendTo added in v0.88.0

func (s *SelectionState) ExtendTo(current SelectionPoint)

ExtendTo extends the existing anchor to current.

func (*SelectionState) FinishDrag

func (s *SelectionState) FinishDrag()

FinishDrag completes a drag operation. If start not valid (no drag motion), calls Clear(). Otherwise sets Active=false.

func (*SelectionState) GetLineSelectionCols

func (s *SelectionState) GetLineSelectionCols(lineIdx int) (startCol, endCol int)

GetLineSelectionCols returns the visual column range [start, end] inclusive for the given line. Returns (-1,-1) if not selected. endCol==-1 means "to end of line". Logic: single-line returns both cols; first line of multi returns (startCol, -1); last line returns (0, endCol); middle returns (0, -1).

func (*SelectionState) HandleDrag

func (s *SelectionState) HandleDrag(lineIdx, col int)

HandleDrag updates selection state during a drag operation. If start not valid, initialize start=end=anchor. Set Active=true. Order start/end by document position relative to anchor.

func (*SelectionState) HasSelection

func (s *SelectionState) HasSelection() bool

HasSelection returns true if both Start and End are valid.

func (*SelectionState) IsLineSelected

func (s *SelectionState) IsLineSelected(lineIdx int) bool

IsLineSelected checks if line is in [Start.Line, End.Line].

func (*SelectionState) PrepareDrag

func (s *SelectionState) PrepareDrag(lineIdx, col int, viewRect mouse.Rect)

PrepareDrag stores the click position and starts drag tracking without initializing selection. Selection only activates on actual drag motion.

func (*SelectionState) PrepareDragMode added in v0.88.0

func (s *SelectionState) PrepareDragMode(lineIdx, col int, viewRect mouse.Rect, rectangular bool)

PrepareDragMode starts a character or rectangular drag.

func (*SelectionState) SelectRange added in v0.88.0

func (s *SelectionState) SelectRange(anchor, current SelectionPoint, rectangular bool)

SelectRange installs a complete selection and preserves anchor for future shift-extension gestures.

func (*SelectionState) SelectedText

func (s *SelectionState) SelectedText(lines []string, startLine int, tabWidth int) []string

SelectedText takes raw lines in the selected range starting at startLine index, expands tabs, extracts with column precision using VisualSubstring. For single-line: extract [startCol, endCol+1). For multi-line: first line from startCol to end, middle lines ANSI-stripped, last line from 0 to endCol+1.

type Skeleton

type Skeleton struct {
	// Configuration
	Rows      int   // Number of skeleton rows to display
	RowWidths []int // Width pattern for each row (cycles if fewer than Rows)
	// contains filtered or unexported fields
}

Skeleton renders animated placeholder rows with a shimmer effect.

func NewSkeleton

func NewSkeleton(rows int, rowWidths []int) Skeleton

NewSkeleton creates a skeleton loader with the given row count. RowWidths defines the relative width of each row (e.g., []int{80, 60, 75} for varied lengths). If rowWidths is nil, uses a default varied pattern.

func (Skeleton) IsActive

func (s Skeleton) IsActive() bool

IsActive returns whether the animation is running.

func (*Skeleton) Start

func (s *Skeleton) Start() tea.Cmd

Start begins the shimmer animation.

func (*Skeleton) Stop

func (s *Skeleton) Stop()

Stop halts the shimmer animation.

func (*Skeleton) Update

func (s *Skeleton) Update(msg tea.Msg) tea.Cmd

Update handles tick messages for animation.

func (Skeleton) View

func (s Skeleton) View(width int) string

View renders the skeleton rows with shimmer effect. width is the available content width.

type SkeletonTickMsg

type SkeletonTickMsg time.Time

SkeletonTickMsg is sent to update the shimmer animation frame.

type Span added in v1.0.0

type Span struct {
	SrcStart, SrcEnd, Dst int
}

Span records that out[Dst:Dst+(SrcEnd-SrcStart)] is a verbatim copy of src[SrcStart:SrcEnd]. ElidePath returns one per surviving run so a caller holding byte ranges into the original string (fuzzy-match highlights) can translate them onto the elided text instead of throwing them away.

func ElidePath added in v1.0.0

func ElidePath(path string, width int) (string, []Span)

ElidePath fits a path into width cells while keeping the parts that tell one row from another. Rows in a result list usually share a leading prefix, so the outermost directories are the least informative thing on the line and are spent first — but only as far as the budget demands:

.claude/skills/create-modal/SKILL.md at 30  ->  .c…/s…/create-modal/SKILL.md
.claude/skills/create-modal/SKILL.md at 22  ->  .c…/s…/cre…al/SKILL.md

Every cut is marked with an ellipsis, at every width and in every segment: a path that has been shortened must not read as a path that exists (see markAbbrev).

Degrading gradually is the whole point. Spending a directory outright when a single cell was needed is how a list of siblings turns into a page of identical rows: an all-or-nothing fallback that missed its budget by one cell used to throw the entire head away, and `.c` versus `.a` is routinely the only thing that differs between two rows.

The order of sacrifice is: shorten outermost directories, then collapse the middle ones into a single "…", then — and only then — cut into the filename, from its front, so the end of the name and its extension survive. The leading segment and the filename are what a reader recognises a row by, so they are the last things to go, never the first.

type TruncateCache

type TruncateCache struct {
	// contains filtered or unexported fields
}

TruncateCache provides cached ANSI-aware truncation to eliminate allocation churn. Thread-safe for concurrent access from rendering goroutines.

func NewTruncateCache

func NewTruncateCache(maxSize int) *TruncateCache

NewTruncateCache creates a new truncation cache with the given maximum size. maxSize limits memory growth; when exceeded, the cache is cleared.

func (*TruncateCache) Clear

func (c *TruncateCache) Clear()

Clear removes all cached entries. Should be called when window resizes to avoid stale results.

func (*TruncateCache) Size

func (c *TruncateCache) Size() int

Size returns the current number of cached entries (for testing/monitoring).

func (*TruncateCache) Truncate

func (c *TruncateCache) Truncate(content string, width int, tail string) string

Truncate returns the content truncated to width using ANSI-aware truncation. Results are cached to avoid repeated parser allocations.

func (*TruncateCache) TruncateLeft

func (c *TruncateCache) TruncateLeft(content string, offset int, tail string) string

TruncateLeft returns the content truncated from the left to width using ANSI-aware truncation. Results are cached to avoid repeated parser allocations. NOTE: For horizontal scrolling with varying offsets, prefer TruncateLeftRight to avoid cache thrashing. Each unique offset creates a new cache entry.

func (*TruncateCache) TruncateLeftRight

func (c *TruncateCache) TruncateLeftRight(content string, leftOffset int, width int) string

TruncateLeftRight applies a left offset and then truncates to width. This is optimized for horizontal scrolling where the offset varies frequently. To prevent cache thrashing, offsets are normalized (rounded down to nearest 5).

Benefits: - Reduces cache key variance from millions of possible offsets to ~1000 - Combines two parse operations into one (width+offset in single pass) - High cache hit rate for repeated/back-and-forth scrolling

This prevents cellbuf allocation churn that occurs when TruncateLeft is called with constantly-varying offset values.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL