view

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultTheme = "mocha"

	// DefaultLanguage is the document language name used when no language
	// could be detected or was explicitly cleared
	DefaultLanguage = "text"

	BufferLineNever    BufferLine = "never"
	BufferLineAlways   BufferLine = "always"
	BufferLineMultiple BufferLine = "multiple"

	StatusLineMode             StatusLineElement = "mode"
	StatusLineFileBaseName     StatusLineElement = "file-base-name"
	StatusLineFileName         StatusLineElement = "file-name"
	StatusLineFileAbsolutePath StatusLineElement = "file-absolute-path"
	StatusLineReadOnly         StatusLineElement = "read-only-indicator"
	StatusLineFileEncoding     StatusLineElement = "file-encoding"
	StatusLineFileLineEnding   StatusLineElement = "file-line-ending"
	StatusLineFileIndentStyle  StatusLineElement = "file-indent-style"
	StatusLineFileType         StatusLineElement = "file-type"
	StatusLineDiagnostics      StatusLineElement = "diagnostics"
	StatusLineSelections       StatusLineElement = "selections"
	StatusLinePrimaryLen       StatusLineElement = "primary-selection-length"
	StatusLinePosition         StatusLineElement = "position"
	StatusLineSeparator        StatusLineElement = "separator"
	StatusLinePercent          StatusLineElement = "position-percentage"
	StatusLineTotalLines       StatusLineElement = "total-line-numbers"
	StatusLineSpacer           StatusLineElement = "spacer"
	StatusLineVersionControl   StatusLineElement = "version-control"
	StatusLineModified         StatusLineElement = "file-modified-indicator"
	StatusLineSpinner          StatusLineElement = "spinner"

	CursorKindBlock     CursorKind = "block"
	CursorKindBar       CursorKind = "bar"
	CursorKindUnderline CursorKind = "underline"
	CursorKindHidden    CursorKind = "hidden"

	LineNumberAbsolute LineNumber = "absolute"
	LineNumberRelative LineNumber = "relative"

	DefaultScrollOff     = 5
	DefaultScrollLines   = 3
	DefaultAutoSaveDelay = 3000
	DefaultInactiveDim   = 10

	WhitespaceRenderNone WhitespaceRenderValue = "none"
	WhitespaceRenderAll  WhitespaceRenderValue = "all"

	DefaultWSSpace        = '\u00b7' // '·' - middle dot (·)
	DefaultWSNbsp         = '\u237d' // '⍽' - shouldered open box (⍽)
	DefaultWSTab          = '\u2192' // '→' - rightwards arrow (→)
	DefaultWSNewline      = '\u23ce' // '⏎' - return symbol (⏎)
	DefaultWSTabpad  rune = ' '

	DefaultIndentGuideChar = '\u2502' // U+2502 box drawings light vertical

	DefaultStatusLineSeparator = "\u2502" // '│' box drawings light vertical

	GutterTypeDiagnostics GutterType = "diagnostics"
	GutterTypeLineNumbers GutterType = "line-numbers"
	GutterTypeSpacer      GutterType = "spacer"
	GutterTypeDiff        GutterType = "diff"

	DefaultGutterLineNumberMinWidth = 3
)
View Source
const (
	// InvalidDocumentId is the zero value, indicating no document
	InvalidDocumentId DocumentId = 0
	// ScratchBufferName is the display name used for unnamed scratch documents
	ScratchBufferName = "[scratch]"
	// MessagesBufferName is the display name of the message log document
	MessagesBufferName = "[messages]"
	// MessagesLanguage is the language identifier of the message log
	MessagesLanguage = "toe-log"

	// EncodingUTF8 and EncodingUTF8BOM are the text-encoding display names
	// used in config and status display
	EncodingUTF8    = "utf-8"
	EncodingUTF8BOM = "utf-8-bom"
)
View Source
const (
	RegisterSearch           = '/'
	RegisterDefaultYank      = '"'
	RegisterSelectionIndices = '#'
	RegisterSelectionText    = '.'
	RegisterDocumentPath     = '%'
	RegisterClipboard        = '+'
	RegisterPrimaryClipboard = '*'
	RegisterBlackHole        = '_'
)

Variables

View Source
var (
	ErrInvalidCursorKind       = errors.New("invalid cursor kind")
	ErrInvalidLineNumber       = errors.New("invalid line-number value")
	ErrInvalidStatusLine       = errors.New("invalid statusline element")
	ErrInvalidWhitespaceRender = errors.New("invalid whitespace render value")
	ErrInvalidGutterType       = errors.New("invalid gutter type")
	ErrInvalidBufferLine       = errors.New("invalid bufferline value")
)
View Source
var (
	ErrNoDocument        = errors.New("no document")
	ErrNoView            = errors.New("no view")
	ErrReadOnly          = errors.New("document is readonly")
	ErrDocumentNoPath    = errors.New("document has no path")
	ErrEmptyDirStack     = errors.New("directory stack is empty")
	ErrConfigUnavailable = errors.New("config path unavailable")
	ErrUnsavedChanges    = errors.New("unsaved changes")
	ErrFileChangedOnDisk = errors.New(
		"file modified by an external process, use :w! to overwrite",
	)
	ErrFileReadOnly = errors.New("path is read only")
	ErrCannotSplit  = errors.New("pane is too small to split")
)
View Source
var (
	// ErrNoLanguageServer reports that no language server is configured for a
	// document's language
	ErrNoLanguageServer = errors.New("LSP not defined for document")

	// ErrUnknownLanguageServer reports that a named language server was not
	// found among the document's configured servers
	ErrUnknownLanguageServer = errors.New("unknown language server")

	// ErrWorkspaceCommand reports that a requested workspace command is not
	// offered by any configured language server
	ErrWorkspaceCommand = errors.New("workspace command unavailable")

	// ErrFormatSelection reports that range formatting cannot be performed for
	// the current selection
	ErrFormatSelection = errors.New("format selection unsupported")
)
View Source
var (
	ErrSessionEmpty       = errors.New("session is empty")
	ErrSessionInvalid     = errors.New("session is invalid")
	ErrSessionUnsupported = errors.New("session version unsupported")
)

Functions

func CursorKindNames

func CursorKindNames() []string

CursorKindNames returns the recognized CursorKind values as strings

func DefaultShell

func DefaultShell() []string

DefaultShell returns the platform shell command prefix for shell actions

func DocumentRelativeName

func DocumentRelativeName(args DocumentRelativeNameArgs) string

DocumentRelativeName returns Path relative to BaseDir, falling back to the absolute path on error

func RuneWidth

func RuneWidth(ch rune, at core.TabStop) int

RuneWidth returns the display width of ch at the given tab stop, expanding tabs to the next boundary. The ASCII fast path avoids a per-rune string allocation in the render and cursor-positioning hot paths

func StatusLineElementNames added in v0.1.2

func StatusLineElementNames() []string

StatusLineElementNames returns the recognized statusline elements

func VisualColumn

func VisualColumn(doc core.Rope, s core.Span, tabW int) int

VisualColumn returns the display column of the span's end, measured from its start, expanding tabs to the next tabW boundary. It folds rune widths over the span directly, allocating no intermediate substring

func WorkspaceSessionFile

func WorkspaceSessionFile(dir string) string

WorkspaceSessionFile returns the session file path for dir's workspace

Types

type Align

type Align int

Align describes vertical scroll alignment

type AsyncRenderer added in v0.1.10

type AsyncRenderer interface {
	SetRedraw(func())
}

AsyncRenderer marks a pane that mutates outside the event loop; the tree hands it a redraw hook on insertion so it can wake the render loop

type BaseOptionsLoader added in v0.2.3

type BaseOptionsLoader func() map[string]string

BaseOptionsLoader resolves the option values in effect once config and init files have been applied

type BufferLine

type BufferLine string

func ParseBufferLine

func ParseBufferLine(value string) (BufferLine, error)

ParseBufferLine parses a buffer-line visibility name

func (*BufferLine) UnmarshalText

func (b *BufferLine) UnmarshalText(text []byte) error

UnmarshalText parses a buffer-line visibility name

type Clipboard

type Clipboard interface {
	Read() (string, error)
	ReadPrimary() (string, error)
	Write(text string) error
	WritePrimary(text string) error
	Available() bool
}

Clipboard is the system clipboard plus the X11 PRIMARY selection

type CodeAction

type CodeAction struct {
	ID        string
	Title     string
	Kind      string
	Server    string
	Preferred bool
}

CodeAction is a normalized language-server action or command

type CompletionItem

type CompletionItem struct {
	ID     string
	Server string
	Kind   string

	Label            string
	LabelDetail      string
	LabelDescription string
	Detail           string
	Docs             string

	Filter string
	Sort   string
	Insert string

	Preselect  bool
	Deprecated bool
}

CompletionItem is a normalized language-server completion candidate

type CompletionResult

type CompletionResult struct {
	Items      []*CompletionItem
	Incomplete bool
}

CompletionResult is a normalized language-server completion response

type CursorKind

type CursorKind string

func ParseCursorKind

func ParseCursorKind(value string) (CursorKind, error)

ParseCursorKind parses a cursor shape name

func (*CursorKind) UnmarshalText

func (c *CursorKind) UnmarshalText(text []byte) error

UnmarshalText parses a cursor shape name

type CursorScroll added in v0.2.0

type CursorScroll struct {
	Doc       core.Rope
	Selection core.Selection
	Height    int
	Width     int
	TabWidth  int
	ScrollOff int
	Visual    *core.VisualMoveFormat
}

CursorScroll carries the viewport inputs that keep the cursor visible. Height and Visual drive vertical scrolling, Width and TabWidth drive horizontal scrolling

type CursorShape

type CursorShape struct {
	Normal CursorKind `toml:"normal"`
	Select CursorKind `toml:"select"`
	Insert CursorKind `toml:"insert"`
}

type Diagnostic

type Diagnostic struct {
	Range    core.Span
	Severity DiagnosticSeverity
	Message  string
	Source   string
	Provider string
}

Diagnostic is a document diagnostic reported by an external provider

type DiagnosticCounts

type DiagnosticCounts struct {
	Errors   int
	Warnings int
	Info     int
	Hints    int
}

DiagnosticCounts groups diagnostics by severity

type DiagnosticSeverity

type DiagnosticSeverity int

DiagnosticSeverity orders diagnostics by user-facing severity

const (
	DiagnosticSeverityHint DiagnosticSeverity = iota + 1
	DiagnosticSeverityInfo
	DiagnosticSeverityWarning
	DiagnosticSeverityError
)

type DiffHunk

type DiffHunk struct {
	BaseFrom int
	BaseTo   int
	From     int
	To       int
}

DiffHunk is a change as half-open ranges [BaseFrom,BaseTo) and [From,To); an empty base range is a pure insertion, empty doc range a pure removal

func (DiffHunk) PureInsertion

func (h DiffHunk) PureInsertion() bool

PureInsertion reports whether the hunk only adds document lines

func (DiffHunk) PureRemoval

func (h DiffHunk) PureRemoval() bool

PureRemoval reports whether the hunk only removes base lines

type Direction

type Direction int

Direction is used to navigate between splits

const (
	DirectionUp Direction = iota
	DirectionDown
	DirectionLeft
	DirectionRight
)

type Displaceable added in v0.1.16

type Displaceable interface {
	OnDisplace()
	OnRevert()
}

Displaceable marks a pane that frees heavy resources while stashed behind another pane and reacquires them when reverted back into view

type DocType added in v0.3.0

type DocType uint8

DocType is what a document is for: text the user owns, or a log the editor writes and the user only reads

const (
	DocTypeFile DocType = iota // a file or scratch buffer, saved and renamed
	DocTypeLog                 // editor output: read-only, never saved
)

type Document

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

Document holds an open buffer and its editing, file, view, and render state

func (*Document) AccessedAt

func (d *Document) AccessedAt() int64

AccessedAt returns the monotonic focus/access sequence for MRU ordering

func (*Document) Apply

func (d *Document) Apply(tx core.Transaction, vid Id) error

Apply applies a transaction to the document, recording in history. While an insert group is active (BeginInsertGroup was called), changes are accumulated and a single revision is committed by CommitInsertHistory

func (*Document) BeginInsertGroup

func (d *Document) BeginInsertGroup(vid Id)

BeginInsertGroup starts insert-mode change accumulation for vid if not already active. Subsequent Apply calls accumulate into a single history revision until CommitInsertHistory is called

func (*Document) ClearAllDocumentHighlights

func (d *Document) ClearAllDocumentHighlights()

ClearAllDocumentHighlights removes highlight ranges for every view

func (*Document) ClearAllInlayHints

func (d *Document) ClearAllInlayHints()

ClearAllInlayHints removes language-server inlay hints for every view

func (*Document) ClearDiagnostics

func (d *Document) ClearDiagnostics()

ClearDiagnostics removes all diagnostics from the document

func (*Document) ClearDocumentColors

func (d *Document) ClearDocumentColors()

ClearDocumentColors removes document-wide LSP colors

func (*Document) ClearDocumentHighlights

func (d *Document) ClearDocumentHighlights(vid Id)

ClearDocumentHighlights removes highlight ranges for a view

func (d *Document) ClearDocumentLinks()

ClearDocumentLinks removes document-wide LSP links

func (*Document) ClearInlayHints

func (d *Document) ClearInlayHints(vid Id)

ClearInlayHints removes language-server inlay hints for a view

func (*Document) CommitInsertHistory

func (d *Document) CommitInsertHistory(vid Id)

CommitInsertHistory flushes any accumulated insert-mode changes as one history revision. It is a no-op when no accumulation is active

func (*Document) ConsumeDirty

func (d *Document) ConsumeDirty(vid Id) bool

ConsumeDirty reports whether vid's rendered state changed since the last call for vid, clearing the flag. A vid never seen before is dirty

func (*Document) DiagnosticCounts

func (d *Document) DiagnosticCounts() DiagnosticCounts

DiagnosticCounts returns severity counts for all current diagnostics

func (*Document) Diagnostics

func (d *Document) Diagnostics() []Diagnostic

Diagnostics returns a snapshot of all current diagnostics

func (*Document) DisplayName

func (d *Document) DisplayName() string

DisplayName returns the short display name for the document

func (*Document) DocumentColors

func (d *Document) DocumentColors() []DocumentColor

DocumentColors returns document-wide LSP colors

func (*Document) DocumentHighlights

func (d *Document) DocumentHighlights(vid Id) []DocumentHighlight

DocumentHighlights returns same-document highlight ranges for a view

func (d *Document) DocumentLinks() []DocumentLink

DocumentLinks returns document-wide LSP links

func (*Document) ExternalState

func (d *Document) ExternalState() ExternalState

ExternalState reports any unresolved change made to the backing file by another process

func (*Document) HasBOM

func (d *Document) HasBOM() bool

HasBOM reports whether the document was loaded with a UTF-8 BOM, which is preserved on save

func (*Document) ID

func (d *Document) ID() DocumentId

ID returns the unique document identifier

func (*Document) IndentStyle

func (d *Document) IndentStyle() core.IndentStyle

IndentStyle returns the active indentation style

func (*Document) InlayHints

func (d *Document) InlayHints(vid Id) []InlayHint

InlayHints returns language-server inlay hints for a view

func (*Document) Lang

func (d *Document) Lang() string

Lang returns the language identifier for syntax highlighting

func (*Document) LastEditPos

func (d *Document) LastEditPos() int

LastEditPos returns the char offset of the most recently committed change

func (*Document) LineEnding

func (d *Document) LineEnding() core.LineEnding

LineEnding returns the document's line-ending style

func (*Document) Loaded

func (d *Document) Loaded() bool

Loaded reports whether the backing file has been read; a restored session buffer stays unloaded until its content is first accessed

func (*Document) MarkDirty

func (d *Document) MarkDirty()

MarkDirty flags every view of this document for repaint

func (*Document) Modified

func (d *Document) Modified() bool

Modified reports whether the document has unsaved changes

func (*Document) Path

func (d *Document) Path() string

Path returns the file path, or empty string for scratch buffers

func (*Document) ReadOnly

func (d *Document) ReadOnly() bool

ReadOnly reports whether the document is read-only

func (*Document) Redo

func (d *Document) Redo(vid Id) bool

Redo reapplies one reverted step for the given view

func (*Document) RelativeName

func (d *Document) RelativeName(basedir string) string

RelativeName returns the path relative to basedir, or the display name when no file backs the document

func (*Document) Reload

func (d *Document) Reload() error

Reload replaces the document text with the current file contents on disk All per-view selections are reset to the start of the document

func (*Document) RemoveView

func (d *Document) RemoveView(vid Id)

RemoveView cleans up selection and LSP state for a closed view

func (*Document) ReplaceDiagnostics

func (d *Document) ReplaceDiagnostics(provider string, diags []Diagnostic)

ReplaceDiagnostics replaces all diagnostics from provider with diags

func (*Document) RestoreCursor

func (d *Document) RestoreCursor() bool

RestoreCursor reports whether the next exit from insert mode should move the cursor back by one grapheme

func (*Document) Revision

func (d *Document) Revision() int

Revision returns the document version used for render-cache invalidation

func (*Document) Save

func (d *Document) Save(opts *Options, force bool) error

Save writes the document to its current path. Unless force is set, it refuses an unsafe overwrite (changed on disk, or read-only). A log has no path of its own, so it can only be copied out with WriteCopy

func (*Document) SearchHighlightsActive

func (d *Document) SearchHighlightsActive(vid Id) bool

SearchHighlightsActive reports whether search matches should be highlighted for a view

func (*Document) Selection

func (d *Document) Selection() core.Selection

Selection returns the buffer's canonical cursor, independent of any view

func (*Document) SelectionFor

func (d *Document) SelectionFor(vid Id) core.Selection

SelectionFor returns the selection for a given view

func (*Document) SetDisplayName added in v0.3.0

func (d *Document) SetDisplayName(name string)

SetDisplayName renames a document that has no file backing it

func (*Document) SetDocumentColors

func (d *Document) SetDocumentColors(colors []DocumentColor)

SetDocumentColors stores document-wide LSP colors

func (*Document) SetDocumentHighlights

func (d *Document) SetDocumentHighlights(
	vid Id, highlights []DocumentHighlight,
)

SetDocumentHighlights stores the same-document highlight ranges for a view

func (d *Document) SetDocumentLinks(links []DocumentLink)

SetDocumentLinks stores document-wide LSP links

func (*Document) SetIndentStyle

func (d *Document) SetIndentStyle(s core.IndentStyle)

SetIndentStyle updates the indent style for this document

func (*Document) SetInlayHints

func (d *Document) SetInlayHints(vid Id, hints []InlayHint)

SetInlayHints stores language-server inlay hints for a view

func (*Document) SetLang

func (d *Document) SetLang(lang string)

SetLang sets the language identifier and resolves its definition once so the render path reads the cached *language.Language directly

func (*Document) SetLineEnding

func (d *Document) SetLineEnding(le core.LineEnding)

SetLineEnding updates the line ending for this document

func (*Document) SetPath

func (d *Document) SetPath(path string)

SetPath sets the file path for this document, renaming it to match. A log is the editor's own, so it keeps the name the editor gave it

func (*Document) SetReadOnly

func (d *Document) SetReadOnly(v bool)

SetReadOnly marks the document as read-only or writable

func (*Document) SetRestoreCursor

func (d *Document) SetRestoreCursor(v bool)

SetRestoreCursor marks whether the next insert-mode exit should restore the cursor one grapheme to the left

func (*Document) SetSelectionFor

func (d *Document) SetSelectionFor(vid Id, sel core.Selection)

SetSelectionFor sets the selection for a view. Changing the selection clears any search-match highlighting for that view

func (*Document) ShowSearchHighlights

func (d *Document) ShowSearchHighlights(vid Id)

ShowSearchHighlights marks a view's search matches as visible. Search actions call this after moving the selection to their match

func (*Document) TabWidth

func (d *Document) TabWidth() int

TabWidth returns the display tab width

func (*Document) Text

func (d *Document) Text() core.Rope

Text returns the current rope text

func (*Document) TextFormat

func (d *Document) TextFormat(w int) *language.TextFormat

TextFormat returns the display-time text layout options for this document

func (*Document) TextFormatForConfig

func (d *Document) TextFormatForConfig(
	w int, opts *Options,
) *language.TextFormat

TextFormatForConfig returns layout options using the supplied editor options

func (*Document) Type added in v0.3.0

func (d *Document) Type() DocType

Type returns what the document is for

func (*Document) Undo

func (d *Document) Undo(vid Id) bool

Undo reverts one history step for the given view

func (*Document) WriteCopy added in v0.3.0

func (d *Document) WriteCopy(path string, opts *Options) error

WriteCopy writes the document's text to path, leaving the document itself alone: it keeps its own path, name, and modification state

type DocumentChange

type DocumentChange struct {
	Before  core.Rope
	Changes core.ChangeSet
}

DocumentChange describes an editor text change for document observers

type DocumentColor

type DocumentColor struct {
	From  int
	To    int
	Red   uint8
	Green uint8
	Blue  uint8
}

DocumentColor is a normalized color range in a document

type DocumentHighlight

type DocumentHighlight struct {
	From int
	To   int
}

DocumentHighlight is a normalized same-document symbol highlight

type DocumentId

type DocumentId int

DocumentId is the unique identifier for an open document

type DocumentLink struct {
	ID     string
	From   int
	To     int
	Target string
	Server string
}

DocumentLink is a normalized link range in a document

type DocumentObserver

type DocumentObserver interface {
	DocumentOpened(*Document)
	DocumentChanged(*Document, DocumentChange)
	DocumentSaved(*Document)
	DocumentClosed(*Document)
}

DocumentObserver receives editor document lifecycle notifications

type DocumentOpenError

type DocumentOpenError struct {
	Path string
	Err  error
}

DocumentOpenError describes why a document could not be opened

func (*DocumentOpenError) Error

func (d *DocumentOpenError) Error() string

Error names the path that could not be opened

func (*DocumentOpenError) Unwrap

func (d *DocumentOpenError) Unwrap() error

Unwrap returns the underlying filesystem error

type DocumentRelativeNameArgs added in v0.2.0

type DocumentRelativeNameArgs struct {
	Path    string
	BaseDir string
}

DocumentRelativeNameArgs is a document path and the directory to make it relative to

type Editor

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

Editor holds the full state of the editor session: all open documents, the view layout tree, and shared editor state

func NewEditor

func NewEditor(cwd string) *Editor

NewEditor creates an empty editor with one scratch document and view

func (*Editor) ActiveRegister

func (e *Editor) ActiveRegister() rune

ActiveRegister returns the pending register rune (0 = default)

func (*Editor) AddDocumentObserver

func (e *Editor) AddDocumentObserver(o DocumentObserver)

AddDocumentObserver installs a document lifecycle observer. Observers are notified in registration order

func (*Editor) AllDocuments

func (e *Editor) AllDocuments() []*Document

AllDocuments returns all open documents

func (*Editor) AllViews

func (e *Editor) AllViews() []*View

AllViews returns all open views in DFS order

func (*Editor) AppendMessage added in v0.3.0

func (e *Editor) AppendMessage(msg string)

AppendMessage records a message in the log document. The append bypasses the read-only flag that keeps the user from editing the log

func (*Editor) Apply

func (e *Editor) Apply(tx core.Transaction) error

Apply applies a transaction to the focused document for the focused view

func (*Editor) ApplyToDocument

func (e *Editor) ApplyToDocument(doc *Document, tx core.Transaction) error

ApplyToDocument applies a transaction without changing the focused view

func (*Editor) BaseOptions added in v0.2.3

func (e *Editor) BaseOptions() map[string]string

BaseOptions resolves the base option values, returning nil when no loader is registered

func (*Editor) Chdir

func (e *Editor) Chdir(path string) error

Chdir changes the editor working directory

func (*Editor) Clipboard

func (e *Editor) Clipboard() Clipboard

Clipboard returns the clipboard provider in use

func (*Editor) CloseAllOtherViews

func (e *Editor) CloseAllOtherViews()

CloseAllOtherViews closes all views except the focused one

func (*Editor) CloseCurrentView

func (e *Editor) CloseCurrentView()

CloseCurrentView closes the focused pane

func (*Editor) ClosePane

func (e *Editor) ClosePane(id Id)

ClosePane closes the pane at id. If it is the tree's only pane, it is replaced with a fresh scratch document instead of leaving the tree empty

func (*Editor) CommitInsertHistory

func (e *Editor) CommitInsertHistory()

CommitInsertHistory flushes any pending insert-mode history accumulation on the focused document into a single history revision

func (*Editor) Count

func (e *Editor) Count() int

Count takes the pending numeric count argument, clearing it (0 = none)

func (*Editor) CountOr added in v0.3.0

func (e *Editor) CountOr(def int) int

CountOr takes the pending count, clearing it, answering def when unset

func (*Editor) Cwd

func (e *Editor) Cwd() string

Cwd returns the editor working directory

func (*Editor) DeleteDocument

func (e *Editor) DeleteDocument(did DocumentId)

DeleteDocument removes a document without closing its views; affected views will report no focused document

func (*Editor) DeleteRegister added in v0.3.0

func (e *Editor) DeleteRegister() rune

DeleteRegister returns the register a destructive edit yanks into

func (*Editor) DirStack

func (e *Editor) DirStack() []string

DirStack returns a copy of the directory stack (bottom to top)

func (*Editor) DiscardPane

func (e *Editor) DiscardPane(p Pane)

DiscardPane closes p's document, if p is a view and this was its last reference, for a displaced pane the caller has decided not to keep

func (*Editor) DisplacePane added in v0.1.16

func (e *Editor) DisplacePane(id Id, p Pane)

DisplacePane swaps the pane at id for p, stashing the displaced pane on the node so RevertPane can restore it when p closes

func (*Editor) Document

func (e *Editor) Document(did DocumentId) *Document

Document returns a document by id

func (*Editor) Earlier

func (e *Editor) Earlier(kind core.UndoKind) bool

Earlier navigates history backward by the given UndoKind

func (*Editor) FirstRegister

func (e *Editor) FirstRegister(name rune) (string, bool)

FirstRegister returns the first value from ReadRegister

func (*Editor) FocusDirection

func (e *Editor) FocusDirection(dir Direction)

FocusDirection moves focus to the nearest split in the given direction

func (*Editor) FocusNextView

func (e *Editor) FocusNextView()

FocusNextView moves focus to the next view in DFS order

func (*Editor) FocusPane

func (e *Editor) FocusPane(id Id)

FocusPane moves focus to the given pane

func (*Editor) FocusPrevView

func (e *Editor) FocusPrevView()

FocusPrevView moves focus to the previous view in DFS order

func (*Editor) FocusView

func (e *Editor) FocusView(vid Id)

FocusView moves focus to the given view

func (*Editor) FocusedDocument

func (e *Editor) FocusedDocument() *Document

FocusedDocument returns the document displayed by the focused view

func (*Editor) FocusedPane

func (e *Editor) FocusedPane() Pane

FocusedPane returns the currently focused pane

func (*Editor) FocusedView

func (e *Editor) FocusedView() *View

FocusedView returns the currently focused view

func (*Editor) HSplit

func (e *Editor) HSplit(docID DocumentId) *View

HSplit opens docID in a new horizontal split (stacked)

func (*Editor) HSplitNew

func (e *Editor) HSplitNew() *View

HSplitNew opens a new scratch document in a new horizontal split

func (*Editor) IndentForNewline

func (e *Editor) IndentForNewline(args IndentForNewlineArgs) (string, bool)

IndentForNewline returns syntax-aware indentation when a provider exists

func (*Editor) LanguageServerController

func (e *Editor) LanguageServerController() LanguageServerController

LanguageServerController returns the installed language-server controller

func (*Editor) LastModifiedDocIDs

func (e *Editor) LastModifiedDocIDs() [2]DocumentId

LastModifiedDocIDs returns the two most recently modified-and-left documents, with the most recent first. Invalid entries have value InvalidDocumentId

func (*Editor) LastMotion

func (e *Editor) LastMotion() func(*Editor)

LastMotion returns the most recently recorded repeatable motion

func (*Editor) Later

func (e *Editor) Later(kind core.UndoKind) bool

Later navigates history forward by the given UndoKind

func (*Editor) MessagesDocument added in v0.3.0

func (e *Editor) MessagesDocument() *Document

MessagesDocument returns the editor's message log, creating it on first use. It is the only way to reach the log: an editor has exactly one, and it is registered like any other buffer so the buffer picker lists it

func (*Editor) Mode

func (e *Editor) Mode() Mode

Mode returns the mode of the focused view

func (*Editor) MoveFocusedFile

func (e *Editor) MoveFocusedFile(path string, force bool) error

MoveFocusedFile renames the focused document's backing file and updates the document path

func (*Editor) NewDocument

func (e *Editor) NewDocument() *View

NewDocument creates a new empty scratch document and makes it the focused view

func (*Editor) OpenFile

func (e *Editor) OpenFile(path string) (*View, error)

OpenFile replaces the focused view's document with the given file, reusing an existing document if it is already open

func (*Editor) Options

func (e *Editor) Options() *Options

Options returns the typed runtime config values for the editor session

func (*Editor) PeekDoc

func (e *Editor) PeekDoc(path string) (*Document, error)

PeekDoc reads path without registering it as a buffer

func (*Editor) PopDirectory

func (e *Editor) PopDirectory() error

PopDirectory changes to the top of the directory stack, if any

func (*Editor) PopPrevDocID

func (e *Editor) PopPrevDocID() (DocumentId, bool)

PopPrevDocID returns and removes the most recently accessed document for the focused view

func (*Editor) ProcessExternalFileChange

func (e *Editor) ProcessExternalFileChange(path string) bool

ProcessExternalFileChange updates any open document whose backing file changed outside the editor

func (*Editor) PushDirectory

func (e *Editor) PushDirectory(path string) error

PushDirectory pushes the current directory onto the stack then chdirs

func (*Editor) ReadRegister

func (e *Editor) ReadRegister(name rune) []string

ReadRegister returns regular and computed register contents for the current editor state

func (*Editor) Redo

func (e *Editor) Redo() bool

Redo reapplies one reverted step in the focused document

func (*Editor) RegisterPaneRestorer

func (e *Editor) RegisterPaneRestorer(kind SessionKind, fn PaneRestorer)

RegisterPaneRestorer registers how to rebuild a leaf pane of the given session kind

func (*Editor) Registers

func (e *Editor) Registers() register.Registers

Registers returns the editor's register store

func (*Editor) Reload

func (e *Editor) Reload() error

Reload reloads the focused document from disk

func (*Editor) ReloadAll

func (e *Editor) ReloadAll() []error

ReloadAll reloads all documents that have a file path

func (*Editor) ReloadConfig

func (e *Editor) ReloadConfig() error

ReloadConfig reloads the live editor config and resets module section state. Falls back to loading user config only when no reload function is registered

func (*Editor) ReplacePane

func (e *Editor) ReplacePane(id Id, p Pane) Pane

ReplacePane swaps the pane at id for p in place, discarding any panes stashed behind id, and returns the evicted pane for the caller to dispose of

func (*Editor) ResetRegister

func (e *Editor) ResetRegister()

ResetRegister clears the pending register to the default

func (*Editor) ResizeFocusedSplit

func (e *Editor) ResizeFocusedSplit(dir Direction, delta int)

ResizeFocusedSplit pushes the border on the given side of the focused split by delta cells, screen-direction style (see Tree.ResizeFocused)

func (*Editor) ResizeTree

func (e *Editor) ResizeTree(size geom.Size)

ResizeTree resizes the layout tree to the given content area dimensions

func (*Editor) RestoreSession

func (e *Editor) RestoreSession(path string) (map[string]string, bool, error)

RestoreSession restores file-backed documents and view state from path. It returns any runtime option strings stored in the session for the caller to apply through the command registry

func (*Editor) RevertPane added in v0.1.16

func (e *Editor) RevertPane(id Id) bool

RevertPane restores the pane most recently displaced at id, reporting whether one was available

func (*Editor) Save

func (e *Editor) Save(force bool) error

Save saves the focused document to disk. Unless force is set, it refuses an unsafe overwrite (changed on disk, or read-only)

func (*Editor) SaveAll

func (e *Editor) SaveAll(force bool) []error

SaveAll saves all modified documents. Unless force is set, it refuses an unsafe overwrite (changed on disk, or read-only)

func (*Editor) SaveSession

func (e *Editor) SaveSession(path string, opts map[string]string) error

SaveSession stores restorable workspace state in path. Runtime option strings are supplied by the command registry that owns the option handlers

func (*Editor) SetBaseOptions added in v0.2.3

func (e *Editor) SetBaseOptions(fn BaseOptionsLoader)

SetBaseOptions registers the loader that resolves the option values a saved session is compared against, so a session carries only what changed since

func (*Editor) SetClipboard

func (e *Editor) SetClipboard(c Clipboard)

SetClipboard installs the clipboard provider

func (*Editor) SetConfigReload

func (e *Editor) SetConfigReload(fn func() error)

SetConfigReload registers the function called by ReloadConfig to reset module section state and re-apply the merged TOML config

func (*Editor) SetCount

func (e *Editor) SetCount(n int)

SetCount sets the pending numeric count

func (*Editor) SetIndenter

func (e *Editor) SetIndenter(p Indenter)

SetIndenter installs syntax-aware indentation support

func (*Editor) SetLanguageServerController

func (e *Editor) SetLanguageServerController(c LanguageServerController)

SetLanguageServerController installs the language-server request handler

func (*Editor) SetLastMotion

func (e *Editor) SetLastMotion(fn func(*Editor))

SetLastMotion records fn as the last repeatable motion

func (*Editor) SetMode

func (e *Editor) SetMode(m Mode)

SetMode sets the mode of the focused view

func (*Editor) SetRegister

func (e *Editor) SetRegister(r rune)

SetRegister sets the pending register selection

func (*Editor) SetStatusMsg

func (e *Editor) SetStatusMsg(msg string)

SetStatusMsg queues a status message for display. Producers may be off the UI goroutine, so the queue holds every message until the UI drains it

func (*Editor) SetVersionControl

func (e *Editor) SetVersionControl(vc VersionControl)

SetVersionControl installs the version-control state provider

func (*Editor) SetViewContentWidth

func (e *Editor) SetViewContentWidth(w int)

SetViewContentWidth stores the text content width (called by the renderer after computing the gutter width for the focused document)

func (*Editor) SetViewHeight

func (e *Editor) SetViewHeight(h int)

SetViewHeight sets the content area height (called by the UI on resize)

func (*Editor) ShowDocument

func (e *Editor) ShowDocument(did DocumentId) *View

ShowDocument displays an open document in the focused pane

func (*Editor) SplitFocused

func (e *Editor) SplitFocused(layout Layout) error

SplitFocused opens the focused pane in a new split

func (*Editor) SplitPane

func (e *Editor) SplitPane(p Pane, layout Layout) bool

SplitPane adds p in a new split

func (*Editor) SwapSplitInDirection

func (e *Editor) SwapSplitInDirection(dir Direction)

SwapSplitInDirection swaps focus with the nearest split in the direction

func (*Editor) SwitchBuffer

func (e *Editor) SwitchBuffer(did DocumentId) bool

SwitchBuffer replaces the focused view's document with an already-open document by ID. Returns false if the document does not exist or there is no focused view

func (*Editor) SwitchOrOpenDoc

func (e *Editor) SwitchOrOpenDoc(path string) (*Document, error)

SwitchOrOpenDoc returns an existing document for path, opening it if needed

func (*Editor) TakeStatusMsgs added in v0.3.0

func (e *Editor) TakeStatusMsgs() []string

TakeStatusMsgs returns the queued status messages and clears the queue

func (*Editor) TogglePaneMaximized added in v0.1.8

func (e *Editor) TogglePaneMaximized()

TogglePaneMaximized maximizes the focused pane or restores the split layout

func (*Editor) Transpose

func (e *Editor) Transpose()

Transpose flips the layout of the container holding the focused view

func (*Editor) Tree

func (e *Editor) Tree() *Tree

Tree returns the layout tree

func (*Editor) Undo

func (e *Editor) Undo() bool

Undo reverts one history step in the focused document

func (*Editor) VSplit

func (e *Editor) VSplit(docID DocumentId) *View

VSplit opens docID in a new vertical split (side by side)

func (*Editor) VSplitNew

func (e *Editor) VSplitNew() *View

VSplitNew opens a new scratch document in a new vertical split

func (*Editor) VersionControl

func (e *Editor) VersionControl() VersionControl

VersionControl returns the installed version-control state provider

func (*Editor) View

func (e *Editor) View(vid Id) *View

View returns a view by id

func (*Editor) ViewContentWidth

func (e *Editor) ViewContentWidth() int

ViewContentWidth returns the last-reported text content width (viewport minus gutter), used for visual-line movement when soft-wrap is active

func (*Editor) ViewHeight

func (e *Editor) ViewHeight() int

ViewHeight returns the last-reported content area height

func (*Editor) Views

func (e *Editor) Views() []struct {
	View    *View
	Focused bool
}

Views returns all open views in DFS order with a focused flag

func (*Editor) VisibleDocuments

func (e *Editor) VisibleDocuments() []*Document

VisibleDocuments returns the deduplicated documents currently shown in a pane

func (*Editor) WriteRegister

func (e *Editor) WriteRegister(name rune, values []string)

WriteRegister stores regular register contents, syncing special clipboard registers to the system clipboard provider

func (*Editor) YankRegister added in v0.3.0

func (e *Editor) YankRegister() rune

YankRegister returns the register a yank or paste uses

type ExternalState

type ExternalState int

ExternalState describes whether a file-backed document has diverged from the last disk snapshot toe loaded or wrote

const (
	ExternalStateClean   ExternalState = iota // no external disk change pending
	ExternalStateChanged                      // changed while buffer dirty
	ExternalStateDeleted                      // backing file removed while open
)

type FileChange

type FileChange struct {
	Kind     FileChangeKind
	Path     string
	FromPath string // original path, set only for FileChangeRenamed
	Staged   bool
}

FileChange describes one change to one file reported by version control. A file edited both in the index and the working tree yields two changes, one per stage

type FileChangeKind

type FileChangeKind int

FileChangeKind classifies a FileChange

const (
	FileChangeUntracked FileChangeKind = iota
	FileChangeAdded
	FileChangeModified
	FileChangeConflict
	FileChangeDeleted
	FileChangeRenamed
)

type FileOperationController

type FileOperationController interface {
	WillCreateFile(path string, dir bool) error
	DidCreateFile(path string, dir bool) error
	WillRenameFile(rename FileRename, dir bool) error
	DidRenameFile(rename FileRename, dir bool) error
	WillDeleteFile(path string, dir bool) error
	DidDeleteFile(path string, dir bool) error
}

FileOperationController handles user-initiated filesystem operations for language-server clients interested in workspace file operations

type FileRename added in v0.2.0

type FileRename struct {
	OldPath string
	NewPath string
}

FileRename is a path change, from OldPath to NewPath

type Gutter

type Gutter struct {
	Present     bool
	Layout      []GutterType      `toml:"layout"`
	LineNumbers GutterLineNumbers `toml:"line-numbers"`
}

Gutter controls which gutters are shown and in what order. In TOML it can be an array of type strings or a table with layout/line-numbers. Present tracks whether the config was explicitly set

func (*Gutter) GutterLayout

func (g *Gutter) GutterLayout() []GutterType

GutterLayout is the configured column order, or the default

func (*Gutter) HasGutterType

func (g *Gutter) HasGutterType(gt GutterType) bool

HasGutterType reports whether the layout includes a column

func (*Gutter) LineNumberMinWidth

func (g *Gutter) LineNumberMinWidth() int

LineNumberMinWidth is the narrowest the line-number column may draw

func (*Gutter) UnmarshalTOML

func (g *Gutter) UnmarshalTOML(value any) error

UnmarshalTOML accepts either a column list or a table of gutter settings

type GutterLineNumbers

type GutterLineNumbers struct {
	MinWidth *int `toml:"min-width"`
}

type GutterType

type GutterType string

func (*GutterType) UnmarshalText

func (g *GutterType) UnmarshalText(text []byte) error

UnmarshalText parses a gutter column name

type Id

type Id int

Id is the unique identifier for an open view

const (
	// InvalidViewId is the zero value, indicating no view
	InvalidViewId Id = 0
)

type IndentForNewlineArgs added in v0.2.0

type IndentForNewlineArgs struct {
	Doc  *Document
	Line int
	Pos  int
}

IndentForNewlineArgs is the document and the point a newline is inserted at

type IndentGuides

type IndentGuides struct {
	Render     bool   `toml:"render"`
	Character  string `toml:"character"`
	SkipLevels *int   `toml:"skip-levels"`
}

func (IndentGuides) CharRune

func (i IndentGuides) CharRune() rune

CharRune is the glyph drawn for an indent guide

func (IndentGuides) GetSkipLevels

func (i IndentGuides) GetSkipLevels() int

GetSkipLevels is the number of leading indent levels left undrawn

type Indenter

type Indenter func(doc *Document, line, pos int) (string, bool)

Indenter computes indentation for a new line at pos in doc

type InlayHint

type InlayHint struct {
	Pos          int
	Label        string
	Kind         string
	PaddingLeft  bool
	PaddingRight bool
}

InlayHint is a normalized language-server hint at a document position

type JumpEntry

type JumpEntry struct {
	DocID     DocumentId
	Anchor    int
	Selection core.Selection
}

JumpEntry is a single entry in the jump history

type JumpList

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

JumpList manages a bounded history of cursor positions

func (*JumpList) Backward

func (j *JumpList) Backward() (DocumentId, int, bool)

Backward moves to the previous jump and returns it

func (*JumpList) Clone

func (j *JumpList) Clone() JumpList

Clone returns an independent copy of the jump list

func (*JumpList) Entries

func (j *JumpList) Entries() []JumpEntry

Entries returns all jump history entries from oldest to newest

func (*JumpList) Forward

func (j *JumpList) Forward() (DocumentId, int, bool)

Forward moves to the next jump and returns it

func (*JumpList) GoTo added in v0.3.2

func (j *JumpList) GoTo(i int) (JumpEntry, bool)

GoTo moves the head to the entry at i and returns it, so navigating to a listed entry keeps the history either side of it

func (*JumpList) Head

func (j *JumpList) Head() int

Head returns the current head index in the jump list

func (*JumpList) Push

func (j *JumpList) Push(docID DocumentId, anchor int, sel core.Selection)

Push adds a new jump selection, discarding forward history

func (*JumpList) Restore

func (j *JumpList) Restore(items []JumpEntry, head int)

Restore replaces the jump list contents and head position

type LanguageServerController

type LanguageServerController interface {
	RestartLanguageServers(*Document, []string) ([]string, error)
	StopLanguageServers(*Document, []string) ([]string, error)
	ExecuteWorkspaceCommand(*Document, string, []string) error
	WorkspaceCommands(*Document) []string
	LanguageServerNames(*Document) []string
	Completions(*Document, Id) (CompletionResult, error)
	TriggerCompletions(*Document, Id) (CompletionResult, error)
	ResolveCompletion(
		*Document, Id, *CompletionItem,
	) (*CompletionItem, error)
	ApplyCompletion(*Document, Id, *CompletionItem) error
	Hover(*Document, Id) (string, error)
	SignatureHelp(*Document, Id) (SignatureHelp, error)
	TriggerSignatureHelp(*Document, Id) (SignatureHelp, error)
	GotoDeclaration(*Document, Id) ([]Location, error)
	GotoDefinition(*Document, Id) ([]Location, error)
	GotoTypeDefinition(*Document, Id) ([]Location, error)
	GotoImplementation(*Document, Id) ([]Location, error)
	GotoReference(*Document, Id) ([]Location, error)
	RenameSymbolPrefill(*Document, Id) (string, error)
	RenameSymbol(*Document, Id, string) error
	CodeActions(*Document, Id) ([]CodeAction, error)
	ApplyCodeAction(*Document, Id, CodeAction) error
	DocumentHighlights(*Document, Id) ([]DocumentHighlight, error)
	DocumentLinks(*Document) ([]DocumentLink, error)
	ResolveDocumentLink(*Document, DocumentLink) (DocumentLink, error)
	FormatDocument(*Document, Id) error
	FormatSelection(*Document, Id) error
	DocumentSymbols(*Document) ([]Symbol, error)
	WorkspaceSymbols(*Document, string) ([]Symbol, error)
	Busy() bool
}

LanguageServerController controls language-server sessions for commands

type Layout

type Layout bool

Layout describes how child panes are arranged within a split container

const (
	// LayoutVertical places splits side by side
	LayoutVertical Layout = false
	// LayoutHorizontal stacks splits one above the other
	LayoutHorizontal Layout = true
)

type LineNumber

type LineNumber string

func ParseLineNumber

func ParseLineNumber(value string) (LineNumber, error)

ParseLineNumber parses a line-number mode name

func (*LineNumber) UnmarshalText

func (l *LineNumber) UnmarshalText(text []byte) error

UnmarshalText parses a line-number mode name

type Location

type Location struct {
	Path     string
	From     ServerPosition
	To       ServerPosition
	Encoding PositionEncoding
}

Location is a normalized language-server target location, holding the server's own positions so listing never reads the files; ResolveRange converts them against a document at jump time

func (Location) ResolveRange added in v0.1.42

func (l Location) ResolveRange(text core.Rope) (core.Range, bool)

ResolveRange converts the location's server positions into a character range in text, reversed so the cursor lands on the start of the target

type Mode

type Mode int

Mode describes the current editing mode

const (
	ModeNormal   Mode = 1 << iota // NOR
	ModeInsert                    // INS
	ModeSelect                    // SEL
	ModeTerminal                  // TRM
	ModeImage                     // IMG
	ModeBinary                    // BIN

	// ModeCompletion is not a pane mode; it is the keymap dispatch bucket
	// used only while the completion popup owns key handling
	ModeCompletion // COM
)
const ModeAny Mode = 0

ModeAny is the zero value; it is not a pane mode. It is the wildcard key in a Command's per-mode Keys map, applying to every mode the command supports unless a specific mode overrides it

func ParseMode

func ParseMode(name string) Mode

ParseMode returns the Mode for a short name (NOR, INS, …), defaulting to ModeNormal for anything unrecognized

func (Mode) Scope

func (m Mode) Scope() string

Scope returns the theme scope suffix for the pane's status line and, for document panes, the cursor style: e.g. normal, insert, terminal, binary

func (Mode) Split added in v0.1.24

func (m Mode) Split() []Mode

Split decomposes an ORed set of modes into its constituent single-bit values, in declaration order

func (Mode) String

func (i Mode) String() string

type Options

type Options struct {
	Theme       string
	ScrollOff   int
	ScrollLines int
	InactiveDim int

	Mouse            bool
	MiddleClickPaste bool
	NerdFonts        bool
	Shell            []string

	AutoSaveFocusLost    bool
	AutoSaveAfterDelay   bool
	AutoSaveDelayTimeout int

	AtomicSave             bool
	InsertFinalNewline     bool
	TrimFinalNewlines      bool
	TrimTrailingWhitespace bool
	EditorConfig           bool

	AutoSession      bool
	FileWatch        bool
	Insecure         bool
	ContinueComments bool

	SearchSmartCase  bool
	SearchWrapAround bool

	TextWidth         *int
	SoftWrap          language.SoftWrap
	DefaultLineEnding core.LineEnding
	Rulers            []int

	LineNumber LineNumber
	Gutters    Gutter
	BufferLine BufferLine
	StatusLine StatusLine

	CursorLine   bool
	CursorColumn bool
	CursorShape  CursorShape

	Whitespace   Whitespace
	IndentGuides IndentGuides

	AutoPairMap  core.AutoPairs
	HasAutoPairs bool

	Gen int
}

Options holds the editor's typed runtime config values. Fields are exported so module Apply functions can write to them directly

func (*Options) AutoPairs

func (o *Options) AutoPairs() (core.AutoPairs, bool)

AutoPairs returns the auto-pair map and whether auto-pairs are enabled

func (*Options) CursorShapeForMode

func (o *Options) CursorShapeForMode(mode Mode) CursorKind

CursorShapeForMode returns the cursor shape for the given mode

func (*Options) SetRulers added in v0.1.29

func (o *Options) SetRulers(rulers []int)

SetRulers stores ruler columns as a sorted, deduplicated set

func (*Options) StatusLineLeft

func (o *Options) StatusLineLeft() []StatusLineItem

StatusLineLeft returns the left status line items with defaults

func (*Options) StatusLineRight

func (o *Options) StatusLineRight() []StatusLineItem

StatusLineRight returns the right status line items with defaults

func (*Options) StatusLineSeparator

func (o *Options) StatusLineSeparator() string

StatusLineSeparator returns the status line separator string with default

type Pane

type Pane interface {
	ID() Id
	Path() string
	SetID(Id)
	Area() geom.Area
	SetArea(geom.Area)
	MarkDirty()
	Mode() Mode
	SaveSession(*SessionWriter)
	Split() (Pane, error)
	Discard()
	Shutdown()
}

Pane is the interface implemented by every split tree leaf

type PaneRestorer

type PaneRestorer func(*Editor, *PaneSession) (Pane, error)

PaneRestorer rebuilds a leaf pane of a given session kind from its persisted state

type PaneSession

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

PaneSession exposes module-owned state for a restored pane

func (*PaneSession) Path

func (s *PaneSession) Path() string

Path returns the pane's persisted path

func (*PaneSession) Value

func (s *PaneSession) Value(key string) (json.RawMessage, bool)

Value returns module-owned pane state as raw JSON by key

type Position

type Position struct {
	Anchor           int
	HorizontalOffset int
	VerticalOffset   int
}

Position holds the scroll offset for a view

type PositionEncoding added in v0.1.42

type PositionEncoding int

PositionEncoding names the units a language server counts a line's characters in

const (
	PositionEncodingUTF16 PositionEncoding = iota
	PositionEncodingUTF8
	PositionEncodingUTF32
)

Position encodings a language server may count line characters in; UTF-16 is the protocol default

func (PositionEncoding) RuneLen added in v0.1.42

func (e PositionEncoding) RuneLen(ch rune) int

RuneLen reports how many encoding units ch occupies

type ResizeHolder added in v0.2.4

type ResizeHolder interface {
	HoldResize()
	ResumeResize()
}

ResizeHolder marks a pane that would rather not see every step of a resize, so a run of them is held until the layout settles

type Separator

type Separator struct {
	Layout Layout
	geom.Area
}

Separator describes the position and extent of the gap between two adjacent split panes in a container

type SeparatorAtRes

type SeparatorAtRes struct {
	ContainerID Id
	ChildIdx    int
	Layout      Layout
}

type ServerPosition added in v0.1.42

type ServerPosition struct {
	Line      int
	Character int
}

ServerPosition is a zero-based line and in-line character offset, the character counted in the server's PositionEncoding

func (ServerPosition) Resolve added in v0.1.42

func (p ServerPosition) Resolve(
	text core.Rope, encoding PositionEncoding,
) (int, bool)

Resolve converts a server position into a character offset in text

type SessionKind

type SessionKind string

SessionKind identifies a leaf pane's restorer in a saved session

const (
	SessionFile = "session.json"

	SessionKindSplit    SessionKind = "split"
	SessionKindView     SessionKind = "view"
	SessionKindImage    SessionKind = "image"
	SessionKindTerminal SessionKind = "terminal"
	SessionKindBinary   SessionKind = "binary"
	SessionKindMessages SessionKind = "messages"
)

type SessionWriter

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

SessionWriter is the opaque target a pane writes session state into

func (*SessionWriter) SaveSlot

func (w *SessionWriter) SaveSlot(kind SessionKind, path string)

SaveSlot stores a reopenable pane slot in the session

func (*SessionWriter) SaveValue

func (w *SessionWriter) SaveValue(key string, value any)

SaveValue stores module-owned pane state

type SignatureHelp

type SignatureHelp struct {
	Signatures []SignatureInformation
	Active     int
}

SignatureHelp is a normalized callable signature response

type SignatureInformation

type SignatureInformation struct {
	Label       string
	Docs        string
	ParamDocs   string
	ActiveStart int
	ActiveEnd   int
}

SignatureInformation describes one callable signature

type StatusLine

type StatusLine struct {
	Left      []StatusLineItem `toml:"left"`
	Right     []StatusLineItem `toml:"right"`
	Separator string           `toml:"separator"`
}

type StatusLineElement

type StatusLineElement string

type StatusLineItem

type StatusLineItem struct {
	Element StatusLineElement
	Pinned  bool
}

StatusLineItem is one configured status bar element. In TOML it is the element name, optionally suffixed with "!" to pin it so it is never dropped when the bar is too narrow to fit every element

func (*StatusLineItem) UnmarshalText

func (s *StatusLineItem) UnmarshalText(text []byte) error

UnmarshalText parses a status line item name

type Symbol

type Symbol struct {
	Name      string
	Kind      string
	Container string
	Location  Location
}

Symbol is a normalized language-server document or workspace symbol

type Tree

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

Tree manages the spatial layout of views as a split tree

func (*Tree) Any

func (t *Tree) Any(pred func(Pane) bool) bool

Any reports whether any leaf pane satisfies pred, without allocating

func (*Tree) CanSplit

func (t *Tree) CanSplit(layout Layout) bool

CanSplit reports whether there is enough room to split the focused pane in the given layout while keeping all resulting panes at or above the min size

func (*Tree) ContainerLayoutAt

func (t *Tree) ContainerLayoutAt(id Id) (Layout, bool)

ContainerLayoutAt returns the layout of the container that holds id

func (*Tree) Count

func (t *Tree) Count() int

Count returns the number of leaf panes, without allocating

func (*Tree) DiscardHistory added in v0.1.16

func (t *Tree) DiscardHistory(id Id)

DiscardHistory discards every pane stashed behind id, for when the slot is vacated without reverting

func (*Tree) DisplacePane added in v0.1.16

func (t *Tree) DisplacePane(id Id, p Pane)

DisplacePane swaps the pane at id for p, stashing the displaced pane on the node so RevertPane can bring it back when p closes. The oldest entry is discarded once the stack exceeds maxPaneHistory

func (*Tree) FindSplitInDirection

func (t *Tree) FindSplitInDirection(id Id, dir Direction) (Id, bool)

FindSplitInDirection finds the nearest split in the given direction from id,

func (*Tree) Focus

func (t *Tree) Focus() Id

Focus returns the currently focused view id

func (*Tree) Get

func (t *Tree) Get(id Id) Pane

Get returns the pane at id, or nil if id is not a leaf node

func (*Tree) GrowFocusedWidth added in v0.1.28

func (t *Tree) GrowFocusedWidth(delta int) bool

GrowFocusedWidth widens the focused pane by moving the nearest vertical split, constrained by the minimum width of its sibling

func (*Tree) Insert

func (t *Tree) Insert(p Pane) Id

Insert adds a pane as the next sibling after the currently focused pane

func (*Tree) IsEmpty

func (t *Tree) IsEmpty() bool

IsEmpty reports whether the tree has no views

func (*Tree) Maximized added in v0.1.8

func (t *Tree) Maximized() bool

Maximized reports whether one pane temporarily occupies the full tree area

func (*Tree) MoveSeparator

func (t *Tree) MoveSeparator(
	containerID Id, childIdx int, layout Layout, newPos int,
)

MoveSeparator adjusts the split between children[childIdx] and children[childIdx+1] in containerID, in tree coordinates

func (*Tree) Next

func (t *Tree) Next() Id

Next returns the id of the pane after the focused one in DFS order

func (*Tree) Prev

func (t *Tree) Prev() Id

Prev returns the id of the pane before the focused one in DFS order

func (*Tree) Range

func (t *Tree) Range(fn func(Pane) bool)

Range calls fn for each leaf pane in DFS order (left-to-right, top-to-bottom), stopping early if fn returns false. It does not allocate

func (*Tree) RangeVisible added in v0.1.8

func (t *Tree) RangeVisible(fn func(Pane) bool)

RangeVisible calls fn for each pane currently visible in the layout

func (*Tree) Redraw added in v0.1.11

func (t *Tree) Redraw()

Redraw wakes the renderer after asynchronous editor state changes

func (*Tree) Remove

func (t *Tree) Remove(id Id)

Remove removes a view from the tree. Focus is moved to the previous view before removal. Empty containers are collapsed

func (*Tree) ReplacePane

func (t *Tree) ReplacePane(id Id, p Pane)

ReplacePane swaps the pane at id for p, keeping its tree position and area

func (*Tree) Resize

func (t *Tree) Resize(size geom.Size) bool

Resize updates the total area and recalculates view areas. Returns true if the area changed

func (*Tree) ResizeFocused

func (t *Tree) ResizeFocused(dir Direction, delta int) bool

ResizeFocused pushes a border of the focused pane's split by delta cells in dir, falling back to its other border if it has none on that side. False if no ancestor splits along that axis

func (*Tree) RevertPane added in v0.1.16

func (t *Tree) RevertPane(id Id) bool

RevertPane restores the most recently displaced pane at id, reporting whether one was available

func (*Tree) SeparatorAt

func (t *Tree) SeparatorAt(at geom.Point) (SeparatorAtRes, bool)

SeparatorAt returns the container ID, left-child index, and layout of the separator hit by the click at tree column x, tree row y (bufferline excluded) SeparatorAtRes identifies a separator and its owning child

func (*Tree) SetFocus

func (t *Tree) SetFocus(id Id)

SetFocus moves focus to the given view id

func (*Tree) SetRedraw added in v0.1.10

func (t *Tree) SetRedraw(fn func())

SetRedraw installs the hook the tree hands to AsyncRenderer panes on insertion, wiring any that are already present

func (*Tree) Split

func (t *Tree) Split(p Pane, layout Layout) Id

Split creates a new pane alongside the focused pane using the given layout. If the focused pane's parent container already uses the same layout, the new pane is added as a sibling. Otherwise a new sub-container is created

func (*Tree) SwapSplitInDirection

func (t *Tree) SwapSplitInDirection(dir Direction) bool

SwapSplitInDirection swaps the focused pane with the nearest pane in the given direction

func (*Tree) ToggleMaximized added in v0.1.8

func (t *Tree) ToggleMaximized()

ToggleMaximized maximizes the focused pane or restores the split layout

func (*Tree) Transpose

func (t *Tree) Transpose()

Transpose flips the layout of the container holding the focused pane

func (*Tree) Traverse

func (t *Tree) Traverse() []Pane

Traverse returns all leaf panes in DFS order (left-to-right, top-to-bottom). Prefer Tree.Range when a slice isn't actually needed

func (*Tree) Unmaximize added in v0.1.9

func (t *Tree) Unmaximize()

Unmaximize restores the preserved split layout

func (*Tree) WalkSeparators

func (t *Tree) WalkSeparators(fn func(Separator))

WalkSeparators calls fn for each separator between adjacent panes. Vertical seps have W=1 and span the container height; horizontal seps have H=1 and span the container width

type VersionControl

type VersionControl interface {
	// DiffHunks returns the current hunks between the document and its
	// version-control base, sorted ascending and non-overlapping
	DiffHunks(*Document) []DiffHunk

	// DiffBase returns the version-control base text of the document
	DiffBase(*Document) (string, bool)

	// DiffHunksForPath computes hunks between the checked-in base and the
	// on-disk contents of an arbitrary workspace file
	DiffHunksForPath(path string) []DiffHunk

	// DiffBaseForPath returns the version-control base text of an arbitrary
	// workspace file, empty when it has none
	DiffBaseForPath(path string) string

	// HeadName returns a short display name for the current head of the
	// repository containing the document
	HeadName(*Document) (string, bool)

	// ChangedFiles lists workspace files that differ from the head
	ChangedFiles() ([]FileChange, error)

	// Refresh picks up external version-control state changes
	Refresh()

	// Updates delivers a token whenever diff state changes, so the UI can
	// schedule a redraw
	Updates() <-chan struct{}
}

VersionControl exposes version-control state to commands, pickers, and rendering. Implementations live outside the view package; the editor only holds the seam

type View

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

View is a viewport into a document

func (*View) Area

func (v *View) Area() geom.Area

Area returns the screen rectangle assigned by the layout engine

func (*View) BeginFreeScroll

func (v *View) BeginFreeScroll(rev int, sel core.Selection)

BeginFreeScroll decouples the viewport from the cursor. The revision and selection snapshot the document state at this moment; free scroll ends automatically when either changes

func (*View) ConsumeDirty

func (v *View) ConsumeDirty() bool

ConsumeDirty reports whether the view has changed since the last call, clearing the flag

func (*View) ContentHeight added in v0.3.0

func (v *View) ContentHeight() int

ContentHeight returns the view's rows for text, excluding its status line

func (*View) Discard

func (v *View) Discard()

Discard closes this displaced view if no other view uses its document

func (*View) DocID

func (v *View) DocID() DocumentId

DocID returns the document this view displays

func (*View) EndFreeScroll

func (v *View) EndFreeScroll()

EndFreeScroll re-couples the viewport to the cursor

func (*View) EnsureCursorVisible

func (v *View) EnsureCursorVisible(cs *CursorScroll)

EnsureCursorVisible scrolls so the cursor is visible within Height rows, respecting ScrollOff; measured in visual rows when Visual has active soft-wrap

func (*View) EnsureCursorVisibleHorizontal

func (v *View) EnsureCursorVisibleHorizontal(cs *CursorScroll)

EnsureCursorVisibleHorizontal scrolls so the cursor's visual column stays within Width content columns (gutter excluded). Width <= 0 disables horizontal scrolling and resets the offset to 0

func (*View) FreeScroll

func (v *View) FreeScroll() bool

FreeScroll reports whether the viewport is decoupled from the cursor

func (*View) ID

func (v *View) ID() Id

ID returns the view identifier

func (*View) JumpBackward

func (v *View) JumpBackward() (DocumentId, int, bool)

JumpBackward moves to the previous position in the jump list, recording the current position first when there is nothing ahead of it, so a following JumpForward returns to where the jump started

func (*View) JumpForward

func (v *View) JumpForward() (DocumentId, int, bool)

JumpForward moves to the next position in the jump list

func (*View) JumpTo added in v0.3.2

func (v *View) JumpTo(i int) (JumpEntry, bool)

JumpTo moves the jump list head to the entry at i and returns it

func (*View) Jumps

func (v *View) Jumps() []JumpEntry

Jumps returns all entries in the jump history, oldest first

func (*View) MarkDirty

func (v *View) MarkDirty()

MarkDirty flags the view as needing a repaint on the next frame

func (*View) Mode

func (v *View) Mode() Mode

Mode returns the current editing mode

func (*View) Offset

func (v *View) Offset() Position

Offset returns the current scroll position

func (*View) OnDisplace added in v0.1.16

func (v *View) OnDisplace()

OnDisplace marks this view as stashed behind another pane. A view holds no heavy resources of its own, so there is nothing to release

func (*View) OnRevert added in v0.1.16

func (v *View) OnRevert()

OnRevert marks this view as returned to the foreground. Nothing to reacquire

func (*View) Path

func (v *View) Path() string

Path returns the path of the document this view displays

func (*View) PushJump

func (v *View) PushJump(docID DocumentId, anchor int, sel core.Selection)

PushJump records a selection in the jump list

func (*View) SaveSession

func (v *View) SaveSession(w *SessionWriter)

SaveSession stores this view's document state in w. A view onto a buffer the editor generates records only that it was showing it

func (*View) SetArea

func (v *View) SetArea(a geom.Area)

SetArea sets the screen rectangle (called by the layout engine)

func (*View) SetID

func (v *View) SetID(id Id)

SetID sets the view identifier (called by the tree on insertion)

func (*View) SetMode

func (v *View) SetMode(m Mode)

SetMode sets the current editing mode

func (*View) SetOffset

func (v *View) SetOffset(p Position)

SetOffset updates the scroll position

func (*View) Shutdown

func (v *View) Shutdown()

Shutdown releases external resources owned by this view

func (*View) Split

func (v *View) Split() (Pane, error)

Split returns another view of the same document

func (*View) SyncFreeScroll

func (v *View) SyncFreeScroll(rev int, sel core.Selection) bool

SyncFreeScroll ends free scroll when the document revision or selection changed since BeginFreeScroll, and reports whether it remains active

type Whitespace

type Whitespace struct {
	Render     WhitespaceRender     `toml:"render"`
	Characters WhitespaceCharacters `toml:"characters"`
}

type WhitespaceCharacters

type WhitespaceCharacters struct {
	Space   string `toml:"space"`
	Nbsp    string `toml:"nbsp"`
	Tab     string `toml:"tab"`
	Tabpad  string `toml:"tabpad"`
	Newline string `toml:"newline"`
}

func (*WhitespaceCharacters) NbspRune

func (w *WhitespaceCharacters) NbspRune() rune

NbspRune is the glyph drawn for a non-breaking space

func (*WhitespaceCharacters) NewlineRune

func (w *WhitespaceCharacters) NewlineRune() rune

NewlineRune is the glyph drawn for a line ending

func (*WhitespaceCharacters) SpaceRune

func (w *WhitespaceCharacters) SpaceRune() rune

SpaceRune is the glyph drawn for a space

func (*WhitespaceCharacters) TabRune

func (w *WhitespaceCharacters) TabRune() rune

TabRune is the glyph drawn at the start of a tab

func (*WhitespaceCharacters) TabpadRune

func (w *WhitespaceCharacters) TabpadRune() rune

TabpadRune is the glyph filling the rest of a tab

type WhitespaceRender

type WhitespaceRender struct {
	Default *WhitespaceRenderValue
	Space   *WhitespaceRenderValue
	Nbsp    *WhitespaceRenderValue
	Tab     *WhitespaceRenderValue
	Newline *WhitespaceRenderValue
}

WhitespaceRender holds per-kind whitespace rendering settings. A plain-string TOML value sets Default only; a table sets fields independently, each falling back to Default then "none"

func (*WhitespaceRender) NbspRender

func (w *WhitespaceRender) NbspRender() WhitespaceRenderValue

NbspRender is the rendering mode for non-breaking spaces

func (*WhitespaceRender) NewlineRender

func (w *WhitespaceRender) NewlineRender() WhitespaceRenderValue

NewlineRender is the rendering mode for line endings

func (*WhitespaceRender) SpaceRender

func (w *WhitespaceRender) SpaceRender() WhitespaceRenderValue

SpaceRender is the rendering mode for spaces

func (*WhitespaceRender) TabRender

func (w *WhitespaceRender) TabRender() WhitespaceRenderValue

TabRender is the rendering mode for tabs

func (*WhitespaceRender) UnmarshalTOML

func (w *WhitespaceRender) UnmarshalTOML(value any) error

UnmarshalTOML accepts either one mode for everything or a table per kind

type WhitespaceRenderValue

type WhitespaceRenderValue string

func ParseWhitespaceRenderValue

func ParseWhitespaceRenderValue(s string) (WhitespaceRenderValue, error)

ParseWhitespaceRenderValue parses a whitespace rendering mode name

Directories

Path Synopsis
Package register implements the editor register store
Package register implements the editor register store

Jump to

Keyboard shortcuts

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