ansi

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Cp437ToUnicode = [256]rune{}/* 256 elements not displayed */

This array maps CP437 bytes (0-255) to their Unicode equivalents

View Source
var UnicodeToCP437 = map[rune]byte{}/* 125 elements not displayed */

Reverse map: Unicode Rune -> CP437 Byte (for specific characters needed) Generated carefully to avoid duplicates where multiple runes might map from one byte.

Functions

func ApplyWidthConstraint

func ApplyWidthConstraint(s string, width int) string

ApplyWidthConstraint truncates and/or pads a string to exact width (left-aligned). ANSI escape sequences are preserved during truncation.

func ApplyWidthConstraintAligned

func ApplyWidthConstraintAligned(s string, width int, align Alignment) string

ApplyWidthConstraintAligned truncates and/or pads a string to exact width with the specified alignment. ANSI escape sequences are preserved during truncation.

func CP437BytesToUTF8

func CP437BytesToUTF8(data []byte) []byte

CP437BytesToUTF8 converts raw CP437 bytes to UTF-8, preserving ANSI escape sequences. Use this before doing string operations (e.g. placeholder substitution) on ANS file content so that the writer pipeline receives unambiguous UTF-8 instead of raw CP437 bytes that might accidentally form valid UTF-8 sequences and get misinterpreted.

func ClearScreen

func ClearScreen() string

Example placeholder functions (if they were used externally):

func CursorBackward

func CursorBackward(n int) string

CursorBackward returns a CSI CUB sequence that moves the cursor left by n columns. This is universally supported and avoids reliance on cursor save/restore, which is inconsistent across terminal emulators.

func DisplayComprehensiveSolution

func DisplayComprehensiveSolution(session ssh.Session, filename string) error

This function is a comprehensive solution for displaying CP437 ANSI art It tries multiple strategies and includes detailed debugging. **NOTE:** This function seems largely redundant with DisplayAnsiFile now. Keeping it as defined in the prompt, but consider merging/removing. The main difference is the direct VT100 attempt and more debug prints.

func DisplayWithASCIIFallback

func DisplayWithASCIIFallback(session ssh.Session, filename string) error

Strategy 2: Use ASCII Fallbacks

func DisplayWithRawBytes

func DisplayWithRawBytes(session ssh.Session, filename string) error

Strategy 4: Use Raw Bytes (After Pipe Code Replacement)

func DisplayWithStandardUTF8

func DisplayWithStandardUTF8(session ssh.Session, filename string) error

Strategy 3: Use Standard UTF-8 Conversion

func DisplayWithVT100LineDrawing

func DisplayWithVT100LineDrawing(session ssh.Session, filename string) error

Strategy 1: Use VT100 Line Drawing Mode

func FindEditorColorAtPos

func FindEditorColorAtPos(template []byte, targetRow, targetCol int) string

FindEditorColorAtPos returns the ANSI SGR escape sequence active at the specified terminal row and column (both 1-based) in the raw template bytes. It processes ANSI escape sequences (which update SGR state without advancing the column counter) before checking the column position, so the returned state accurately reflects the color that would apply when drawing the character at that column.

Use this to capture the color context of a specific template cell for cursor-overlay rendering — for example, to get the dark shade color at the ░ padding position adjacent to a dynamic number field.

Returns "" if the target position is not reached in the template.

func FindEditorPlaceholderPos

func FindEditorPlaceholderPos(template []byte, code byte) (row, col int, colorEsc string)

FindEditorPlaceholderPos returns the terminal row and column (both 1-based) at which the first occurrence of a placeholder for the given code letter begins in template, along with the ANSI SGR escape sequence that restores the color/attribute state active at that position. This lets callers dynamically overwrite the placeholder later while preserving the original template colors.

It works by scanning through the raw template bytes (before substitution) and tracking the terminal cursor position via ANSI CSI escape sequences. Because visual-width placeholders (@X####@) occupy the same byte count as their rendered field width, cursor tracking against the raw template gives the same result as tracking the rendered output.

Returns (0, 0, "") if the placeholder is not found.

func GetAnsiFileContent

func GetAnsiFileContent(filename string) ([]byte, error)

GetAnsiFileContent reads an ANSI file and returns its raw byte content. It replaces the previous DisplayAnsiFile which incorrectly wrote directly. SAUCE metadata (if present) is automatically stripped from the returned content.

func MoveCursor

func MoveCursor(row, col int) string

MoveCursor returns an ANSI escape sequence to move the cursor to the specified row and column. Rows and columns are 1-indexed (1,1 is top-left).

func PadVisible

func PadVisible(s string, width int, padChar rune) string

PadVisible pads a string to the specified width using the given pad character. ANSI escape sequences do not count toward the width.

func ProcessEditorPlaceholders

func ProcessEditorPlaceholders(template []byte, substitutions map[byte]string) []byte

ProcessEditorPlaceholders replaces @CODE@ placeholders in editor template files.

Supported formats:

@S@          — insert value as-is (no width constraint)
@S:20@       — explicit width: truncate/pad to exactly 20 visible characters
@S########@  — visual width: total placeholder length (including delimiters) is the field width
@S|R8@       — right-justify in 8-char field (Synchronet-style width)
@S|R:20@     — right-justify in 20-char field (explicit colon width)
@S|R#######@ — right-justify in visual-width field
@S|C:20@     — center in 20-char field

Unknown codes (not present in substitutions) are preserved unchanged. Color ANSI codes within values are preserved during truncation via ApplyWidthConstraintAligned.

func ReplacePipeCodes

func ReplacePipeCodes(data []byte) []byte

Helper function to replace pipe codes with ANSI sequences It should ONLY replace |XX codes and pass through all other bytes. Simplified version: Removed complex ||XX handling for now.

func RestoreCursor

func RestoreCursor() string

RestoreCursor returns ANSI escape sequences to restore the cursor to the previously saved position. Both SCO (\x1b[u) and DEC (DECRC: \x1b8) forms are emitted for broad compatibility.

func SaveCursor

func SaveCursor() string

SaveCursor returns ANSI escape sequences to save the current cursor position. Both SCO (\x1b[s) and DEC (DECSC: \x1b7) forms are emitted so that the widest range of terminal emulators will honor at least one.

func StripAnsi

func StripAnsi(str string) string

Add StripAnsi if it was used externally

func TruncateVisible

func TruncateVisible(s string, maxVisible int) string

TruncateVisible truncates a string to maxVisible characters while preserving ANSI codes. ANSI escape sequences are kept intact and do not count toward the visible character limit.

func VisibleLength

func VisibleLength(s string) int

VisibleLength returns the display width of a string, ignoring ANSI escape sequences. This counts only the characters that would be visible on screen.

Types

type Alignment

type Alignment int

Alignment specifies how a value is positioned within its field width.

const (
	AlignLeft   Alignment = iota // Pad right (default)
	AlignRight                   // Pad left
	AlignCenter                  // Pad both sides
)

func ParseAlignment

func ParseAlignment(modifier string) Alignment

ParseAlignment returns the Alignment for a single-character modifier string. Recognized values: "L" (left), "R" (right), "C" (center). Returns AlignLeft for any unrecognized value.

type OutputMode

type OutputMode int

OutputMode defines the character encoding strategy for terminal output.

const (
	OutputModeAuto  OutputMode = iota // Default: Detect based on TERM variable
	OutputModeUTF8                    // Force UTF-8 character output
	OutputModeCP437                   // Force raw CP437 byte output
)

type ProcessAnsiResult

type ProcessAnsiResult struct {
	DisplayBytes []byte                        // The processed bytes with standard ANSI escapes, ready for display.
	FieldCoords  map[string]struct{ X, Y int } // Map of |XX or ~XX codes to their calculated coordinates.
	FieldColors  map[string]string             // Map of |XX or ~XX codes to their ANSI color escape sequence at that position.
}

ProcessAnsiResult holds the results of processing an ANSI file, including field coordinates.

func ProcessAnsiAndExtractCoords

func ProcessAnsiAndExtractCoords(rawContent []byte, outputMode OutputMode) (ProcessAnsiResult, error)

ProcessAnsiAndExtractCoords processes raw CP437 byte content containing ViSiON/2 codes and ANSI escapes. It translates ViSiON codes to standard ANSI, handles cursor positioning, extracts coordinates for field codes (|XX, ~XX), strips specific codes, and returns the final byte slice for display and the coordinate map. Added outputMode parameter to control character encoding.

Jump to

Keyboard shortcuts

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