codeedit

package
v0.8.6 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 21 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package codeedit is a code editor for jamb: a multi-line text area for source code, with a line-indexed text buffer, undo and redo, several selections, find and replace, folding by indentation, and syntax highlighting.

A Document holds the text, the selections and the history. An editor shows one, and is placed in a tree as its element:

doc := codeedit.NewDocument(source)
ui.Div().Child(codeedit.Editor(doc).Label("main.go").Language("go"))

The keys are actions (see Bindings and the Cmd actions) with default bindings, so they work without setup, and an app can bind them to other keys. Several editors may show one Document: the selections and the folds belong to the Document, and the scrolling to each editor.

Highlighting uses @pierre/highlights, a highlighter with a lexer for each of 76 languages, built into the package (see codeedit/highlight). EditorElement.Language names the language, as a code fence does, such as "go" or "python", and starts a highlight session for the document; the editor sends it each change as it is made and paints with the spans it has. A document over the highlight limit is shown without colors. EditorElement.Highlighter takes a highlighter of the app's own instead, such as the tree-sitter one of github.com/tyler-builds/jamb-grammars.

Index

Constants

This section is empty.

Variables

View Source
var (
	CmdMoveLeft          = ui.NewAction("codeedit.move-left", "Move left").Hide()
	CmdMoveRight         = ui.NewAction("codeedit.move-right", "Move right").Hide()
	CmdMoveWordLeft      = ui.NewAction("codeedit.move-word-left", "Move word left").Hide()
	CmdMoveWordRight     = ui.NewAction("codeedit.move-word-right", "Move word right").Hide()
	CmdMoveUp            = ui.NewAction("codeedit.move-up", "Move up").Hide()
	CmdMoveDown          = ui.NewAction("codeedit.move-down", "Move down").Hide()
	CmdMoveLineStart     = ui.NewAction("codeedit.move-line-start", "Move to line start").Hide()
	CmdMoveLineEnd       = ui.NewAction("codeedit.move-line-end", "Move to line end").Hide()
	CmdMoveDocStart      = ui.NewAction("codeedit.move-doc-start", "Move to start").Hide()
	CmdMoveDocEnd        = ui.NewAction("codeedit.move-doc-end", "Move to end").Hide()
	CmdPageUp            = ui.NewAction("codeedit.page-up", "Page up").Hide()
	CmdPageDown          = ui.NewAction("codeedit.page-down", "Page down").Hide()
	CmdSelectLeft        = ui.NewAction("codeedit.select-left", "Select left").Hide()
	CmdSelectRight       = ui.NewAction("codeedit.select-right", "Select right").Hide()
	CmdSelectWordLeft    = ui.NewAction("codeedit.select-word-left", "Select word left").Hide()
	CmdSelectWordRight   = ui.NewAction("codeedit.select-word-right", "Select word right").Hide()
	CmdSelectUp          = ui.NewAction("codeedit.select-up", "Select up").Hide()
	CmdSelectDown        = ui.NewAction("codeedit.select-down", "Select down").Hide()
	CmdSelectLineStart   = ui.NewAction("codeedit.select-line-start", "Select to line start").Hide()
	CmdSelectLineEnd     = ui.NewAction("codeedit.select-line-end", "Select to line end").Hide()
	CmdSelectDocStart    = ui.NewAction("codeedit.select-doc-start", "Select to start").Hide()
	CmdSelectDocEnd      = ui.NewAction("codeedit.select-doc-end", "Select to end").Hide()
	CmdSelectPageUp      = ui.NewAction("codeedit.select-page-up", "Select page up").Hide()
	CmdSelectPageDown    = ui.NewAction("codeedit.select-page-down", "Select page down").Hide()
	CmdSelectAll         = ui.NewAction("codeedit.select-all", "Select all").Hide()
	CmdCollapse          = ui.NewAction("codeedit.collapse", "Single cursor").Hide()
	CmdDeleteBack        = ui.NewAction("codeedit.delete-back", "Delete back").Hide()
	CmdDeleteForward     = ui.NewAction("codeedit.delete-forward", "Delete forward").Hide()
	CmdDeleteWordBack    = ui.NewAction("codeedit.delete-word-back", "Delete word back").Hide()
	CmdDeleteWordForward = ui.NewAction("codeedit.delete-word-forward", "Delete word forward").Hide()
	CmdNewline           = ui.NewAction("codeedit.newline", "New line").Hide()
	CmdIndent            = ui.NewAction("codeedit.indent", "Indent").Hide()
	CmdOutdent           = ui.NewAction("codeedit.outdent", "Outdent").Hide()
	CmdUndo              = ui.NewAction("codeedit.undo", "Undo").Hide()
	CmdRedo              = ui.NewAction("codeedit.redo", "Redo").Hide()
	CmdCopy              = ui.NewAction("codeedit.copy", "Copy").Hide()
	CmdCut               = ui.NewAction("codeedit.cut", "Cut").Hide()
	CmdPaste             = ui.NewAction("codeedit.paste", "Paste")
	CmdComment           = ui.NewAction("codeedit.comment", "Toggle line comment")
	CmdAddNextOccurrence = ui.NewAction("codeedit.add-next-occurrence", "Add next occurrence")
	CmdAddCaretAbove     = ui.NewAction("codeedit.add-caret-above", "Add cursor above")
	CmdAddCaretBelow     = ui.NewAction("codeedit.add-caret-below", "Add cursor below")
	CmdFind              = ui.NewAction("codeedit.find", "Find")
	CmdReplace           = ui.NewAction("codeedit.replace", "Replace")
	CmdFindNext          = ui.NewAction("codeedit.find-next", "Find next")
	CmdFindPrevious      = ui.NewAction("codeedit.find-previous", "Find previous")
	CmdGoToLine          = ui.NewAction("codeedit.go-to-line", "Go to line")
	CmdFold              = ui.NewAction("codeedit.fold", "Fold")
	CmdUnfold            = ui.NewAction("codeedit.unfold", "Unfold")
	CmdNextDiagnostic    = ui.NewAction("codeedit.next-diagnostic", "Go to next problem")
	CmdPrevDiagnostic    = ui.NewAction("codeedit.prev-diagnostic", "Go to previous problem")
	CmdShowHover         = ui.NewAction("codeedit.show-hover", "Show hover")
	CmdCodeActions       = ui.NewAction("codeedit.code-actions", "Show code actions")
)

The commands of the editor are actions, so that key bindings and menus can run them, and an app can bind them to other keys or turn them off. Bindings maps the usual keys to them, in the "CodeEditor" key context that the editor sets, and the package registers them as default bindings (ui.RegisterDefaultBindings), so the keys work in every window without the app binding them. Movement and typing commands are hidden from a command palette, as the ui's text field actions are; the others are listed. An app binds other keys, or turns one off, with its own bindings, which win over the defaults:

rt.AddBindings(ui.BindIn("CodeEditor", "ctrl+k", codeedit.CmdFind))
rt.AddBindings(ui.BindIn("CodeEditor", "ctrl+z", ui.Unbind(codeedit.CmdUndo)))
View Source
var CmdGoToDefinition = ui.NewAction("codeedit.go-to-definition", "Go to definition")

CmdGoToDefinition goes to the definition of the symbol at the caret.

View Source
var CmdTriggerSuggest = ui.NewAction("codeedit.trigger-suggest", "Trigger suggestions")

CmdTriggerSuggest opens the completion list at the caret.

View Source
var ErrRange = errors.New("codeedit: change out of range")

ErrRange is returned by Edit and Replace for a change outside the text, or one that does not start and end on a character boundary, or that overlaps another.

Functions

func Bindings

func Bindings() []ui.Binding

Bindings returns the key bindings of the editor's commands, in the "CodeEditor" context that the editor's canvas sets. They are registered as default bindings, so an app need not add them; it can list them, as a keyboard help does. The punctuation keys name the key position as the US layout prints it (see ui.Bind), so ctrl+shift+[ is the key that is [ on the US layout.

Types

type Change

type Change struct {
	// From and To are the byte range that Text replaces.
	From, To int
	// Text is the new text that replaces the range.
	Text string
}

A Change replaces the bytes [From, To) of the text with Text. An insertion has From equal to To, and a deletion has an empty Text.

type CodeAction added in v0.4.0

type CodeAction struct {
	// Title is the text the menu shows and announces.
	Title string
	// Kind is the kind of the action, which groups it in the menu.
	Kind CodeActionKind
	// Diagnostics are the diagnostics the action fixes. They are informational.
	Diagnostics []Diagnostic
	// Preferred sorts the action first in its group, and highlights it when the menu opens.
	Preferred bool
	// Disabled, when not empty, shows the action dimmed with this reason. It is not applied.
	Disabled string
	// Edits are the changes to this document, in the byte offsets of the query's text. They are
	// made as one step of the undo history.
	Edits []Change
	// Run runs on the UI thread after Edits: a command, a change in another file, or a workspace
	// edit. It may capture state that has since changed, so it should check what it acts on.
	Run func()
}

A CodeAction is one action the provider offers for the query: a quick fix, a refactoring or a source action. The editor applies its Edits itself and then calls its Run.

type CodeActionFunc added in v0.4.0

type CodeActionFunc func(ctx context.Context, q CodeActionQuery) ([]CodeAction, error)

CodeActionFunc is a function that is a CodeActionProvider.

func (CodeActionFunc) CodeActions added in v0.4.0

func (f CodeActionFunc) CodeActions(ctx context.Context, q CodeActionQuery) ([]CodeAction, error)

CodeActions calls f.

type CodeActionKind added in v0.4.0

type CodeActionKind string

A CodeActionKind is the kind of a code action, in the hierarchy of the Language Server Protocol: "refactor.extract" is a kind of "refactor", and the menu groups the actions by their kind.

const (
	CodeActionQuickFix              CodeActionKind = "quickfix"
	CodeActionRefactor              CodeActionKind = "refactor"
	CodeActionRefactorExtract       CodeActionKind = "refactor.extract"
	CodeActionRefactorInline        CodeActionKind = "refactor.inline"
	CodeActionRefactorRewrite       CodeActionKind = "refactor.rewrite"
	CodeActionSource                CodeActionKind = "source"
	CodeActionSourceOrganizeImports CodeActionKind = "source.organizeImports"
	CodeActionSourceFixAll          CodeActionKind = "source.fixAll"
)

The kinds of code actions. A provider may use any kind; these are the ones the menu groups.

func (CodeActionKind) Within added in v0.4.0

func (k CodeActionKind) Within(parent CodeActionKind) bool

Within reports whether k is parent or a kind below it, so that "refactor.extract" is within "refactor", and "refactorExtra" is not.

type CodeActionProvider added in v0.4.0

type CodeActionProvider interface {
	CodeActions(ctx context.Context, q CodeActionQuery) ([]CodeAction, error)
}

A CodeActionProvider offers the code actions for a query, as a language server's code action request does. CodeActions runs on a goroutine of its own, with a context that is canceled when the answer is no longer wanted.

type CodeActionQuery added in v0.4.0

type CodeActionQuery struct {
	// Query is the text and the offset of the primary caret.
	Query
	// From and To are the primary selection's range. From equals To for a caret.
	From, To int
	// Diagnostics are the diagnostics that overlap the range, their ends included. With none, they
	// are the diagnostics on the caret's row.
	Diagnostics []Diagnostic
	// Trigger is why the editor asks.
	Trigger CodeActionTrigger
}

A CodeActionQuery is a Query about the primary selection, with the diagnostics the actions may fix and why the editor asks.

type CodeActionTrigger added in v0.4.0

type CodeActionTrigger uint8

A CodeActionTrigger says why the editor asks for code actions.

const (
	CodeActionInvoked   CodeActionTrigger = iota + 1 // Ctrl+., a click on the lightbulb, or the hover's quick fix
	CodeActionAutomatic                              // the probe that decides whether the lightbulb shows
)

type CompletionItem added in v0.4.0

type CompletionItem struct {
	// Label is the text the list shows. Detail is shown after it, such as a signature, and Doc
	// is the item's documentation, shown under the list while the item is highlighted.
	Label, Detail, Doc string
	// Insert is the text that replaces the word before the caret; it is Label when empty.
	// Filter is the text that the typed word is matched against; it is Label when empty.
	Insert, Filter string
	// Kind is what the item is.
	Kind CompletionKind
	// Edits are more changes made with the item, such as an import, in the byte offsets of the
	// query's text. They follow the text typed since, and an edit that overlaps the replaced
	// word is dropped.
	Edits []Change
}

A CompletionItem is one entry of a completion list.

type CompletionKind added in v0.4.0

type CompletionKind uint8

A CompletionKind is what a completion is, as the list shows it.

const (
	CompletionText     CompletionKind = iota // a word of the text
	CompletionKeyword                        // a keyword of the language
	CompletionFunction                       // a function
	CompletionMethod                         // a method
	CompletionVariable                       // a variable
	CompletionField                          // a field
	CompletionType                           // a type
	CompletionModule                         // a module or a package
	CompletionConstant                       // a constant
	CompletionSnippet                        // a snippet of code
)

type CompletionList added in v0.4.0

type CompletionList struct {
	// From is the byte offset of the query's text where the replaced text starts, which ends
	// at the caret. -1 is the start of the word before the caret.
	From int
	// Items are the completions, in the order the list shows them. The editor shows at most
	// maxCompletions of them.
	Items []CompletionItem
	// Incomplete says that the list is not all there is: the editor asks again as the word
	// grows, instead of only filtering the items it has.
	Incomplete bool
}

A CompletionList is a provider's answer: the items, and where the text they replace starts.

type CompletionProvider added in v0.4.0

type CompletionProvider interface {
	Triggers() string
	Complete(ctx context.Context, q CompletionQuery) (CompletionList, error)
}

A CompletionProvider gives the completions at the caret, as a language server's completion does. Triggers returns the characters that open the list when typed, such as ".". Complete runs on a goroutine of its own, with a context that is canceled when the answer is no longer wanted.

type CompletionQuery added in v0.4.0

type CompletionQuery struct {
	Query
	// Trigger is why the editor asks.
	Trigger CompletionTrigger
	// Char is the character typed, for TriggerCharacter.
	Char rune
}

A CompletionQuery is a Query about the caret, with why it is asked and, for TriggerCharacter, the character typed.

type CompletionTrigger added in v0.4.0

type CompletionTrigger uint8

A CompletionTrigger says why the editor asks for completions.

const (
	TriggerInvoked    CompletionTrigger = iota + 1 // Ctrl+Space, or CmdTriggerSuggest
	TriggerCharacter                               // one of the provider's Triggers was typed
	TriggerIncomplete                              // the text typed since an incomplete list changed
)

type DefinitionProvider added in v0.4.0

type DefinitionProvider interface {
	Definition(ctx context.Context, q Query) ([]Location, error)
}

A DefinitionProvider finds where the symbol at an offset is defined, as a language server's go-to-definition does. Its Definition runs on a goroutine of its own, with a context that is canceled when the answer is no longer wanted. The editor goes to the first location.

type Diagnostic added in v0.4.0

type Diagnostic struct {
	// From and To are the byte range the diagnostic is about.
	From, To int
	// Severity is how serious it is.
	Severity Severity
	// Message is the text shown and announced. Source names what reported it, such as "gopls",
	// and Code is its code there; the editor shows them in the hover.
	Message, Source, Code string
}

A Diagnostic is a message about the bytes [From, To) of the text. An empty range marks the character at From.

type Document

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

A Document is the text of a code editor: its lines, its selections, the folded lines and the undo history. Several editors can show one Document, and each shows its selections, so that a change made in one appears in the others.

Positions are byte offsets into the text, and rows are zero-based line numbers. A line ends at a line feed; a carriage return before it is kept as part of the line. The Document is not safe for concurrent use: it is changed on the UI thread, as the rest of the UI is.

func NewDocument

func NewDocument(text string) *Document

NewDocument returns a document with the text. Invalid UTF-8 is replaced with U+FFFD, and a CR LF pair is read as a line feed, so Text returns the text with line feeds only. The caret starts at the beginning of the text.

func (*Document) AddCaret

func (d *Document) AddCaret(p int)

AddCaret adds a caret at the byte offset p, which becomes the primary selection.

func (*Document) AddCaretVertical

func (d *Document) AddCaretVertical(dir int)

AddCaretVertical adds a caret one shown row above (dir < 0) or below (dir > 0) the topmost or bottommost caret, at the same screen cell, and makes it the primary selection. It does nothing when there is no such row.

func (*Document) AddNextOccurrence

func (d *Document) AddNextOccurrence() bool

AddNextOccurrence adds the next occurrence of the primary selection's text as a selection, after the last selection and wrapping around, and makes it the primary. With a caret, it selects the word there instead. It reports whether it selected anything new.

func (*Document) CanRedo

func (d *Document) CanRedo() bool

CanRedo reports whether there is a step to redo.

func (*Document) CanUndo

func (d *Document) CanUndo() bool

CanUndo reports whether there is a step to undo.

func (*Document) Caret

func (d *Document) Caret() int

Caret returns the byte offset of the caret of the primary selection.

func (*Document) Collapse

func (d *Document) Collapse()

Collapse makes the primary caret the only selection, as Escape does.

func (*Document) Copy

func (d *Document) Copy() string

Copy returns the selected text, one selection after another, each on a line of its own. It returns "" when every selection is a caret.

func (*Document) DeleteBackward

func (d *Document) DeleteBackward() error

DeleteBackward deletes the selected text, or the character before each caret. Between an empty pair of brackets or quotes it deletes both.

func (*Document) DeleteForward

func (d *Document) DeleteForward() error

DeleteForward deletes the selected text, or the character after each caret.

func (*Document) DeleteWordBackward

func (d *Document) DeleteWordBackward() error

DeleteWordBackward deletes the selected text, or the text back to the start of the word before each caret.

func (*Document) DeleteWordForward

func (d *Document) DeleteWordForward() error

DeleteWordForward deletes the selected text, or the text to the end of the word after each caret.

func (*Document) Diagnostics added in v0.4.0

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

Diagnostics returns the diagnostics, sorted by their start.

func (*Document) DiagnosticsAt added in v0.4.0

func (d *Document) DiagnosticsAt(off int) []Diagnostic

DiagnosticsAt returns the diagnostics whose range holds the byte offset off, its ends included, sorted by their start.

func (*Document) Edit

func (d *Document) Edit(changes ...Change) error

Edit applies the changes as one step of the undo history. The changes may be in any order, but they must not overlap, and each must lie in the text and start and end on character boundaries; otherwise Edit makes no change and returns ErrRange. The selections move with the text: a selection's end that is inside a replaced range goes to the start of the replacement. The caret stays where the text around it stays.

func (*Document) Fold

func (d *Document) Fold(row int) bool

Fold hides the lines indented under row, and reports whether it folded any. The row must be visible and must have lines under it that are indented past it. Folds that the new one covers are removed. The width of a tab stop is the document's (see SetTabSize), for the comparison of indentation.

func (*Document) FoldableRow

func (d *Document) FoldableRow(row int) bool

FoldableRow reports whether row has lines under it that are indented past it, and so can be folded. The width of a tab is the document's (see SetTabSize).

func (*Document) Folded

func (d *Document) Folded(row int) bool

Folded reports whether row is the header of a fold, which hides lines under it.

func (*Document) Indent

func (d *Document) Indent() error

Indent indents the rows of the selections by one tab stop, or, for a caret on one line, inserts spaces to the next tab stop. The width of a tab stop is the document's (see SetTabSize). It is a multi-line command: each row gets its indent, and the selections move with the text.

func (*Document) Len

func (d *Document) Len() int

Len returns the length of the text in bytes.

func (*Document) Line

func (d *Document) Line(row int) string

Line returns the text of row, without its line feed.

func (*Document) LineCount

func (d *Document) LineCount() int

LineCount returns the number of lines. A text with no line feed has one line, and a text that ends with a line feed has an empty last line.

func (*Document) LineEnd

func (d *Document) LineEnd(row int) int

LineEnd returns the byte offset of the line feed that ends row, or the length of the text for the last line.

func (*Document) LineStart

func (d *Document) LineStart(row int) int

LineStart returns the byte offset of the first byte of row. It panics if row is out of range.

func (*Document) MatchingBracket

func (d *Document) MatchingBracket(p int) (int, bool)

MatchingBracket returns the byte offset of the bracket that pairs with the one at the caret, or before it, and reports whether there is one. It looks at most 20,000 bytes away, so that a long text is not searched to its end.

func (*Document) Move

func (d *Document) Move(m Move, extend bool, page int)

Move moves every caret by m. With extend the selections grow from their anchors, and without it they collapse to the caret. page is how many shown rows a page holds, for MovePageUp and MovePageDown. The screen column of a vertical move, in cells, is kept from one move to the next, as far as the lines allow, when there is one selection.

func (*Document) Newline

func (d *Document) Newline() error

Newline replaces each selection with a line feed and the indentation of its line. After an opening bracket the new line is indented one more tab stop, and a closer typed next goes on a line of its own, below the caret, at the indentation of its line.

func (*Document) OffsetUTF16 added in v0.4.0

func (d *Document) OffsetUTF16(row, col int) int

OffsetUTF16 returns the byte offset of the row and the UTF-16 column, as UTF16Pos gives them. A row outside the text is clamped to it, a column past the end of the row is the end of the row, and a column between the two halves of a surrogate pair is the start of its character.

func (*Document) OnChange

func (d *Document) OnChange(fn func()) (cancel func())

OnChange calls fn after each change of the text, the selections or the folds, until the returned function is called. fn runs on the UI thread.

func (*Document) OnEdit

func (d *Document) OnEdit(fn func(Change)) (cancel func())

OnEdit calls fn for each change of the text, as the change is made, with the bytes it replaces in the text as it was just before it. A multi-part edit is reported one change at a time, last part first, so that each change's offsets hold for the text before it. Undo and SetText report one change for the whole difference. The highlighter follows the text through these changes. The returned function cancels fn.

func (*Document) Outdent

func (d *Document) Outdent() error

Outdent removes one tab stop of indentation from the rows of the selections: one tab, or up to a tab stop of spaces.

func (*Document) Paste

func (d *Document) Paste(text string) error

Paste replaces each selection with text. When there are as many selections as lines of text, and there is more than one of each, each selection gets one line, in order.

func (*Document) Primary

func (d *Document) Primary() Selection

Primary returns the primary selection.

func (*Document) PrimaryIndex

func (d *Document) PrimaryIndex() int

PrimaryIndex returns the index of the primary selection in Selections.

func (*Document) Redo

func (d *Document) Redo() bool

Redo redoes the latest undone step and reports whether there was one to redo.

func (*Document) Replace

func (d *Document) Replace(from, to int, s string) error

Replace replaces the bytes [from, to) of the text with s, as Edit does for one change.

func (*Document) ReplaceMatches

func (d *Document) ReplaceMatches(f *Finder, ms []Match, repl string) (int, error)

ReplaceMatches replaces the given matches with repl, as one step of the undo history. The matches must be in order and must not overlap, as Matches returns them. It returns the number of matches replaced.

func (*Document) RowAtVisible

func (d *Document) RowAtVisible(i int) (int, bool)

RowAtVisible returns the row of the i-th shown row, zero-based, and reports whether there is one.

func (*Document) RowOf

func (d *Document) RowOf(off int) int

RowOf returns the row that holds the byte offset off.

func (*Document) SelectAll

func (d *Document) SelectAll()

SelectAll selects the whole text, as one selection.

func (*Document) SelectRow

func (d *Document) SelectRow(row int)

SelectRow selects the whole of row, with its line feed, as a triple click does.

func (*Document) SelectWord

func (d *Document) SelectWord(p int)

SelectWord selects the word at byte offset p, or the white space or punctuation there.

func (*Document) Selections

func (d *Document) Selections() []Selection

Selections returns the selections in document order. The primary selection is the one the caret and the scrolling follow.

func (*Document) SetCaret

func (d *Document) SetCaret(p int)

SetCaret sets the selections to one caret at byte offset p.

func (*Document) SetDiagnostics added in v0.4.0

func (d *Document) SetDiagnostics(ds []Diagnostic)

SetDiagnostics replaces the diagnostics with ds. Each range is clamped to the text and to character boundaries, and a zero severity is SeverityError. The editors that show the document draw them at their next frame. The Document is not safe for concurrent use, so an app that receives diagnostics on another goroutine sets them on the UI thread, with ui.Context.Post.

func (*Document) SetDiagnosticsFor added in v0.4.0

func (d *Document) SetDiagnosticsFor(textVersion uint64, ds []Diagnostic) bool

SetDiagnosticsFor sets the diagnostics as SetDiagnostics does when the text is still the one of textVersion (see TextVersion), and reports whether it set them. A result computed for an older text is dropped: its offsets are of a text that has changed since.

func (*Document) SetSelections

func (d *Document) SetSelections(sels ...Selection)

SetSelections replaces the selections, with the last one as the primary. Each selection is clamped to the text and to a character boundary; overlapping selections are merged. It panics if no selection is given.

func (*Document) SetTabSize

func (d *Document) SetTabSize(n int)

SetTabSize sets the width of a tab stop, in cells, that the commands use. A vertical move keeps its column in cells, as the editor shows them, so the tab stops decide where the caret lands after a tab. The editor sets it from its TabSize. A width below 1 is 1. It is 4 by default.

func (*Document) SetText

func (d *Document) SetText(s string)

SetText replaces the text and the selections, and clears the undo history, as when a file is loaded. The caret goes to the beginning of the text, and the folds and the diagnostics are removed. It is not an undo step.

func (*Document) Text

func (d *Document) Text() string

Text returns the text, with line feeds only.

func (*Document) TextVersion added in v0.4.0

func (d *Document) TextVersion() uint64

TextVersion returns a number that changes on every change of the text, and only of the text: a move of the caret or a fold leaves it as it was, unlike Version. A request to a language server records it, so that a result for an older text can be told apart (see SetDiagnosticsFor).

func (*Document) ToggleComment

func (d *Document) ToggleComment(prefix string) error

ToggleComment comments or uncomments the rows of the selections with prefix, such as "// ". The rows are uncommented when every non-blank one starts with the prefix, after its indentation (the prefix's trailing space is optional when uncommenting). Otherwise the prefix goes in at the indentation of the least indented non-blank row.

func (*Document) TypeText

func (d *Document) TypeText(s string) error

TypeText types s over every selection: each selection is replaced by s. Typing a bracket or a quote closes it, and typing a closer that is already next steps over it. A bracket or quote typed over a selection wraps the selection in the pair, and keeps the selection. Typing white space ends an undo step.

func (*Document) UTF16Pos added in v0.4.0

func (d *Document) UTF16Pos(off int) (row, col int)

UTF16Pos returns the row and the column of the byte offset off, where the column counts UTF-16 code units from the start of the row, as the Language Server Protocol counts positions by default. An offset outside the text is clamped to it.

func (*Document) Undo

func (d *Document) Undo() bool

Undo undoes the latest step and reports whether there was one to undo.

func (*Document) Unfold

func (d *Document) Unfold(row int) bool

Unfold shows the lines hidden by the fold at row, or by the fold that hides row, and reports whether it unfolded any.

func (*Document) Version

func (d *Document) Version() uint64

Version returns a number that changes on every change of the text, the selections or the folds: edits, typing, undo and redo, SetText and selection and fold changes. Compare it with an earlier value to see whether the document changed since.

Read during a component's render, Version is a tracked read, like Signal.Get: the component renders again after the next change, so a component that shows whether the document is modified needs no OnChange of its own. Read anywhere else it is a plain read.

func (*Document) VisibleIndex

func (d *Document) VisibleIndex(row int) int

VisibleIndex returns the position of row among the shown rows. A hidden row has the position of the row above it.

func (*Document) VisibleRows

func (d *Document) VisibleRows() int

VisibleRows returns how many rows are shown: the lines, less the hidden ones.

type EditorElement

type EditorElement struct {
	ui.Composite
	// contains filtered or unexported fields
}

An EditorElement is a code editor under construction. It is made by Editor and configured with the methods below, each of which returns the editor so that they chain. An EditorElement is an element: place it in a tree as it is, and it renders itself. Its size is Full by 300 pixels unless the sizing methods (Size, Width, Height and the others) say otherwise.

func Editor

func Editor(doc *Document) *EditorElement

Editor returns an editor that shows doc. Line numbers are on, tabs are four columns wide, lines do not wrap, and the editor is writable with no comment prefix.

func (*EditorElement) CodeActions added in v0.4.0

func (e *EditorElement) CodeActions(p CodeActionProvider) *EditorElement

CodeActions sets the provider of the code actions. Ctrl+. and a click on the lightbulb that shows beside a line with a diagnostic open the menu of the actions at the caret; the editor asks the provider about each open, and the provider answers with the actions for the query.

func (*EditorElement) CommentPrefix

func (e *EditorElement) CommentPrefix(prefix string) *EditorElement

CommentPrefix sets the prefix that the comment command toggles at the start of each line, such as "// " for Go. With no prefix, the comment command does nothing.

func (*EditorElement) Completions added in v0.4.0

func (e *EditorElement) Completions(p CompletionProvider) *EditorElement

Completions sets the provider of the completion list. The list opens at the caret when one of the provider's trigger characters is typed, and on Ctrl+Space. Typing filters it, matching the typed word against each item's Filter or Label in order, ignoring case. Up, Down, PageUp and PageDown move the highlight, Enter and Tab accept it, and Escape, a click, the loss of focus and a move of the caret off the word close the list. The keyboard focus stays in the editor.

func (*EditorElement) Definitions added in v0.4.0

func (e *EditorElement) Definitions(p DefinitionProvider) *EditorElement

Definitions sets the provider of go-to-definition, which F12 and Ctrl+click run. A definition in this document is selected and scrolled into view, and one in another file is handed to the function set with OnOpenLocation. While Ctrl is held, the word under the pointer is underlined.

func (*EditorElement) Document

func (e *EditorElement) Document() *Document

Document returns the document the editor shows.

func (*EditorElement) GridSpan added in v0.2.0

func (e *EditorElement) GridSpan(cols, rows int) *EditorElement

GridSpan sets how many columns and rows the editor covers in its parent's grid.

func (*EditorElement) Grow added in v0.2.0

func (e *EditorElement) Grow(f float32) *EditorElement

Grow makes the editor take a share of the free space on its parent's main axis.

func (*EditorElement) Height

func (e *EditorElement) Height(h ui.Length) *EditorElement

Height sets the height of the editor, which is 300 pixels by default.

func (*EditorElement) Highlighter

func (e *EditorElement) Highlighter(h Highlighter) *EditorElement

Highlighter sets the syntax highlighter of the editor, when it is not a session the editor starts itself (see Language). The highlighter must have been made from the document's text, and the editor sends it each later change. A nil highlighter shows plain text.

func (*EditorElement) Hover added in v0.4.0

Hover sets the provider of the hover popup. When the pointer rests on the text, or on Ctrl+K Ctrl+I at the caret, the editor asks p about the offset and shows its answer under the range, with the messages of the diagnostics there. Without a provider the popup shows the diagnostics alone. Escape, an edit, the loss of focus and a move of the pointer off the range close it.

func (*EditorElement) HoverDelay added in v0.4.0

func (e *EditorElement) HoverDelay(d time.Duration) *EditorElement

HoverDelay sets how long the pointer rests on the text before the hover opens. It is 500 milliseconds by default.

func (*EditorElement) Key

func (e *EditorElement) Key(k string) *EditorElement

Key gives the editor a stable identity among its siblings, so its state (the scroll position, the find bar) survives reordering.

func (*EditorElement) Label

func (e *EditorElement) Label(s string) *EditorElement

Label sets the name that assistive technology reads for the editor.

func (*EditorElement) Language

func (e *EditorElement) Language(lang string) *EditorElement

Language highlights the document in the language named lang, as a code fence names it, such as "go", "python" or "ts" (see highlight.Languages). The editor starts a highlight session on the document's text, sends it each change, and paints the spans it has. It closes the session when the language or the document changes. A document over the highlight limit, or in a language the highlighter does not know, is shown without colors, and "" shows plain text.

func (*EditorElement) LineNumbers

func (e *EditorElement) LineNumbers(on bool) *EditorElement

LineNumbers shows or hides the column of line numbers. It is shown by default. The fold markers are always shown.

func (*EditorElement) MaxHeight added in v0.2.0

func (e *EditorElement) MaxHeight(l ui.Length) *EditorElement

MaxHeight sets the largest height of the editor.

func (*EditorElement) MaxWidth added in v0.2.0

func (e *EditorElement) MaxWidth(l ui.Length) *EditorElement

MaxWidth sets the largest width of the editor.

func (*EditorElement) MinHeight added in v0.2.0

func (e *EditorElement) MinHeight(l ui.Length) *EditorElement

MinHeight sets the smallest height of the editor.

func (*EditorElement) MinWidth added in v0.2.0

func (e *EditorElement) MinWidth(l ui.Length) *EditorElement

MinWidth sets the smallest width of the editor.

func (*EditorElement) OnOpenLocation added in v0.4.0

func (e *EditorElement) OnOpenLocation(fn func(Location)) *EditorElement

OnOpenLocation sets the function that opens a definition in another file, such as in a new tab of the app. Without one, such a definition is not opened.

func (*EditorElement) ReadOnly

func (e *EditorElement) ReadOnly(on bool) *EditorElement

ReadOnly shows the text and lets it be selected, moved through and copied, but not changed.

func (*EditorElement) Render

func (e *EditorElement) Render(ctx *ui.Context) ui.Element

Render builds the editor. It is called by the UI, and reads the signals of the editor's state, so the editor renders again when the text, the selections or the view change.

func (*EditorElement) Size

func (e *EditorElement) Size(w, h ui.Length) *EditorElement

Size sets the width and the height of the editor.

func (*EditorElement) SoftWrap added in v0.4.0

func (e *EditorElement) SoftWrap(m WrapMode) *EditorElement

SoftWrap sets where the editor wraps lines that are too long for it: not at all (WrapNone, the default), at the width of the editor (WrapViewport), at a column (WrapColumn), or at the narrower of the two (WrapBounded). A wrapped line is cut after the last space or punctuation that fits, or else between two characters, and each segment is drawn on a row of its own; the line numbers and the fold markers are on the first segment. Up, Down, PageUp and PageDown move by the rows shown, and Home and End go to the start and the end of the segment first, then of the line. The document's text and its line count do not change.

func (*EditorElement) Styles

func (e *EditorElement) Styles(st Style) *EditorElement

Styles sets the look of the parts of the editor, for this editor only. Set fields win over the theme's Style and the defaults. Calling Styles again merges with the earlier values.

func (*EditorElement) TabSize

func (e *EditorElement) TabSize(n int) *EditorElement

TabSize sets how many columns a tab stop is, for the display of tabs, for Tab and for the folding of indented lines. It is 4 by default.

func (*EditorElement) Width added in v0.2.0

func (e *EditorElement) Width(l ui.Length) *EditorElement

The sizing methods give the editor's box a size, as they do for the widgets of the ui package. The editor is Full wide by default. See Sizing in docs/styling.md.

func (*EditorElement) WrapColumn added in v0.4.0

func (e *EditorElement) WrapColumn(n int) *EditorElement

WrapColumn sets the column, in cells, where WrapColumn and WrapBounded wrap lines. It is 80 by default, and a column below 1 is 1.

func (*EditorElement) WrappingIndent added in v0.4.0

func (e *EditorElement) WrappingIndent(i WrappingIndent) *EditorElement

WrappingIndent sets where the continuation segments of a wrapped line start: at the left edge (IndentNone), under the line's first non-blank character (IndentSame, the default), or one tab stop further (IndentOneLevel). An indent that would leave fewer than 8 cells of text is dropped.

type FindOptions

type FindOptions struct {
	// MatchCase makes the search case-sensitive.
	MatchCase bool
	// WholeWord matches only whole words.
	WholeWord bool
	// Regex treats the query as a regular expression.
	Regex bool
}

FindOptions are the options of a search: whether it matches case, whole words only, and whether the query is a regular expression (in Go's syntax, RE2).

type Finder

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

A Finder searches a Document for a query. It keeps the matches of the last text it searched, and searches again only when the text changes. A Finder is made for one query and options; a new query makes a new Finder.

func NewFinder

func NewFinder(query string, opt FindOptions) (*Finder, error)

NewFinder returns a Finder for query. It returns an error if the query is an invalid regular expression. An empty query finds nothing.

func (*Finder) Index

func (f *Finder) Index(matches []Match, p int) (int, bool)

Index returns the index of the first match that starts at or after p, and reports whether there is one. The matches are those that Matches returns.

func (*Finder) Matches

func (f *Finder) Matches(d *Document) []Match

Matches returns the matches of the query in d, in order. A match that is empty is not a match. The result is kept until the text of d changes, and must not be changed.

func (*Finder) Replacement

func (f *Finder) Replacement(d *Document, m Match, repl string) string

Replacement returns the text that replaces match m when the replacement is repl. In a regular expression search, repl may refer to the groups as $1 or ${name}, as Go's regexp.Expand does; otherwise it is used as it is.

type Highlighter

type Highlighter interface {
	// Edit tells the highlighter about one change of the text, with the bytes it replaces.
	Edit(e highlight.EditRecord) error
	// SetViewport tells the highlighter which bytes are shown, so that it colors those first.
	SetViewport(lo, hi int) error
	// Spans returns the spans as they are now, and a version that changes when they do.
	Spans() ([]highlight.Span, uint64)
	// CaptureNames returns the names that highlight.Span.Capture indexes.
	CaptureNames() []string
	// Close stops the highlighter and releases what it holds.
	Close() error
}

A Highlighter gives an editor its syntax colors. It is satisfied by *highlight.Session. The editor sends it each change of the text as it is made, and paints with the spans it has.

The contract, which the session keeps:

  • Edit is called on the UI thread for each change, with the bytes it replaces, and returns at once. The spans shift with the text until the highlighter has new ones, so a keystroke never waits for the highlighter.
  • SetViewport tells the highlighter which bytes are shown, so that it colors those first.
  • Spans returns the spans as they are now, and a version that changes when they do. The editor draws whatever it has.
  • CaptureNames returns the names that highlight.Span.Capture indexes.

Methods may be added to Highlighter in later versions.

type Hover added in v0.4.0

type Hover struct {
	// From and To are the byte range the hover is about. The popup closes when the pointer
	// leaves it. An empty range is the word under the pointer.
	From, To int
	// Text is the text of the hover, which is also what is announced when the hover is opened
	// from the keyboard.
	Text string
	// Content, when set, builds the element shown in place of Text, such as rendered Markdown.
	Content func() ui.Element
}

A Hover is what a HoverProvider says about a range of the text: plain text, or an element of its own, which the editor shows in a popup under the range, after the diagnostics there.

type HoverFunc added in v0.4.0

type HoverFunc func(ctx context.Context, q Query) (Hover, error)

HoverFunc is a function that is a HoverProvider.

func (HoverFunc) Hover added in v0.4.0

func (f HoverFunc) Hover(ctx context.Context, q Query) (Hover, error)

Hover calls f.

type HoverProvider added in v0.4.0

type HoverProvider interface {
	Hover(ctx context.Context, q Query) (Hover, error)
}

A HoverProvider answers what the text at an offset is, as a language server's hover does. Its Hover runs on a goroutine of its own, with a context that is canceled when the answer is no longer wanted. An empty Hover, or an error, shows nothing but the diagnostics there.

type Location added in v0.4.0

type Location struct {
	// URI names the file, such as "file:///home/me/main.go", or is empty for this document.
	URI string
	// From and To are the byte range of the definition in this document.
	From, To int
	// Row and Col are the position of the definition in another file.
	Row, Col int
}

A Location is where a definition is: in this document, when URI is empty, at the bytes [From, To), or in another file, which the app opens (see OnOpenLocation). Row and Col are the position in that file, for the app, as its provider gives them; the editor reads them only for another file.

type Match

type Match struct {
	// From and To are the byte offsets of the match.
	From, To int
	// contains filtered or unexported fields
}

A Match is a range of the text that a Finder found, in bytes. For a regular expression it also keeps the submatches, which Replace expands with $1 or ${name}.

type Move

type Move uint8

A Move is a caret movement, given to Document.Move.

const (
	MoveLeft      Move = iota // one character left; a selection collapses to its start
	MoveRight                 // one character right; a selection collapses to its end
	MoveWordLeft              // to the start of the word before
	MoveWordRight             // to the end of the word after
	MoveUp                    // up one shown row, keeping the column
	MoveDown                  // down one shown row, keeping the column
	MoveLineStart             // to the first non-blank character, then to column 0
	MoveLineEnd               // to the end of the line
	MoveDocStart              // to the start of the text
	MoveDocEnd                // to the end of the text
	MovePageUp                // up a page of shown rows
	MovePageDown              // down a page of shown rows
)

type Query added in v0.4.0

type Query struct {
	// Text is the document's text when the request started.
	Text string
	// Version is the document's TextVersion for Text.
	Version uint64
	// Offset is the byte offset in Text that the request is about.
	Offset int
}

A Query is what a provider is asked about: the text as it was when the request started, its TextVersion, and a byte offset in it, such as the caret's or the pointer's. The text is a copy that does not change, so the provider can read it from its goroutine.

type Selection

type Selection struct {
	// Anchor and Head are the byte offsets of the two ends of the selection; Head is where the caret is.
	Anchor, Head int
}

A Selection is a range of the text with a caret. Anchor is where the selection was started and Head is the caret: the selection is the text between them, and an empty selection is a plain caret.

func (Selection) Empty

func (s Selection) Empty() bool

Empty reports whether the selection is a caret, with no text selected.

func (Selection) Range

func (s Selection) Range() (from, to int)

Range returns the start and the end of the selected text, in bytes.

type Severity added in v0.4.0

type Severity uint8

A Severity is how serious a diagnostic is.

const (
	SeverityError   Severity = iota + 1 // an error; the zero Severity is read as one
	SeverityWarning                     // a warning
	SeverityInfo                        // information
	SeverityHint                        // a hint, such as a suggestion to simplify
)

type Style

type Style struct {
	// Box is the frame of the editor and its background.
	Box ui.Style
	// BoxFocused is the frame while the editor has keyboard focus.
	BoxFocused ui.Style
	// Text is the look of the text itself.
	Text ui.Style
	// Gutter is the column of line numbers and fold markers.
	Gutter ui.Style
	// ActiveLine is the look of the line that holds the caret.
	ActiveLine ui.Style
	// Selection is the look of the selected text.
	Selection ui.Style
	// Match is the look of each find match.
	Match ui.Style
	// CurrentMatch is the look of the find match that is current.
	CurrentMatch ui.Style
	// Find is the look of the find bar.
	Find ui.Style
	// DiagnosticError is the look of the marks of an error: its TextColor.
	DiagnosticError ui.Style
	// DiagnosticWarning is the look of the marks of a warning: its TextColor.
	DiagnosticWarning ui.Style
	// DiagnosticInfo is the look of the marks of an information diagnostic: its TextColor.
	DiagnosticInfo ui.Style
	// DiagnosticHint is the look of the marks of a hint: its TextColor.
	DiagnosticHint ui.Style
	// Popup is the panel of the hover and of the list of completions.
	Popup ui.Style
	// PopupItem is one entry of a popup: a message of the hover, or a completion.
	PopupItem ui.Style
	// PopupItemSelected is the completion that Enter accepts.
	PopupItemSelected ui.Style
	// Lightbulb is the mark of a line that has a code action: its TextColor.
	Lightbulb ui.Style
	// PopupItemDisabled is the look of a code action that is disabled: its TextColor.
	PopupItemDisabled ui.Style
	// PopupGroup is the look of the header of a group in the menu of code actions: its TextColor.
	PopupGroup ui.Style
}

Style is the look of the parts of an Editor. A part's style merges over the built-in defaults, which come from the colors of the theme (Theme.CodeEditor and Theme.Syntax), then over the Style that the theme holds for every editor (set with ui.SetThemeStyle), and then over the Styles of the editor. Box is the frame of the editor: its Background, border, radius and padding. BoxFocused is the frame while the editor has focus. By default it is unset, as in code editors, where the caret shows focus: the frame does not change. Under high contrast it is a border of the Highlight color, so focus shows in the frame as well. Text is the text: its TextColor and FontSize. Gutter is the column of line numbers and fold markers: its TextColor, FontSize and Background. ActiveLine is the row of the caret, Selection the selected text, Match the other find matches and CurrentMatch the current one; their Background is the fill. Find is the box of the find and replace bar. DiagnosticError, DiagnosticWarning, DiagnosticInfo and DiagnosticHint are the marks of the diagnostics of each severity: their TextColor colors the wavy underline and the gutter marker, which the theme's Danger, Warning, Accent and TextMuted colors are by default. Popup is the panel of the hover and of the completions, PopupItem one entry of it, and PopupItemSelected the completion that Enter accepts. Lightbulb is the mark of a line that has a code action, its TextColor; PopupItemDisabled is a code action that is disabled, and PopupGroup the header of a group in the menu of code actions, each by its TextColor.

Under high contrast the colors of these parts are the system colors, whatever is set here or in the theme; their sizes and spacing still apply.

type WrapMode added in v0.4.0

type WrapMode uint8

A WrapMode says where an editor wraps long lines (see EditorElement.SoftWrap).

const (
	// WrapNone does not wrap: a long line scrolls horizontally. It is the default.
	WrapNone WrapMode = iota
	// WrapViewport wraps lines at the width of the editor's text.
	WrapViewport
	// WrapColumn wraps lines at the column set with WrapColumn, whatever the width of the
	// editor; a narrower editor scrolls horizontally to the column.
	WrapColumn
	// WrapBounded wraps lines at the column set with WrapColumn, or at the width of the editor's
	// text when that is narrower.
	WrapBounded
)

type WrappingIndent added in v0.4.0

type WrappingIndent uint8

A WrappingIndent says where the continuation segments of a wrapped line start (see EditorElement.WrappingIndent).

const (
	// IndentNone starts the continuation segments at the left edge of the text.
	IndentNone WrappingIndent = iota
	// IndentSame starts them under the first non-blank character of the line. It is the default.
	IndentSame
	// IndentOneLevel starts them one tab stop past the first non-blank character of the line.
	IndentOneLevel
)

Directories

Path Synopsis
Package highlight colors the text of a code editor with @pierre/highlights, a syntax highlighter of the Pierre Computer Company with a lexer for each of 76 languages, which runs in WebAssembly (see codeedit/internal/lexer).
Package highlight colors the text of a code editor with @pierre/highlights, a syntax highlighter of the Pierre Computer Company with a lexer for each of 76 languages, which runs in WebAssembly (see codeedit/internal/lexer).
internal
lexer
Package lexer runs @pierre/highlights, the syntax highlighter of the Pierre Computer Company (https://github.com/pierrecomputer/pierre, Apache-2.0).
Package lexer runs @pierre/highlights, the syntax highlighter of the Pierre Computer Company (https://github.com/pierrecomputer/pierre, Apache-2.0).
lexer/update command
Command update downloads a release of @pierre/highlights from the npm registry and writes its WebAssembly module, license and tables into the lexer package:
Command update downloads a release of @pierre/highlights from the npm registry and writes its WebAssembly module, license and tables into the lexer package:

Jump to

Keyboard shortcuts

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