widthx

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package widthx implements Pi's terminal width, grapheme and ANSI operations with JavaScript UTF-16 semantics. Ports packages/tui/src/utils.ts

Index

Constants

View Source
const CursorMarker = "\x1b_pi:c\x07"

CursorMarker is the APC sequence that signals "the focusable cursor is here" when emitted in rendered component output. Already covered by ExtractAnsi as a regular APC sequence (so it does NOT count toward VisibleWidth and IS stripped by StripAnsi).

View Source
const SegmentReset = "\x1b[0m\x1b]8;;\x07"

SegmentReset is the hard ANSI/OSC barrier appended to non-image lines after rendering. It resets all SGR attributes and closes any open OSC 8 hyperlink. Mirrors upstream TUI.SEGMENT_RESET (`"\x1b[0m\x1b]8;;\x07"`).

Variables

This section is empty.

Functions

func ApplyLineReset

func ApplyLineReset(line string) string

ApplyLineReset applies terminal normalization and appends the `SegmentReset` barrier to a single non-image line. Image lines are returned unchanged. This is the per-row body of upstream `TUI.applyLineResets` (tui.ts:427), factored out so callers can apply it selectively (e.g. an index-aligned reuse cache) without duplicating the rule.

func ApplyLineResets

func ApplyLineResets(lines []string) []string

ApplyLineResets returns a new slice where every non-image line has the `SegmentReset` barrier appended. Image lines are returned unchanged.

Mirrors upstream `TUI.applyLineResets` (tui.ts:427). The reset suffix is required to prevent SGR / OSC 8 hyperlink state from bleeding between adjacent rendered lines.

Returns a new slice; the input slice is not mutated.

func EastAsianWidth

func EastAsianWidth(r rune) int

EastAsianWidth mirrors get-east-asian-width's eastAsianWidth(cp): 2 for Fullwidth/Wide, else 1.

func ExtractAnsi

func ExtractAnsi(s string, i int) int

ExtractAnsi returns the byte length of the ANSI escape starting at byte offset i in s, or 0 if none begins there. It is upstream extractAnsiCode exactly (via ExtractAnsiCode): a CSI runs to the first m|G|K|H|J, whatever comes between, and OSC/APC run to BEL or ST. Width must match Pi byte for byte because PiG adopts Pi's crash-on-overflow render check; the former D47 h/l extension and bail-on-unknown-final-byte rule made PiG measure some strings wider than Pi does.

func ExtractAnsiCode

func ExtractAnsiCode(s string, pos int) (code string, length int)

ExtractAnsiCode returns the ANSI escape beginning at byte offset pos in s (the matched substring and its byte length) or ("", 0) when none begins there. Mirrors upstream extractAnsiCode: CSI ends at m|G|K|H|J; OSC/APC end at BEL or ST (ESC \).

func FirstGrapheme

func FirstGrapheme(s string) (cluster, rest string)

FirstGrapheme returns the first extended grapheme cluster of s and the remainder, following UAX #29 as implemented by ICU's Intl.Segmenter (including GB9c Indic conjuncts), with the Unicode version of the tables.

func FrameAt

func FrameAt(lines []string, frameWidth, width int) []string

FrameAt returns the rows of a pre-rendered component frame for painting at width. frameWidth is the width the frame was rendered at; 0 means the producer did not report one, and the rows are painted as rendered (an over-wide row then reaches the renderer's overflow check, as in Pi).

A frame rendered for any other width is stale and is never painted, whatever its rows contain: Pi always renders components at the current width. The caller has already requested a frame at the current width.

func GetActiveBackgroundAnsi

func GetActiveBackgroundAnsi(text string) string

GetActiveBackgroundAnsi returns only the background color active at the end of an ANSI-styled string. Mirrors upstream getActiveBackgroundAnsi.

func GetOsc8LinkAtColumn

func GetOsc8LinkAtColumn(line string, column int) (url string, ok bool)

GetOsc8LinkAtColumn returns the OSC 8 hyperlink URL covering visible column `column` in line, or ok=false when no active link covers it. Mirrors upstream getOsc8LinkAtColumn, including its tab-as-3-cells width rule.

func GraphemeCellRange

func GraphemeCellRange(line string, column int) (start, end int, ok bool)

GraphemeCellRange reports the [start, end) cell-column span of the grapheme occupying display column `column` in line, or ok=false if no grapheme covers it (past the end of visible content). ANSI escapes are skipped and contribute no width. Mirrors upstream getGraphemeCellRange.

func GraphemeWidth

func GraphemeWidth(seg string) int

GraphemeWidth is upstream graphemeWidth(segment) for one cluster produced by FirstGrapheme.

func IsCJKBreak

func IsCJKBreak(s string) bool

IsCJKBreak reports whether s contains a code point matching upstream's cjkBreakRegex.

func IsImageLine

func IsImageLine(line string) bool

IsImageLine reports whether a rendered line contains a Kitty or iTerm2 image graphics sequence. Image lines MUST NOT receive the `SegmentReset` suffix because the trailing reset can corrupt the image protocol payload.

Mirrors upstream `isImageLine` (terminal-image.ts:106). Checks both the fast prefix path (single-row images) and a contains-scan (multi-row images that begin with a cursor-up movement before the graphics sequence).

Both prefixes start with ESC, so one pass over the line's ESC bytes answers both contains-scans; styled rows otherwise pay two full searches each time the frame asks (clamp, reset, scrollbar and image-redraw checks).

func IsJSSpace

func IsJSSpace(r rune) bool

IsJSSpace reports whether r matches JavaScript's \s.

func JSTrim

func JSTrim(s string) string

JSTrim is String.prototype.trim.

func JSTrimEnd

func JSTrimEnd(s string) string

JSTrimEnd is String.prototype.trimEnd.

func NormalizeTerminalOutput

func NormalizeTerminalOutput(s string) string

NormalizeTerminalOutput encodes unpaired UTF-16 units like Node's UTF-8 terminal writes, then rewrites Thai/Lao AM vowels to compatibility decompositions that preserve logical content while avoiding stale-cell artifacts in some terminal differential repaints. Visible tabs are expanded to the fixed layout width (3 spaces, matching VisibleWidth) so terminal tab stops cannot wrap a logical line; tabs inside ANSI sequences stay untouched.

func SliceByColumn

func SliceByColumn(line string, startCol, length int, strict bool) string

SliceByColumn extracts a range of visible columns [startCol, startCol+length) from a line. ANSI codes are preserved. If `strict` is true, a wide character that would extend past the end column is excluded.

Mirrors upstream `sliceByColumn`.

func StripAnsi

func StripAnsi(s string) string

StripAnsi removes recognized ANSI/OSC/APC sequences from s. Other escape sequences (e.g. cursor movement CSI A/B/C/D) are left intact: matches upstream's behavior.

func StripTerminalSequences

func StripTerminalSequences(s string) string

StripTerminalSequences removes ANSI/OSC/APC escapes from s, leaving only printable content with the upstream-compatible layout extractor.

func TruncateToWidth

func TruncateToWidth(text string, maxWidth int, ellipsis string, pad bool) string

TruncateToWidth truncates text to fit within `maxWidth` visible columns, appending `ellipsis` (default "...") when truncation occurs. If `pad` is true, the result is padded with trailing spaces to exactly `maxWidth` columns. Mirrors upstream `truncateToWidth`.

ANSI escape codes do not count toward width. Tabs expand to 3 columns to match upstream.

func VisibleWidth

func VisibleWidth(s string) int

VisibleWidth returns the display column width of s, mirroring upstream's `visibleWidth`:

  • Tabs expand to 3 spaces (NOT 8): matches upstream
  • CSI/OSC/APC sequences stripped before measuring
  • Width per grapheme via GraphemeWidth (upstream graphemeWidth)

func WrapTextWithAnsi

func WrapTextWithAnsi(text string, width int) []string

WrapTextWithAnsi wraps text to `width` visible columns per line, preserving active ANSI SGR and OSC 8 hyperlink state across line breaks. Returns at least one line.

Mirrors upstream `wrapTextWithAnsi`. ONLY does word wrapping: no padding, no background colors.

Types

type AnsiCodeTracker

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

AnsiCodeTracker tracks SGR state and active OSC 8 hyperlink across a stream of ANSI codes. Mirrors upstream `AnsiCodeTracker`.

func (*AnsiCodeTracker) ActiveBackgroundCode

func (t *AnsiCodeTracker) ActiveBackgroundCode() string

ActiveBackgroundCode returns only the active background SGR, or "". Mirrors upstream AnsiCodeTracker.getActiveBackgroundCode.

func (*AnsiCodeTracker) ActiveCodes

func (t *AnsiCodeTracker) ActiveCodes() string

ActiveCodes returns the ANSI escape string needed to re-establish the currently active styling. Returns "" if no styling is active.

func (*AnsiCodeTracker) Clear

func (t *AnsiCodeTracker) Clear()

Clear resets the entire tracker including hyperlink state. Used to reuse a pooled instance.

func (*AnsiCodeTracker) HasActiveCodes

func (t *AnsiCodeTracker) HasActiveCodes() bool

HasActiveCodes reports whether any styling or hyperlink is currently active.

func (*AnsiCodeTracker) LineEndReset

func (t *AnsiCodeTracker) LineEndReset() string

LineEndReset returns the escape string needed at end-of-line to prevent underline from bleeding into padding and to close any active OSC 8 hyperlink. The hyperlink is re-opened at the start of the next line via ActiveCodes(). Returns "" if no reset is needed.

Mirrors upstream `getLineEndReset`.

func (*AnsiCodeTracker) Process

func (t *AnsiCodeTracker) Process(code string)

Process applies a single ANSI escape code to the tracker. The code must be a complete escape sequence as returned by ExtractAnsi.

func (*AnsiCodeTracker) UpdateFromText

func (t *AnsiCodeTracker) UpdateFromText(text string)

UpdateFromText scans text, extracts every ANSI code, and processes it through the tracker. Mirrors upstream `updateTrackerFromText`.

type CursorPosition

type CursorPosition struct {
	Row, Col int
}

CursorPosition is the (row, col) of an extracted cursor marker.

func ExtractCursorPosition

func ExtractCursorPosition(lines []string, height int) (CursorPosition, bool)

ExtractCursorPosition searches the bottom `height` lines of `lines` for the first occurrence of CursorMarker, mutates `lines` in place to strip the marker, and returns its position. Returns (CursorPosition{}, false) if no marker is present.

Mirrors upstream `TUI.extractCursorPosition` (tui.ts:868). The visual column is computed via VisibleWidth on the text preceding the marker, so it is grapheme-aware and ignores any prior ANSI styling.

type SegmentsResult

type SegmentsResult struct {
	Before      string
	BeforeWidth int
	After       string
	AfterWidth  int
}

SegmentsResult is the return shape of ExtractSegments.

func ExtractSegments

func ExtractSegments(line string, beforeEnd, afterStart, afterLen int, strictAfter bool) SegmentsResult

ExtractSegments extracts the "before" and "after" segments around an overlay region in a single pass over `line`. SGR/hyperlink styling that was active just before the overlay's start column is prepended to the "after" segment so the overlay does not visually break style continuity.

`beforeEnd` = first column NOT in "before" segment `afterStart` = first column of "after" segment `afterLen` = number of columns in "after" segment (0 = before-only) `strictAfter` = exclude wide char at the end that would overrun afterEnd

Mirrors upstream `extractSegments`. The shared pooled tracker in upstream is replaced here by a fresh local tracker per call: the function is already at the inner loop of overlay compositing and a stack-allocated tracker is essentially free.

type SliceResult

type SliceResult struct {
	Text  string
	Width int
}

SliceResult is the return shape of SliceWithWidth.

func SliceWithWidth

func SliceWithWidth(line string, startCol, length int, strict bool) SliceResult

SliceWithWidth is like SliceByColumn but also returns the actual visible width of the result. Mirrors upstream `sliceWithWidth`.

Jump to

Keyboard shortcuts

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