editor

package
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

internal/editor/buffer.go

internal/editor/cursor.go

internal/editor/display.go

internal/editor/editor.go

internal/editor/ghost.go

internal/editor/input.go

internal/editor/insert.go

internal/editor/key.go

internal/editor/mode.go

internal/editor/normal.go

internal/editor/undo.go

Index

Constants

View Source
const DefaultMaxPasteSize uint = 10 * 1024 * 1024

DefaultMaxPasteSize is the default maximum size of pasted content (10MB). Prevents memory exhaustion from extremely large pastes.

Variables

This section is empty.

Functions

func AnnotateDuration

func AnnotateDuration(out io.Writer, termWidth, outputLines, cmdLines int, durationMs int64, bgColor string)

AnnotateDuration writes execution duration to the right side of a previous command line. Call after command execution. outputLines = lines of output, cmdLines = lines of command.

Types

type Action

type Action int

Action describes what happened for undo grouping.

const (
	ActionNone Action = iota
	ActionInsert
	ActionDelete
	ActionPaste
	ActionModeChange
)

type Buffer

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

Buffer holds the text content as a slice of lines.

func NewBuffer

func NewBuffer() *Buffer

NewBuffer creates an empty buffer with one empty line.

func NewBufferFromString

func NewBufferFromString(s string) *Buffer

NewBufferFromString creates a buffer from a string.

func (*Buffer) Clone

func (b *Buffer) Clone() *Buffer

Clone creates a deep copy of the buffer.

func (*Buffer) Content

func (b *Buffer) Content() string

Content returns the full buffer content with newlines.

func (*Buffer) Delete

func (b *Buffer) Delete(from, to Position)

Delete removes text between two positions.

func (*Buffer) Insert

func (b *Buffer) Insert(row, col int, text string)

Insert inserts text at the given position.

func (*Buffer) Line

func (b *Buffer) Line(row int) string

Line returns the content of a line (0-indexed).

func (*Buffer) LineCount

func (b *Buffer) LineCount() int

LineCount returns the number of lines.

func (*Buffer) ReplaceLine

func (b *Buffer) ReplaceLine(row int, content string)

ReplaceLine replaces the content of a line (0-indexed).

type Completion

type Completion struct {
	Text        string
	Description string
}

Completion represents a completion candidate.

type CompletionItem

type CompletionItem struct {
	Text        string
	Description string
}

CompletionItem is passed to display for rendering.

type Config

type Config struct {
	Keybindings    string                                   // "helix", "emacs", "vim"
	HistoryFunc    func(dir int, currentLine string) string // -1=prev, +1=next; currentLine is for saving
	CompleteFunc   func(line string, pos int) []Completion  // Tab completion
	PrefetchFunc   func(line string, pos int)               // Background completion prefetch (on space)
	OnInputReady   func()                                   // Called after editor chrome is rendered, before input loop
	Gutter         bool                                     // Show gutter indicator
	Prompt         string                                   // Prompt string to display before input
	InputBgColor   string                                   // Background color for submitted input (hex)
	ScrollbarColor string                                   // Foreground color for scrollbars (hex)
	MaxPasteSize   uint                                     // Maximum paste size in bytes (default 10MB)
}

Config configures the editor.

type Cursor

type Cursor struct {
	Pos    Position  // Current cursor position
	Anchor *Position // Selection anchor (nil if no selection)
}

Cursor tracks position and optional selection anchor.

func NewCursor

func NewCursor() *Cursor

NewCursor creates a cursor at position 0,0.

func (*Cursor) Clamp

func (c *Cursor) Clamp(buf *Buffer)

Clamp ensures cursor is within buffer bounds.

func (*Cursor) ClearSelection

func (c *Cursor) ClearSelection()

ClearSelection removes the selection.

func (*Cursor) Clone

func (c *Cursor) Clone() *Cursor

Clone creates a deep copy of the cursor.

func (*Cursor) HasSelection

func (c *Cursor) HasSelection() bool

HasSelection returns true if there's an active selection.

func (*Cursor) MoveTo

func (c *Cursor) MoveTo(row, col int)

MoveTo moves the cursor to a new position.

func (*Cursor) SelectionRange

func (c *Cursor) SelectionRange() (start, end Position)

SelectionRange returns start and end positions (normalized so start < end).

func (*Cursor) StartSelection

func (c *Cursor) StartSelection()

StartSelection begins a selection at the current position.

type Display

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

Display handles terminal rendering.

func NewDisplay

func NewDisplay(out io.Writer, width, height int) *Display

NewDisplay creates a new display.

func (*Display) AnnotateDuration

func (d *Display) AnnotateDuration(outputLines int, durationMs int64)

AnnotateDuration adds execution duration to the right side of the command line. Must be called after command execution, with outputLines = lines of command output.

func (*Display) Clear

func (d *Display) Clear()

Clear clears the display area.

func (*Display) ClearCompletionMenu

func (d *Display) ClearCompletionMenu(numItems int)

ClearCompletionMenu removes the completion menu from display.

func (*Display) Finalize

func (d *Display) Finalize(buf *Buffer)

Finalize leaves the content on screen and moves to a new line. Re-renders with background highlight to distinguish from output.

func (*Display) FinalizedLines

func (d *Display) FinalizedLines() int

FinalizedLines returns how many lines were rendered by Finalize. Used to position cursor for post-execution annotations.

func (*Display) Render

func (d *Display) Render(buf *Buffer, cur *Cursor, hasSelection bool)

Render draws the buffer content with cursor.

func (*Display) RenderCompletionMenu

func (d *Display) RenderCompletionMenu(items []CompletionItem, selected, startCol int)

RenderCompletionMenu draws the completion dropdown below the cursor.

func (*Display) RenderWithGhost

func (d *Display) RenderWithGhost(buf *Buffer, cur *Cursor, hasSelection bool, ghostText string, streaming, fromAgent bool, modelName string)

RenderWithGhost draws the buffer with inline ghost text suggestion. Ghost text appears after the cursor in dim gray, showing the suggested completion. fromAgent indicates whether this is an agent suggestion (show hints) or prediction (fish-style).

func (*Display) Resize

func (d *Display) Resize(width, height int)

Resize updates the terminal dimensions.

func (*Display) SetGutter

func (d *Display) SetGutter(enabled bool)

SetGutter enables/disables the gutter indicator.

func (*Display) SetInputBgColor

func (d *Display) SetInputBgColor(hexColor string)

SetInputBgColor sets the background color for submitted input. hexColor should be in format "#RRGGBB".

func (*Display) SetMode

func (d *Display) SetMode(mode string)

SetMode sets the current editor mode for gutter display.

func (*Display) SetPrompt

func (d *Display) SetPrompt(prompt string)

SetPrompt sets the prompt string to display before the first line.

func (*Display) SetPromptWidth

func (d *Display) SetPromptWidth(w int)

SetPromptWidth sets the prompt width for cursor positioning.

func (*Display) SetScrollbarColor

func (d *Display) SetScrollbarColor(hexColor string)

SetScrollbarColor sets the foreground color for scrollbars. hexColor should be in format "#RRGGBB".

type Editor

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

Editor is the main editor instance.

func New

func New(cfg Config, in io.Reader, out io.Writer) *Editor

New creates a new editor.

func (*Editor) ClearGhostText

func (e *Editor) ClearGhostText()

ClearGhostText removes any ghost text.

func (*Editor) Run

func (e *Editor) Run(ctx context.Context) (Result, error)

Run starts the editor and blocks until submit or cancel.

func (*Editor) SetGhostText

func (e *Editor) SetGhostText(text string)

SetGhostText sets inline suggestion text that appears after the cursor.

func (*Editor) SetGhostTextStreaming

func (e *Editor) SetGhostTextStreaming(textCh <-chan string, errCh <-chan error)

SetGhostTextStreaming sets up streaming ghost text from channels. Text chunks arrive on textCh, errors on errCh.

func (*Editor) SetInitialText

func (e *Editor) SetInitialText(text string)

SetInitialText sets the initial text in the editor buffer.

func (*Editor) SetPromptWidth

func (e *Editor) SetPromptWidth(cols int)

SetPromptWidth sets the prompt width for cursor positioning.

func (*Editor) SetStreamingModel

func (e *Editor) SetStreamingModel(model string)

SetStreamingModel sets the model name for "Thinking..." display.

type EditorState

type EditorState struct {
	Buffer    *Buffer
	Cursor    *Cursor
	UndoStack *UndoStack
}

EditorState holds the current editor state.

func NewEditorState

func NewEditorState() *EditorState

NewEditorState creates a new editor state.

type GhostText

type GhostText struct {
	Text       string // The full ghost text suggestion
	AcceptedAt int    // Number of characters already accepted (for partial acceptance)
	Active     bool   // Whether ghost text is currently displayed
	Streaming  bool   // Whether more text is still arriving
	FromAgent  bool   // True for agent suggestions (show hints), false for predictions (fish-style)
}

GhostText represents inline suggestion text that appears after the cursor. Ghost text is shown in dim gray and can be accepted with Tab or dismissed with Esc.

func NewGhostText

func NewGhostText() *GhostText

NewGhostText creates a new ghost text state.

func (*GhostText) AcceptAll

func (g *GhostText) AcceptAll() string

AcceptAll accepts all remaining ghost text. Returns the text that should be inserted.

func (*GhostText) AcceptChar

func (g *GhostText) AcceptChar() string

AcceptChar accepts the next character of ghost text. Returns the character that should be inserted.

func (*GhostText) AcceptWord

func (g *GhostText) AcceptWord() string

AcceptWord accepts the next word of ghost text. Returns the text that should be inserted.

func (*GhostText) Append

func (g *GhostText) Append(text string)

Append adds more text to the ghost (for streaming).

func (*GhostText) Clear

func (g *GhostText) Clear()

Clear removes the ghost text.

func (*GhostText) IsEmpty

func (g *GhostText) IsEmpty() bool

IsEmpty returns true if there's no ghost text.

func (*GhostText) Remaining

func (g *GhostText) Remaining() string

Remaining returns the unaccepted portion of ghost text.

func (*GhostText) Set

func (g *GhostText) Set(text string)

Set sets the ghost text content.

func (*GhostText) SetStreaming

func (g *GhostText) SetStreaming(streaming bool)

SetStreaming marks the ghost text as still receiving data.

type GhostTextChan

type GhostTextChan <-chan string

GhostTextChan is a channel that receives ghost text updates.

type InputReader

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

InputReader reads keys from a terminal.

func NewInputReader

func NewInputReader(in io.Reader) *InputReader

NewInputReader creates a new input reader.

func (*InputReader) DrainPending

func (r *InputReader) DrainPending()

DrainPending reads any immediately available input without blocking. This captures characters that may have been typed during terminal mode transitions. Call this right after enabling raw mode to recover any "lost" keystrokes.

func (*InputReader) ReadKey

func (r *InputReader) ReadKey() (Key, error)

ReadKey reads and parses the next key.

func (*InputReader) ReadKeyInterruptible

func (r *InputReader) ReadKeyInterruptible(done <-chan struct{}) (Key, error)

ReadKeyInterruptible reads and parses the next key, checking done channel periodically. If done is closed, returns context.Canceled error. This prevents goroutines from blocking indefinitely on stdin when the editor exits.

func (*InputReader) SetMaxPasteSize added in v0.4.3

func (r *InputReader) SetMaxPasteSize(size uint)

SetMaxPasteSize sets the maximum paste size in bytes.

type InsertMode

type InsertMode struct{}

InsertMode is the default text entry mode.

func NewInsertMode

func NewInsertMode() *InsertMode

NewInsertMode creates an insert mode handler.

func (*InsertMode) HandleKey

func (m *InsertMode) HandleKey(key Key, state *EditorState) ModeResult

HandleKey processes a key in insert mode.

func (*InsertMode) Name

func (m *InsertMode) Name() string

Name returns the mode name.

type Key

type Key struct {
	Rune      rune
	Special   KeyCode
	Ctrl      bool
	Alt       bool
	Shift     bool
	PasteText string // Content for KeyPaste (bracketed paste)
}

Key represents a parsed keypress.

func ParseKey

func ParseKey(b []byte) Key

ParseKey parses a byte sequence into a Key.

type KeyCode

type KeyCode int

KeyCode represents special keys.

const (
	KeyNone KeyCode = iota
	KeyEnter
	KeyTab
	KeyBackspace
	KeyDelete
	KeyEscape
	KeyUp
	KeyDown
	KeyLeft
	KeyRight
	KeyHome
	KeyEnd
	KeyPageUp
	KeyPageDown
	KeyPaste // Bracketed paste content
)

type Mode

type Mode interface {
	Name() string
	HandleKey(key Key, state *EditorState) ModeResult
}

Mode handles key input for a specific editing mode.

type ModeResult

type ModeResult struct {
	NewMode       Mode // Nil means stay in current mode
	Action        Action
	Submit        bool // True = user wants to execute
	Complete      bool // True = trigger completion
	Prefetch      bool // True = trigger completion prefetch (background)
	HistoryPrev   bool // True = navigate to previous history
	HistoryNext   bool // True = navigate to next history
	HistorySearch bool // True = launch history search (Ctrl+R)
	ContextPicker bool // True = launch context picker (Ctrl+P)
	Yank          bool // True = yank selection to clipboard
	Paste         bool // True = paste from clipboard
	PasteBefore   bool // True = paste before cursor (P)
}

ModeResult is returned by mode key handlers.

type NormalMode

type NormalMode struct{}

NormalMode handles Helix-style normal mode keybindings.

func NewNormalMode

func NewNormalMode() *NormalMode

NewNormalMode creates a normal mode handler.

func (*NormalMode) HandleKey

func (m *NormalMode) HandleKey(key Key, state *EditorState) ModeResult

HandleKey processes a key in normal mode.

func (*NormalMode) Name

func (m *NormalMode) Name() string

Name returns the mode name.

type Position

type Position struct {
	Row, Col int
}

Position represents a row/column position in the buffer.

type Result

type Result struct {
	Text          string
	Canceled      bool // Ctrl+C - interrupt
	EOF           bool // Ctrl+D - exit shell
	HistorySearch bool // Ctrl+R - launch history search
	ContextPicker bool // Ctrl+P - launch context picker
}

Result is returned when the editor exits.

type Snapshot

type Snapshot struct {
	Buffer *Buffer
	Cursor *Cursor
}

Snapshot holds buffer and cursor state for undo.

type UndoStack

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

UndoStack manages undo/redo history.

func NewUndoStack

func NewUndoStack() *UndoStack

NewUndoStack creates an empty undo stack.

func (*UndoStack) CanRedo

func (u *UndoStack) CanRedo() bool

CanRedo returns true if there's state to redo to.

func (*UndoStack) CanUndo

func (u *UndoStack) CanUndo() bool

CanUndo returns true if there's state to undo to.

func (*UndoStack) Push

func (u *UndoStack) Push(buf *Buffer, cur *Cursor)

Push adds a new state to the history, clearing any redo states.

func (*UndoStack) Redo

func (u *UndoStack) Redo() (*Buffer, *Cursor)

Redo returns the next state.

func (*UndoStack) Undo

func (u *UndoStack) Undo() (*Buffer, *Cursor)

Undo returns the previous state.

Jump to

Keyboard shortcuts

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