editor

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 21 Imported by: 1 module, 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 editor is a code editor and a diff viewer for Golet's native UI, on package ui.

View shows a code editor of a Buffer, as Zed's: syntax highlighting, several carets and selections, soft wraps, folding, finding and replacing, completions, hovers, diagnostics and inlay hints from the app or a language server, and the commands and key bindings of code editors:

st := &editor.State{Buffer: editor.NewBuffer(src)}
st.Buffer.SetLanguage(editor.LanguageFor("main.go"))
// In the view:
editor.View(c, st).Fill()

DiffView shows the changes between two buffers, as Pierre's diffs: side by side or unified, with the words changed highlighted, unchanged lines collapsed, annotations under lines, and the new side editable.

A Language highlights its text with a Tokenizer, a line at a time, or with a Highlighter of its own, as a parser's: the editor gives it the edits of the text and asks it for the tokens of the lines it shows, and uses what it knows of the text's structure (SyntaxSelector, Folder, BracketMatcher, Indenter) for selections, folds, brackets and indentation.

Editors lay out and paint only the lines in view: a buffer of a million lines scrolls and edits as one of ten.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultCompletions

func DefaultCompletions(c *ui.Context, panel ui.Element, m *CompletionMenu)

DefaultCompletions builds the editor's own list of completions into panel, as Zed's: each with its kind, label and detail, nine rows high, and the documentation of the one chosen below them.

func DefaultFindBar

func DefaultFindBar(c *ui.Context, bar ui.Element, f *FindBar)

DefaultFindBar builds the editor's own find bar into bar, as Zed's: the query with its options, the count of matches and the buttons going through them, and the replacement below it while replacing.

func DefaultGoToLine

func DefaultGoToLine(c *ui.Context, bar ui.Element, g *GoToLineBar)

DefaultGoToLine builds the editor's own go to line bar into bar: the field, and where the caret is.

func DefaultGutterButton

func DefaultGutterButton(c *ui.Context, btn ui.Element, r DiffLineRange)

DefaultGutterButton builds the viewer's own gutter button into btn: a + on the accent color.

func DefaultHover

func DefaultHover(c *ui.Context, panel ui.Element, h *HoverCard)

DefaultHover builds the editor's own hover into panel, as Zed's: the diagnostics with bars of their severity's color, then the text in the editor's font and what the app builds, all of it selectable.

func DefaultHunkActions

func DefaultHunkActions(c *ui.Context, bar ui.Element, a *DiffHunkActions)

DefaultHunkActions builds the viewer's own actions into bar: Revert and Keep buttons.

func DefaultSeparator

func DefaultSeparator(c *ui.Context, sep ui.Element, s *DiffSeparator)

DefaultSeparator builds the viewer's own separator into sep, as Pierre's: a bar with chevrons expanding the lines up and down, or all of them when they are few, and "N unmodified lines", which expands them all; or a hunk's header. Shift expands all the lines from any button.

func DiffView

func DiffView(c *ui.Context, d *DiffState) ui.Element

DiffView builds the diff viewer.

func View

func View(c *ui.Context, st *State) ui.Element

View creates a code editor of st's buffer, as Zed's: syntax highlighting, several carets and selections, soft wraps, folding, finding and replacing, completions, diagnostics, and the commands and key bindings of code editors (Command, DefaultBindings). Give it a size, as Fill or Grow; with FitContent it is as high as its lines.

It lays out and draws only the lines in view, shaping each row once and keeping it while frames draw it, whatever the size of the text: a buffer of a million lines scrolls as one of ten.

Types

type Binding

type Binding struct {
	Mods     ui.Modifiers
	Key      ui.Key
	ThenMods ui.Modifiers
	ThenKey  ui.Key
	Command  Command
}

Binding runs Command for a key: Mods+Key, followed by ThenMods+ThenKey when ThenKey is set, as the chords Cmd+K Cmd+0. A binding to NoCommand takes a key away from the editor.

func DefaultBindings

func DefaultBindings() []Binding

DefaultBindings returns the key bindings of code editors on this platform: Zed's on macOS, and the same with Control, as Visual Studio Code's, elsewhere.

type BracketMatcher

type BracketMatcher interface {
	EnclosingBrackets(start, end int) (open, close Range, ok bool)
}

BracketMatcher is a Highlighter matching brackets, as do and end: EnclosingBrackets returns the innermost pair around bytes start to end, which editors highlight around the caret and move between. As in Zed, a pair is around them when its brackets are, or touch them: the opening bracket starts at or before start, and the closing one ends at or after end, so that a caret just after a closing bracket is in its pair.

type BracketPair

type BracketPair struct {
	Open, Close string
	// NotIn lists kinds of tokens in which typing Open does not close it,
	// as a quote typed in a string.
	NotIn []TokenKind
}

BracketPair is an opening and a closing text, as ( and ), that the editor matches, closes as the opening is typed, and wraps a selection in.

type Buffer

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

Buffer is the text an editor edits, with its undo history and its language. Several editors, and both sides of a DiffView, can show one buffer: an edit in one shows in the others, their carets and selections moving with the text around them, and undo takes back the buffer's last edit, whichever editor made it, as in Zed.

The text is a persistent tree of chunks: an edit copies a few kilobytes and a path of the tree, whatever the size of the document, and each version shares the rest with the one before, so undo history keeps versions rather than copies, and frames and other goroutines read a version (Snapshot) without locks. Offsets count bytes of UTF-8, and a Pos a line and the bytes into it.

Lines end in \n, as in Zed: a text set with \r\n line endings keeps \n ones, and LineEnding says which it had, which WriteTo writes.

Methods are safe from any goroutine; schedule changes with Window.Update so the window shows them.

func NewBuffer

func NewBuffer(text string) *Buffer

NewBuffer returns a buffer holding text, which is its saved text.

func (*Buffer) CanRedo

func (b *Buffer) CanRedo() bool

func (*Buffer) CanUndo

func (b *Buffer) CanUndo() bool

CanUndo and CanRedo report whether Undo and Redo have a step to take.

func (*Buffer) Edit

func (b *Buffer) Edit(edits ...Edit)

Edit applies edits to the text as one step of undo. Their offsets are in the text before any of them; overlapping edits are cut to follow the one before.

func (*Buffer) Language

func (b *Buffer) Language() *Language

Language returns the buffer's language, nil for plain text.

func (*Buffer) Len

func (b *Buffer) Len() int

Len returns the length of the text in bytes.

func (*Buffer) Line

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

Line returns line i, without its newline.

func (*Buffer) LineCount

func (b *Buffer) LineCount() int

LineCount returns how many lines the text has: one more than its newlines.

func (*Buffer) LineEnding

func (b *Buffer) LineEnding() string

LineEnding returns the line ending the text had as it was set, \r\n or \n, which WriteTo writes; SetLineEnding changes it.

func (*Buffer) MarkSaved

func (b *Buffer) MarkSaved()

MarkSaved makes the current text the saved one.

func (*Buffer) Modified

func (b *Buffer) Modified() bool

Modified reports whether the text differs from the saved one: the text the buffer was made or Reset with, or had when MarkSaved was called. Undoing back to it makes the buffer unmodified again.

func (*Buffer) Offset

func (b *Buffer) Offset(p Pos) int

Offset returns the byte offset of p, its column clamped to its line.

func (*Buffer) Pos

func (b *Buffer) Pos(offset int) Pos

Pos returns the line and column of byte offset.

func (*Buffer) Redo

func (b *Buffer) Redo() bool

Redo makes the step Undo took back again, and reports whether there was one.

func (*Buffer) Reset

func (b *Buffer) Reset(text string)

Reset replaces the text and forgets the undo history, as for a file loaded anew, and makes it the saved text.

func (*Buffer) Set

func (b *Buffer) Set(text string)

Set replaces the whole text as one edit, which Undo takes back.

func (*Buffer) SetLanguage

func (b *Buffer) SetLanguage(l *Language)

SetLanguage sets the language that highlights the text, and that comments, brackets and indentation follow; nil is plain text.

func (*Buffer) SetLineEnding

func (b *Buffer) SetLineEnding(ending string)

func (*Buffer) Slice

func (b *Buffer) Slice(start, end int) string

Slice returns the bytes start to end of the text.

func (*Buffer) Snapshot

func (b *Buffer) Snapshot() Snapshot

Snapshot returns the text as it is now, which stays as it is while the buffer changes: read it from any goroutine, as to save the text or to send it to a language server.

func (*Buffer) String

func (b *Buffer) String() string

String returns the text.

func (*Buffer) Transact

func (b *Buffer) Transact(fn func())

Transact groups the edits fn makes, through Edit and the editors showing the buffer, into one step of undo.

func (*Buffer) Undo

func (b *Buffer) Undo() bool

Undo takes back the last step of edits, and reports whether there was one.

func (*Buffer) Version

func (b *Buffer) Version() uint64

Version returns a number that changes with every change of the text.

func (*Buffer) WriteTo

func (b *Buffer) WriteTo(w io.Writer) (int64, error)

WriteTo writes the text to w, a chunk at a time, as for saving it, with its LineEnding.

type Change

type Change struct {
	OldStart, OldEnd, NewStart, NewEnd int
}

Change is a range of a text an edit replaced: bytes OldStart to OldEnd of the text before the edit, which are bytes NewStart to NewEnd of the text after it. An edit's changes are in order and do not overlap, so NewStart is OldStart moved by what the changes before it added and removed. An incremental parser, as tree-sitter's, takes them from the last: each starts at OldStart, and ends at OldEnd before and at OldStart+NewEnd-NewStart after, as the changes before it have not moved it yet.

type Command

type Command uint16

Command is something a code editor does, which a key binding runs: st.Run(ui.ToggleComment).

const (
	NoCommand Command = iota
	// Moving the carets, and with Select, extending the selections.
	MoveLeft
	MoveRight
	MoveUp
	MoveDown
	MoveWordLeft
	MoveWordRight
	MoveSubwordLeft
	MoveSubwordRight
	MoveLineStart
	MoveLineEnd
	MoveDocStart
	MoveDocEnd
	MoveParagraphUp
	MoveParagraphDown
	MovePageUp
	MovePageDown
	MoveToBracket
	SelectLeft
	SelectRight
	SelectUp
	SelectDown
	SelectWordLeft
	SelectWordRight
	SelectSubwordLeft
	SelectSubwordRight
	SelectLineStart
	SelectLineEnd
	SelectDocStart
	SelectDocEnd
	SelectParagraphUp
	SelectParagraphDown
	SelectPageUp
	SelectPageDown
	SelectToBracket
	// Selections.
	SelectAll
	SelectLine
	SelectNext
	SelectPrevious
	SelectAllMatches
	AddCursorAbove
	AddCursorBelow
	SelectLarger
	SelectSmaller
	UndoSelection
	RedoSelection
	SplitSelectionIntoLines
	Cancel
	// Editing.
	Undo
	Redo
	Cut
	Copy
	Paste
	Backspace
	Delete
	DeleteWordLeft
	DeleteWordRight
	DeleteSubwordLeft
	DeleteSubwordRight
	DeleteToLineStart
	DeleteToLineEnd
	CutToLineEnd
	DeleteLine
	Newline
	NewlineAbove
	NewlineBelow
	MoveLinesUp
	MoveLinesDown
	DuplicateLinesUp
	DuplicateLinesDown
	DuplicateSelection
	JoinLines
	Transpose
	Indent
	Outdent
	Tab
	Backtab
	ToggleComment
	ToggleBlockComment
	SortLines
	SortLinesCaseInsensitive
	ReverseLines
	UniqueLines
	Uppercase
	Lowercase
	TitleCase
	SnakeCase
	KebabCase
	CamelCase
	PascalCase
	TrimTrailingWhitespace
	// Folding.
	Fold
	Unfold
	ToggleFold
	FoldAll
	UnfoldAll
	FoldRecursive
	UnfoldRecursive
	FoldSelection
	FoldLevel1
	FoldLevel2
	FoldLevel3
	FoldLevel4
	FoldLevel5
	FoldLevel6
	FoldLevel7
	FoldLevel8
	FoldLevel9
	// Finding.
	Find
	FindReplace
	FindNext
	FindPrevious
	UseSelectionForFind
	FindInSelection
	// Going places.
	GoToLine
	ScrollCursorCenter
	ScrollLineUp
	ScrollLineDown
	GoToDefinition
	ShowCompletions
	ShowHover
	// Changes against the DiffBase, or the hunks of a diff.
	NextHunk
	PreviousHunk
	RevertHunk
	// The view.
	ToggleSoftWrap
	ToggleLineNumbers
)

Commands of code editors, as Zed's editor actions.

func CommandNamed

func CommandNamed(name string) (Command, bool)

CommandNamed returns the command of a name String returns.

func (Command) String

func (c Command) String() string

String returns the command's name, as "toggleComment".

type Completion

type Completion struct {
	// Label shows in the list, and is what the prefix typed matches.
	Label string
	// Detail shows dimmed after it, as a type or a signature.
	Detail string
	Kind   CompletionKind
	// Insert replaces the word before the caret, Label when empty.
	Insert string
	// Documentation shows beside the list for the completion chosen.
	Documentation string
	// FilterText is matched instead of Label when set.
	FilterText string
}

Completion is a completion the editor offers.

type CompletionKind

type CompletionKind uint8

CompletionKind is what a completion is, which its icon shows.

const (
	CompletionText CompletionKind = iota
	CompletionKeyword
	CompletionFunction
	CompletionMethod
	CompletionVariable
	CompletionField
	CompletionType
	CompletionModule
	CompletionConstant
	CompletionSnippet
)

func (CompletionKind) Icon

func (k CompletionKind) Icon() string

Icon returns a letter or symbol for a kind of completion, and Token the kind of token it is, whose color tints it, as the default list shows.

func (CompletionKind) Token

func (k CompletionKind) Token() TokenKind

type CompletionMenu

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

CompletionMenu is an editor's list of completions, as RenderCompletions builds it: the completions matching the word typed, best first, and the one chosen, which the arrows move and Enter or Tab inserts.

func (*CompletionMenu) Choose

func (m *CompletionMenu) Choose(i int)

Choose inserts completion i of Items in place of the word typed, and closes the list; Close closes it. Both happen once the list is built.

func (*CompletionMenu) Close

func (m *CompletionMenu) Close()

func (*CompletionMenu) Font

func (m *CompletionMenu) Font() ui.Font

Font is the editor's font, LineHeight the height of its lines, and Theme its colors, to show code as the editor does.

func (*CompletionMenu) Item

func (m *CompletionMenu) Item(i int) ui.Element

Item makes the row of completion i of Items: selected while chosen, scrolled into view as the arrows choose it, and inserting it when clicked. Style it and build its content as the row of a list.

func (*CompletionMenu) Items

func (m *CompletionMenu) Items() []Completion

Items returns the completions shown, best first.

func (*CompletionMenu) LineHeight

func (m *CompletionMenu) LineHeight() float32

func (*CompletionMenu) Prefix

func (m *CompletionMenu) Prefix() string

Prefix is the word typed, which the completions match.

func (*CompletionMenu) Selected

func (m *CompletionMenu) Selected() int

Selected is the index in Items of the completion chosen.

func (*CompletionMenu) Theme

func (m *CompletionMenu) Theme() *Theme

type CompletionRequest

type CompletionRequest struct {
	Offset   int
	Prefix   string
	Version  uint64
	Explicit bool // asked for with ui.Ctrl+Space, rather than by typing
}

CompletionRequest asks for the completions at Offset of the text at Version: Prefix is the word before the caret, which the editor filters the completions it is given by as typing goes on.

type CursorShape

type CursorShape uint8

CursorShape is the shape of an editor's carets, as Zed's CursorShape and the terminal's CursorStyle.

const (
	// CursorBar is a bar before the character at the caret.
	CursorBar CursorShape = iota
	// CursorBlock covers the character after the caret, a space's width
	// at the end of a line, translucent so that the character shows. An
	// editor without the keyboard focus outlines it, as Vim's and Zed's
	// do.
	CursorBlock
	// CursorUnderline underlines the character after the caret.
	CursorUnderline
)

type Diagnostic

type Diagnostic struct {
	Start, End int
	Severity   Severity
	Message    string
	Source     string
}

Diagnostic is a problem with a range of the text, Start to End, which shows underlined, in the hover and the scroll bar.

type DiffAnnotation

type DiffAnnotation struct {
	Side   DiffSide
	Line   int
	Height float32
	Key    any
}

DiffAnnotation is room under a line of a side for what RenderAnnotation builds there, Height DIPs high. Key identifies it among the others.

type DiffHunk

type DiffHunk struct {
	OldStart, OldEnd, NewStart, NewEnd int
}

DiffHunk is a change: the old lines OldStart to OldEnd, exclusive, replaced by the new lines NewStart to NewEnd.

type DiffHunkActions

type DiffHunkActions struct {
	// Index is the change's, in Hunks, and Hunk the change.
	Index int
	Hunk  DiffHunk
	// contains filtered or unexported fields
}

DiffHunkActions are the actions on a change of a diff, as RenderHunkActions builds them: reverting it, or keeping it.

func (*DiffHunkActions) Keep

func (a *DiffHunkActions) Keep()

func (*DiffHunkActions) Revert

func (a *DiffHunkActions) Revert()

Revert puts the change's old lines back in New; Keep makes its new lines Old's, so that it is no longer a change.

type DiffIndicators

type DiffIndicators uint8

DiffIndicators is how a diff viewer marks changed lines.

const (
	// DiffBars draws a bar at the gutter's edge, striped for deletions.
	DiffBars DiffIndicators = iota
	// DiffClassic shows + and - before the lines.
	DiffClassic
	// DiffNoIndicators marks lines by their background alone.
	DiffNoIndicators
)

type DiffInline

type DiffInline uint8

DiffInline is how a diff viewer highlights what changed within lines.

const (
	// DiffInlineWordAlt highlights words, joining those one character
	// apart, as "a b c" changed reads as one highlight.
	DiffInlineWordAlt DiffInline = iota
	// DiffInlineWord highlights each word changed.
	DiffInlineWord
	// DiffInlineWordLine highlights from the first word changed to the
	// last.
	DiffInlineWordLine
	// DiffInlineChar highlights characters.
	DiffInlineChar
	// DiffInlineNone highlights nothing within lines.
	DiffInlineNone
)

type DiffLayout

type DiffLayout uint8

DiffLayout is how a diff viewer lays out its two texts.

const (
	// DiffSplit shows the old text on the left and the new on the right,
	// their lines aligned.
	DiffSplit DiffLayout = iota
	// DiffUnified shows the new text, with the lines deleted from the
	// old above where they were.
	DiffUnified
)

type DiffLineRange

type DiffLineRange struct {
	Side       DiffSide
	Start, End int
}

DiffLineRange is lines Start to End, inclusive, from 0, of a side.

type DiffSeparator

type DiffSeparator struct {
	// Lines is how many unchanged lines it collapses, 0 for a header.
	Lines int
	// Step is how many lines ExpandUp and ExpandDown show, the
	// DiffState's ExpansionLines.
	Step int
	// First and Last report that it is before the first change, or after
	// the last, which expand one way only: up toward the change, or down
	// from it.
	First, Last bool
	// Header is the header of a patch's hunk (SetPatch), as
	// "@@ -12,7 +12,8 @@ func main", for a separator of no lines.
	Header string
	// contains filtered or unexported fields
}

DiffSeparator is a separator of a diff, as RenderSeparator builds it: unchanged lines collapsed between changes, which it expands, or the header of a patch's hunk.

func (*DiffSeparator) ExpandAll

func (s *DiffSeparator) ExpandAll()

func (*DiffSeparator) ExpandDown

func (s *DiffSeparator) ExpandDown()

func (*DiffSeparator) ExpandUp

func (s *DiffSeparator) ExpandUp()

ExpandUp shows Step more of its lines, those right above the change below it; ExpandDown those right below the change above it; ExpandAll all of them.

func (*DiffSeparator) Font

func (s *DiffSeparator) Font() ui.Font

Font is the viewer's font, and Theme its colors.

func (*DiffSeparator) Theme

func (s *DiffSeparator) Theme() *Theme

type DiffSide

type DiffSide uint8

DiffSide is a side of a diff: the old text or the new.

const (
	DiffOld DiffSide = iota
	DiffNew
)

type DiffState

type DiffState struct {
	// Old and New are the texts compared; empty buffers are made when
	// nil. New is the one edited when Editable, and can be the buffer of
	// an editor's too: an edit in either shows in both.
	Old, New *Buffer
	// Layout shows the texts side by side, or one over the other.
	Layout DiffLayout
	// Editable lets the new text be edited where it shows, with all an
	// editor does; the diff follows as it is typed.
	Editable bool
	// Inline highlights what changed within changed lines.
	Inline DiffInline
	// Indicators mark changed lines: with bars, + and -, or nothing.
	Indicators DiffIndicators
	// ContextLines is how many unchanged lines show around changes, 3
	// when 0, none when negative; the others collapse into separators
	// that expand them, ExpansionLines (100 when 0) a click, all of them
	// with Shift. ExpandUnchanged shows them all.
	ContextLines    int
	ExpansionLines  int
	ExpandUnchanged bool
	// NoBackground leaves changed lines without their tint, and
	// NoLineNumbers the gutter without numbers.
	NoBackground  bool
	NoLineNumbers bool
	// Wrap wraps long lines rather than scrolling them sideways.
	Wrap bool
	// FitContent makes the viewer as high as its lines, as a file of a
	// list of them, rather than scrolling them itself.
	FitContent bool
	// Font, LineHeight, TabSize and Theme are those of State.
	Font       ui.Font
	LineHeight float32
	TabSize    int
	Theme      *Theme
	// Bindings add key bindings to the editors of the sides.
	Bindings []Binding
	// HunkActions shows Revert and Keep on the change under the pointer,
	// or the caret's, which put the old lines back in New, or make the
	// new lines Old's, as an agent's changes are reviewed.
	HunkActions bool
	// LineSelection lets the numbers of lines be clicked and dragged to
	// select lines, which OnLineSelection reports.
	LineSelection   bool
	OnLineSelection func(DiffLineRange)
	// OnGutterButton shows a + on the gutter of the line under the
	// pointer, as to comment on it, and is called with the line when it
	// is clicked.
	OnGutterButton func(DiffLineRange)
	// Annotations show what RenderAnnotation builds under lines, as
	// comments of a review, as high as each asks; the other side of a
	// split view leaves the room empty.
	Annotations      []DiffAnnotation
	RenderAnnotation func(c *ui.Context, a DiffAnnotation)

	// RenderSeparator, RenderHunkActions and RenderGutterButton build the
	// viewer's separators, the actions on a change and the gutter's
	// button in place of its own (DefaultSeparator, DefaultHunkActions
	// and DefaultGutterButton, which they can call to wrap them): each is
	// given the element the viewer places, to style and fill, and what
	// the part shows and does. A separator is as wide as the viewer, less
	// the room of the scroll bar's track while the viewer scrolls, and 32
	// DIPs high.
	RenderSeparator    func(c *ui.Context, sep ui.Element, s *DiffSeparator)
	RenderHunkActions  func(c *ui.Context, bar ui.Element, a *DiffHunkActions)
	RenderGutterButton func(c *ui.Context, btn ui.Element, line DiffLineRange)
	// RenderFindBar and RenderGoToLine build the bars of the sides'
	// editors, as State's.
	RenderFindBar  func(c *ui.Context, bar ui.Element, f *FindBar)
	RenderGoToLine func(c *ui.Context, bar ui.Element, g *GoToLineBar)
	// contains filtered or unexported fields
}

DiffState is a diff viewer's state, kept by the app across frames: the texts it compares, its options, and what it keeps of its own, as the lines expanded and its scroll position. Zero options are the defaults, those of Pierre's diffs.

func (*DiffState) Accept

func (d *DiffState) Accept(i int)

Accept makes the new lines of hunk i Old's, so it is no longer a change.

func (*DiffState) ActiveSide

func (d *DiffState) ActiveSide() DiffSide

ActiveSide returns the side that has the keyboard, or had it last: the new side before either had it, and in a unified view. Cursor, CursorPos, CurrentHunk, GoToHunk, Run and Find act in its editor.

func (*DiffState) CollapseAll

func (d *DiffState) CollapseAll()

func (*DiffState) CurrentHunk

func (d *DiffState) CurrentHunk() (i int, inside bool)

CurrentHunk returns the hunk the caret of the active side is in, with inside true, as for Revert; else the last hunk before the caret, as "2 of 5" counts changes and Next Change steps from (GoToHunk(i+1)), or -1 before the first. On a side the hunk has no lines of, as the new side of a deletion, the caret is in it on the line where its lines were.

func (*DiffState) Cursor

func (d *DiffState) Cursor() int

Cursor returns the offset of the newest caret of the active side, in its text.

func (*DiffState) CursorPos

func (d *DiffState) CursorPos() Pos

CursorPos returns the line and column of the newest caret of the active side, in its text.

func (*DiffState) ExpandAll

func (d *DiffState) ExpandAll()

ExpandAll shows every unchanged line; CollapseAll collapses them again into separators.

func (*DiffState) Find

func (d *DiffState) Find(query string)

Find opens the find bar of the active side's editor (ActiveSide) with query, and selects its first match after the caret.

func (*DiffState) GoToHunk

func (d *DiffState) GoToHunk(i int)

GoToHunk puts the caret of the active side (ActiveSide) at the start of hunk i and scrolls it to the middle of the view.

func (*DiffState) Hunks

func (d *DiffState) Hunks() []DiffHunk

Hunks returns the changes between the texts.

func (*DiffState) Revert

func (d *DiffState) Revert(i int)

Revert puts the old lines of hunk i back in New.

func (*DiffState) Run

func (d *DiffState) Run(cmd Command) bool

Run runs a command in the editor of the active side (ActiveSide), as its key would, and reports whether it did something: Find opens its find bar, as an app's menu item does.

func (*DiffState) SelectedLines

func (d *DiffState) SelectedLines() (DiffLineRange, bool)

SelectedLines returns the lines selected by their numbers, and whether there are.

func (*DiffState) SetPatch

func (d *DiffState) SetPatch(p FilePatch)

SetPatch shows a file's patch without the files: its hunks' lines, numbered as in the files, each hunk under its header, as Pierre's diffs show partial patches. Old and New become texts of those lines, not editable, and unchanged lines do not collapse.

func (*DiffState) SetSelectedLines

func (d *DiffState) SetSelectedLines(r DiffLineRange, ok bool)

SetSelectedLines selects lines, as clicking their numbers does; ok false clears the selection.

func (*DiffState) Stats

func (d *DiffState) Stats() (added, deleted int)

Stats returns how many lines the changes add and delete.

type Edit

type Edit struct {
	Start, End int
	Text       string
}

Edit replaces the bytes Start to End of a Buffer's text with Text.

type FilePatch

type FilePatch struct {
	// OldName and NewName are the file's names before and after, without
	// git's a/ and b/; OldName is empty for a file added, NewName for one
	// deleted.
	OldName, NewName string
	// OldMode and NewMode are git's file modes, as "100644", when given.
	OldMode, NewMode string
	// Binary marks a change git shows no lines of.
	Binary bool
	Hunks  []PatchHunk
}

FilePatch is the change of one file in a unified diff, as git diff and diff -u print them.

func ParsePatch

func ParsePatch(text string) ([]FilePatch, error)

ParsePatch reads the files a unified diff changes, in order: those of git diff and git format-patch, with renames, modes and new and deleted files, and those of diff -u.

func (FilePatch) Apply

func (p FilePatch) Apply(old string) (string, error)

Apply applies the patch to the old file's text and returns the new file's, checking that the lines of both and those deleted are there.

type FindBar

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

FindBar is an editor's find bar, as RenderFindBar builds it: the query and its options, which the matches follow as they change, and what the bar does.

func (*FindBar) CanReplace

func (f *FindBar) CanReplace() bool

func (*FindBar) CaseSensitive

func (f *FindBar) CaseSensitive() *bool

CaseSensitive, WholeWord, Regexp and InSelection are the options of the search, to bind toggles to: matching case, whole words only, the query as a regular expression (RE2, as package regexp's), and only within the selections there were as the option was turned on.

func (*FindBar) Close

func (f *FindBar) Close()

Close closes the bar, and gives the keyboard back to the text.

func (*FindBar) Err

func (f *FindBar) Err() error

Err is the error of a query that is not a valid regular expression.

func (*FindBar) InSelection

func (f *FindBar) InSelection() *bool

func (*FindBar) Matches

func (f *FindBar) Matches() (count, current int)

Matches returns how many matches there are, and the index of the one selected, -1 without matches.

func (*FindBar) Next

func (f *FindBar) Next()

Next and Previous select the next and previous match after the caret, round the ends; SelectAll selects every match, with a caret each, and closes the bar.

func (*FindBar) Previous

func (f *FindBar) Previous()

func (*FindBar) Query

func (f *FindBar) Query() *string

Query and Replacement are the texts of the bar's fields, to bind inputs to, with QueryInput and ReplacementInput.

func (*FindBar) QueryInput

func (f *FindBar) QueryInput(in ui.Element) ui.Element

QueryInput makes in the field of the query: it takes the focus with the query selected as the bar opens, and Enter goes to the next match, Shift+Enter to the previous, Alt+Enter selects them all, and Escape closes the bar. It returns in.

func (*FindBar) Regexp

func (f *FindBar) Regexp() *bool

func (*FindBar) Replace

func (f *FindBar) Replace()

Replace replaces the match selected and selects the next; ReplaceAll replaces every match, as one step of undo. A regular expression's replacement expands $1 and ${name}.

func (*FindBar) ReplaceAll

func (f *FindBar) ReplaceAll()

func (*FindBar) Replacement

func (f *FindBar) Replacement() *string

func (*FindBar) ReplacementInput

func (f *FindBar) ReplacementInput(in ui.Element) ui.Element

ReplacementInput makes in the field of the replacement: Enter replaces the match selected, Cmd+Enter all of them, and Escape closes the bar. It returns in.

func (*FindBar) Replacing

func (f *FindBar) Replacing() bool

Replacing reports whether the bar replaces too, as Cmd+Alt+F opens it, and SetReplacing shows or hides replacing, which CanReplace reports a read-only editor never does.

func (*FindBar) SelectAll

func (f *FindBar) SelectAll()

func (*FindBar) SetReplacing

func (f *FindBar) SetReplacing(on bool)

func (*FindBar) Status

func (f *FindBar) Status() string

Status says what was found, as "3 of 12", "No results", or "Invalid" for a regular expression that is not one (Err); nothing without a query.

func (*FindBar) WholeWord

func (f *FindBar) WholeWord() *bool

type Folder

type Folder interface {
	FoldEnd(line int) (end int, ok bool)
}

Folder is a Highlighter knowing what folds: FoldEnd returns the last line folding line hides, and whether line starts a fold, rather than what indentation and brackets say.

type GoToLineBar

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

GoToLineBar is an editor's go to line bar, as RenderGoToLine builds it: line[:column], or +n and -n lines from the caret, which the editor scrolls to as it is typed, as Zed's.

func (*GoToLineBar) Close

func (g *GoToLineBar) Close()

func (*GoToLineBar) Cursor

func (g *GoToLineBar) Cursor() Pos

Cursor is where the newest caret is, and LineCount how many lines there are, as the bar tells.

func (*GoToLineBar) Go

func (g *GoToLineBar) Go()

Go moves the caret to the line typed and closes the bar; Close closes it where the editor was.

func (*GoToLineBar) Input

func (g *GoToLineBar) Input(in ui.Element) ui.Element

Input makes in the bar's field: it takes the focus as the bar opens, Enter goes to the line, and Escape closes the bar where the editor was. It returns in.

func (*GoToLineBar) LineCount

func (g *GoToLineBar) LineCount() int

func (*GoToLineBar) Target

func (g *GoToLineBar) Target() (Pos, bool)

Target is the line and column typed, from 0, and whether the text is one.

func (*GoToLineBar) Text

func (g *GoToLineBar) Text() *string

Text is the text of the bar's field, to bind an input to, with Input.

type GutterMark

type GutterMark struct {
	Line  int
	Color ui.Color
}

GutterMark marks a line in the gutter.

type Highlighter

type Highlighter interface {
	// Edit follows an edit of the text: old and new are the text before
	// and after it, and changes what it replaced, in order.
	Edit(old, new Snapshot, changes []Change)
	// Highlight works toward the tokens of the lines up to last, for at
	// most budget, and reports whether they are ready. Editors call it
	// before painting lines, and in later frames while it reports false.
	Highlight(last int, budget time.Duration) bool
	// Tokens appends the tokens of line i, whose text is text, to dst,
	// and reports whether they are final: false while they are a guess
	// made before Highlight's work on them is done, which editors show
	// until it is.
	Tokens(i int, text string, dst []Token) ([]Token, bool)
}

Highlighter highlights a buffer's text and follows its edits, as Zed's syntax map does: editors give it the edits of the text, have it work toward the lines they show, and paint the tokens it gives. Its methods run on the main thread; what it does in the background, on snapshots, it tells of with the invalidate function it was made with.

A highlighter can also know the structure of the text, as a parser's does: it may implement SyntaxSelector, Folder, BracketMatcher and Indenter, which editors then use rather than tokens and indentation.

func NewTokenHighlighter

func NewTokenHighlighter(t Tokenizer, text Snapshot) Highlighter

NewTokenHighlighter returns the highlighter of text that a Language uses by default: t tokenizes each line from the state the line before ends in, and an edit tokenizes the lines after it again until one starts in the state it started in before, as TextMate grammars and Monaco do, a frame's budget at a time.

type HoverCard

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

HoverCard is what an editor shows of the text under the pointer, as RenderHover builds it: the diagnostics there, and what the app gave ShowHover.

func (*HoverCard) Content

func (h *HoverCard) Content()

func (*HoverCard) Diagnostics

func (h *HoverCard) Diagnostics() []Diagnostic

Diagnostics are the diagnostics of the text hovered.

func (*HoverCard) Font

func (h *HoverCard) Font() ui.Font

Font is the editor's font, and Theme its colors.

func (*HoverCard) Range

func (h *HoverCard) Range() (start, end int)

Range is the text hovered, from start to end.

func (*HoverCard) Text

func (h *HoverCard) Text() string

Text is the text ShowHover gave, and Content builds what its function builds, when it gave one.

func (*HoverCard) Theme

func (h *HoverCard) Theme() *Theme

type HoverRequest

type HoverRequest struct {
	Offset  int
	Version uint64
}

HoverRequest asks what to show for the text at Offset under the pointer, or at the caret.

type IndentStyle

type IndentStyle uint8

IndentStyle is what indenting inserts.

const (
	IndentAuto IndentStyle = iota
	IndentSpaces
	IndentTabs
)

type Indenter

type Indenter interface {
	IndentAfter(offset int) (levels int, ok bool)
}

Indenter is a Highlighter knowing indentation: IndentAfter returns how many levels more than the line holding offset (fewer, negative) a line that Return opens there is indented.

type Inlay

type Inlay struct {
	Offset int
	Text   string
}

Inlay is text shown in a line that is not part of it, as an inlay hint of a type or a parameter's name: at Offset, muted.

type Language

type Language struct {
	Name string
	// Extensions and Filenames find the language of a file, as ".go" or
	// "Makefile" (LanguageFor).
	Extensions []string
	Filenames  []string
	// LineComment starts a comment to the end of the line, as "//";
	// BlockComment encloses one, as {"/*", "*/"}. Toggling comments uses
	// the first, else the second.
	LineComment  string
	BlockComment [2]string
	// Brackets are matched, highlighted at the caret, and indent the
	// lines between them; AutoClose are closed as they are typed, and
	// wrap the selection.
	Brackets  []BracketPair
	AutoClose []BracketPair
	// IncreaseIndent matches a line after which the next is indented one
	// more level, as one ending in { or :; DecreaseIndent a line that is
	// one level less than the one before, as one starting with end, which
	// typing outdents. Without them, the Brackets decide; and a closing
	// bracket typed first on its line takes its opener's indentation.
	IncreaseIndent *regexp.Regexp
	DecreaseIndent *regexp.Regexp
	// WordChars are characters other than letters, digits and _ that
	// words hold, as - in CSS.
	WordChars string
	// TabSize and HardTabs are the indentation the language's files
	// usually have, which editors take unless set: Go's tabs.
	TabSize  int
	HardTabs bool
	// Tokenizer highlights the text a line at a time, as TextMate
	// grammars do (NewTokenHighlighter): the default highlighter, which
	// Highlighter replaces.
	Tokenizer Tokenizer
	// Highlighter makes the highlighter of a buffer of the language, for
	// highlighting of its own, as a parser's, as tree-sitter's: text is
	// the buffer's text, and invalidate draws the windows showing it
	// again, from any goroutine, for work done in the background. When
	// nil, Tokenizer highlights.
	Highlighter func(text Snapshot, invalidate func()) Highlighter
}

Language is what a Buffer knows of the language of its text: how to highlight it, comment it, match its brackets and indent it.

func LanguageFor

func LanguageFor(filename string) *Language

LanguageFor returns the language of a file by its name, as "main.go" or "Makefile", or nil when Golet knows none for it.

func LanguageNamed

func LanguageNamed(name string) *Language

LanguageNamed returns the language Golet knows by a name, as "Go", "TypeScript" or "tsx", ignoring case: its Name, an extension without the dot, or a usual alias, as Markdown's code blocks name them.

func Languages

func Languages() []*Language

Languages returns the languages Golet knows how to highlight.

type LineBackground

type LineBackground struct {
	First, Last int
	Color       ui.Color
}

LineBackground fills lines First to Last, from 0, with Color. The lines are those of the text when it is set: an edit adding or removing lines above them doesn't move them.

type LineNumbers

type LineNumbers uint8

LineNumbers is how the gutter numbers lines.

const (
	LineNumbersOn LineNumbers = iota
	LineNumbersRelative
	LineNumbersOff
)

type PatchHunk

type PatchHunk struct {
	OldStart, OldLines int
	NewStart, NewLines int
	// Section is what follows the second @@, as the function the hunk is
	// in.
	Section string
	// Lines are the hunk's lines with their first character: a space for
	// a line of both, - for one deleted, + for one added. A line "\ No
	// newline at end of file" follows the line it is about.
	Lines []string
}

PatchHunk is a hunk of a FilePatch: lines from OldStart (from 1) of the old file, OldLines of them, and NewStart and NewLines of the new.

type Pos

type Pos struct{ Line, Col int }

Pos is a place in a text: a line, from 0, and a column in bytes from the start of the line.

func (Pos) Less

func (p Pos) Less(q Pos) bool

Less reports whether p comes before q.

type Range

type Range struct{ Start, End int }

Range is a range of a text's bytes, Start to End.

type Selection

type Selection struct {
	Anchor, Head int
}

Selection is a selection of an editor: the text from Anchor to Head, byte offsets, with the caret at Head. Anchor == Head is a caret alone.

func (Selection) Empty

func (s Selection) Empty() bool

Empty reports whether the selection is a caret alone.

func (Selection) End

func (s Selection) End() int

func (Selection) Start

func (s Selection) Start() int

Start and End return the selection's edges in order.

type Severity

type Severity uint8

Severity is how bad a diagnostic is.

const (
	SeverityError Severity = iota
	SeverityWarning
	SeverityInfo
	SeverityHint
)

type Snapshot

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

Snapshot is a version of a buffer's text, which stays as it is while the buffer changes: read it from any goroutine.

func (Snapshot) Chunks

func (s Snapshot) Chunks(start, end int, fn func(text string) bool)

Chunks calls fn with bytes start to end, a piece at a time, until fn returns false: what a parser reads text with.

func (Snapshot) Len

func (s Snapshot) Len() int

Len, LineCount and String return the length in bytes, the number of lines and the text of the snapshot.

func (Snapshot) Line

func (s Snapshot) Line(i int) string

Line returns line i, without its newline.

func (Snapshot) LineCount

func (s Snapshot) LineCount() int

func (Snapshot) LineEnd

func (s Snapshot) LineEnd(i int) int

func (Snapshot) LineOf

func (s Snapshot) LineOf(offset int) int

LineOf returns the line holding byte offset.

func (Snapshot) LineStart

func (s Snapshot) LineStart(i int) int

LineStart and LineEnd return the bytes line i starts and ends at, before its newline.

func (Snapshot) Offset

func (s Snapshot) Offset(p Pos) int

func (Snapshot) Pos

func (s Snapshot) Pos(offset int) Pos

Pos returns the line and column of byte offset, and Offset the byte of a line and column.

func (Snapshot) Slice

func (s Snapshot) Slice(start, end int) string

Slice returns bytes start to end.

func (Snapshot) String

func (s Snapshot) String() string

func (Snapshot) Version

func (s Snapshot) Version() uint64

Version returns the buffer's version the snapshot is of.

func (Snapshot) WriteTo

func (s Snapshot) WriteTo(w io.Writer) (int64, error)

WriteTo writes the text to w.

type State

type State struct {
	// Buffer is the text the editor edits; one is made when nil.
	Buffer *Buffer
	// Font is the editor's font: the system's monospaced font of 13 DIPs
	// when zero.
	Font ui.Font
	// LineHeight is the height of lines as a multiple of the font's size,
	// 1.5 when 0.
	LineHeight float32
	// TabSize is how many columns a tab and a level of indentation take:
	// the language's, else 4, when 0.
	TabSize int
	// Indent says whether indenting inserts tabs or spaces: as the
	// language's files usually do (Go's tabs) by default.
	Indent IndentStyle
	// SoftWrap wraps lines at the editor's width, or at WrapColumn
	// columns when narrower.
	SoftWrap   bool
	WrapColumn int
	// LineNumbers shows the numbers of lines in the gutter, absolute by
	// default.
	LineNumbers LineNumbers
	// ReadOnly makes the text selectable and copyable, not editable.
	ReadOnly bool
	// Whitespace says where spaces and tabs show as dots and arrows:
	// within selections by default.
	Whitespace Whitespace
	// WrapGuides draws guides at these columns, as 80 and 100.
	WrapGuides []int
	// NoIndentGuides hides the lines that show indentation levels.
	NoIndentGuides bool
	// NoScrollPastEnd stops scrolling at the last line rather than
	// letting it scroll up to the top.
	NoScrollPastEnd bool
	// NoAutoClose stops closing brackets and quotes as they are typed.
	NoAutoClose bool
	// NoFolding hides the fold markers of the gutter and turns folding
	// off.
	NoFolding bool
	// NoActiveLine stops highlighting the lines with a caret.
	NoActiveLine bool
	// CursorShape is the shape of the carets: bars by default, or blocks
	// over the character after them, as Vim's normal mode has, or
	// underlines, as its pending operators do.
	CursorShape CursorShape
	// FitContent makes the editor as high as its lines, to show in a
	// scroll view or a list, rather than scrolling them itself.
	FitContent bool
	// Placeholder shows while the buffer is empty.
	Placeholder string
	// Label names the editor for assistive technology.
	Label string
	// Theme colors the editor; DefaultTheme of the window's theme
	// when nil.
	Theme *Theme
	// Bindings add key bindings, or replace the default ones for their
	// keys (DefaultBindings).
	Bindings []Binding
	// DiffBase, when set, is the text the buffer's changes are shown
	// against in the gutter, as the version of a file in Git: bars mark
	// lines added and changed, and a mark where lines were deleted.
	DiffBase *Buffer

	// OnCompletion asks the app for completions where the caret is, as
	// a word is typed or Ctrl+Space pressed: answer with ShowCompletions,
	// at once or later.
	OnCompletion func(CompletionRequest)
	// OnHover asks the app what to show for the text under the pointer
	// once it rests there: answer with ShowHover.
	OnHover func(HoverRequest)
	// OnDefinition is called for Cmd+click (Ctrl+click elsewhere) and F12
	// on a word, as to go to its definition.
	OnDefinition func(offset int)
	// OnGutterClick is called for a click on a line's number, as to set a
	// breakpoint.
	OnGutterClick func(line int)
	// ContextMenu adds items to the editor's context menu, after its
	// own.
	ContextMenu func(m *ui.Menu)
	// GutterMarks marks lines in the gutter, as breakpoints or
	// bookmarks: a dot of their color.
	GutterMarks []GutterMark
	// LineBackgrounds fill the rows of lines with colors, under the
	// text and the selections, as the statement a key runs: not the
	// gutter, nor the lines folds hide. They keep their line numbers as
	// the text is edited, unlike diagnostics and inlays, which move with
	// it: compute them again when the buffer's Version changes.
	LineBackgrounds []LineBackground
	// OnInput sees each input event before the editor, as keys for a
	// mode of the app's such as Vim's: returning true takes it, and the
	// editor leaves it. Text typed at the carets comes as InputText;
	// what an input method composes, commits or replaces, as the accents
	// of press and hold, goes to the editor alone. The key after the
	// first of a chord of Bindings, as Cmd+K Cmd+0, is the chord's.
	OnInput func(ev ui.InputEvent) bool
	// NoInputMethod turns the system's input methods off while the
	// editor has the keyboard (ui's InputMethod): keys type the
	// characters of the keyboard's layout, which come to OnInput as
	// InputText, and nothing is composed, as Vim's normal mode wants
	// with a Chinese input method on. Browsers cannot turn input methods
	// off: there they compose in the text still.
	NoInputMethod bool

	// RenderFindBar, RenderGoToLine, RenderCompletions and RenderHover
	// build the editor's find bar, go to line bar, completions and hovers
	// in place of its own (DefaultFindBar, DefaultGoToLine,
	// DefaultCompletions and DefaultHover, which they can call to wrap
	// them): each is given the element the editor places, as a toolbar
	// over its top right corner or a list below the caret, to style and
	// fill, and a handle to what the part shows and does.
	RenderFindBar     func(c *ui.Context, bar ui.Element, f *FindBar)
	RenderGoToLine    func(c *ui.Context, bar ui.Element, g *GoToLineBar)
	RenderCompletions func(c *ui.Context, panel ui.Element, m *CompletionMenu)
	RenderHover       func(c *ui.Context, panel ui.Element, h *HoverCard)
	// contains filtered or unexported fields
}

State is a code editor's state, kept by the app across frames: the buffer it edits, its options, and what the editor keeps of its own, as its selections, folds and scroll position. Set the options before building the editor; zero values are the defaults, those of Zed.

func (*State) Cursor

func (st *State) Cursor() int

Cursor returns the offset of the newest caret.

func (*State) CursorPos

func (st *State) CursorPos() Pos

CursorPos returns the line and column of the newest caret.

func (*State) Diagnostics

func (st *State) Diagnostics() []Diagnostic

Diagnostics returns the diagnostics shown, where the edits since moved them.

func (*State) Find

func (st *State) Find(query string)

Find opens the find bar with query, and selects its first match after the caret.

func (*State) FindMatches

func (st *State) FindMatches() (count, current int)

FindMatches returns how many matches the find bar has, and which is chosen, from 0.

func (*State) Focused

func (st *State) Focused() bool

Focused reports whether the editor had the keyboard focus in the last frame.

func (*State) Fold

func (st *State) Fold(line int)

Fold folds the lines indented under line, or up to its closing bracket, as the gutter's marker does; Unfold unfolds them.

func (*State) Folded

func (st *State) Folded() []int

Folded returns the lines folds start at.

func (*State) GoTo

func (st *State) GoTo(p Pos)

GoTo puts the caret at a line and column, from 0, and scrolls it to the middle of the editor.

func (*State) Insert

func (st *State) Insert(text string)

Insert replaces each selection with text, as typing or pasting it.

func (*State) Run

func (st *State) Run(cmd Command) bool

Run runs a command as its key would, and reports whether it did something.

func (*State) ScrollTo

func (st *State) ScrollTo(line int)

ScrollTo scrolls a line to the top of the editor.

func (*State) Select

func (st *State) Select(start, end int)

Select selects the text from start to end, a caret alone at end when they are equal.

func (*State) SelectedText

func (st *State) SelectedText() string

SelectedText returns the text of the selections, joined by newlines.

func (*State) Selection

func (st *State) Selection() Selection

Selection returns the newest selection, the one input methods and scrolling follow.

func (*State) Selections

func (st *State) Selections() []Selection

Selections returns the editor's selections, in order.

func (*State) SetDiagnostics

func (st *State) SetDiagnostics(version uint64, ds []Diagnostic)

SetDiagnostics shows diagnostics of the text at version, the buffer's Version when they were made: those of an older version move with the edits since, as a language server's that arrive late.

func (*State) SetInlays

func (st *State) SetInlays(inlays []Inlay)

SetInlays shows inlay hints in the lines, as types and parameter names: they move with the edits until set again.

func (*State) SetSelections

func (st *State) SetSelections(sels ...Selection)

SetSelections sets the selections, the last the newest, and scrolls it into view.

func (*State) SetSuggestion

func (st *State) SetSuggestion(offset int, text string)

SetSuggestion shows text at offset, muted, as an edit prediction: Tab inserts it, and an edit or a move of the caret drops it. An empty text takes it away.

func (*State) ShowCompletions

func (st *State) ShowCompletions(start int, items []Completion)

ShowCompletions shows completions of the word before the caret, which starts at offset start (the request's Offset less its Prefix), or -1 for the word there now. Typing filters them; an empty list closes them.

func (*State) ShowHover

func (st *State) ShowHover(start, end int, text string, build func(c *ui.Context))

ShowHover shows what the text from start to end is: text in the editor's font, and what build adds, as a hover of a language server.

func (*State) Unfold

func (st *State) Unfold(line int)

func (*State) VisibleLines

func (st *State) VisibleLines() (first, last int)

VisibleLines returns the first and the last line, from 0, that the last frame showed, those hidden by folds among them.

type SyntaxSelector

type SyntaxSelector interface {
	Enclosing(start, end int) (Range, bool)
}

SyntaxSelector is a Highlighter knowing the nodes of a syntax tree: Select Larger (SelectLarger) selects the smallest node holding more than the bytes start to end, rather than the word, string or brackets around them.

type Theme

type Theme struct {
	Background ui.Color
	Text       ui.Color
	// LineNumber colors the numbers of the gutter, ActiveLineNumber those
	// of the lines with a caret.
	LineNumber       ui.Color
	ActiveLineNumber ui.Color
	// ActiveLine highlights the lines with a caret.
	ActiveLine ui.Color
	// Selection highlights selected text while the editor has the focus,
	// InactiveSelection while it does not.
	Selection         ui.Color
	InactiveSelection ui.Color
	Cursor            ui.Color
	// MatchingBracket outlines the brackets around the caret.
	MatchingBracket ui.Color
	// Match highlights the matches of the find bar, CurrentMatch the one
	// chosen; Occurrence other occurrences of the selected text.
	Match        ui.Color
	CurrentMatch ui.Color
	Occurrence   ui.Color
	// IndentGuide draws the indent guides, ActiveIndentGuide the one
	// around the caret; WrapGuide the guides at the columns the editor
	// marks; Whitespace the dots and arrows of spaces and tabs shown.
	IndentGuide       ui.Color
	ActiveIndentGuide ui.Color
	WrapGuide         ui.Color
	Whitespace        ui.Color
	// Error, Warning, Info and Hint color diagnostics of each severity.
	Error, Warning, Info, Hint ui.Color
	// Added, Deleted and Modified are the colors of changes, which tint
	// the lines of diffs, their gutters and the words changed in them.
	Added, Deleted, Modified ui.Color
	// Tokens styles the kinds of tokens; a zero color is Text.
	Tokens [tokenKinds]TokenStyle
}

Theme colors editors and diffs. Colors left zero take those of DefaultTheme for the window's appearance, which follow its Theme.

func DefaultTheme

func DefaultTheme(t *ui.Theme) *Theme

DefaultTheme returns the code theme for a window's theme: its background and text, with GitHub's colors for code.

func (*Theme) SeverityColor

func (ct *Theme) SeverityColor(s Severity) ui.Color

SeverityColor returns the color of diagnostics of a severity.

func (*Theme) TokenColor

func (ct *Theme) TokenColor(k TokenKind) ui.Color

TokenColor returns the color of a kind of token: its style's, else the text's.

type Token

type Token struct {
	End  int
	Kind TokenKind
}

Token is a run of a line of code of one kind, from the end of the token before it, or the start of the line, to End, a byte offset in the line.

type TokenKind

type TokenKind uint8

TokenKind is what a token of code is, which the editor's theme colors.

const (
	TokenText TokenKind = iota
	TokenKeyword
	TokenType
	TokenFunction
	TokenVariable
	TokenProperty
	TokenConstant
	TokenNumber
	TokenString
	TokenEscape // escapes and interpolations in strings
	TokenRegexp
	TokenComment
	TokenOperator
	TokenPunctuation
	TokenTag       // HTML and XML elements
	TokenAttribute // their attributes
	TokenMeta      // preprocessor lines, decorators, annotations
	TokenHeading
	TokenEmphasis
	TokenStrong
	TokenLink
	TokenCode // code in prose, as Markdown's
	TokenInserted
	TokenDeleted
	TokenInvalid
)

Kinds of tokens.

type TokenStyle

type TokenStyle struct {
	Color  ui.Color
	Italic bool
	Bold   bool
}

TokenStyle is how a kind of token shows.

type Tokenizer

type Tokenizer interface {
	Tokenize(line string, state uint64, tokens []Token) ([]Token, uint64)
}

Tokenizer splits lines of code into tokens. Tokenize appends the tokens of line, which has no newline, to tokens, starting in state, and returns them with the state the line ends in, which the next line starts in: 0 at the start of the text, and states that compare equal for lines that go on alike, as being inside a comment.

type TokenizerFunc

type TokenizerFunc func(line string, state uint64, tokens []Token) ([]Token, uint64)

TokenizerFunc is a function that is a Tokenizer.

func (TokenizerFunc) Tokenize

func (f TokenizerFunc) Tokenize(line string, state uint64, tokens []Token) ([]Token, uint64)

Tokenize calls f.

type Whitespace

type Whitespace uint8

Whitespace is where spaces and tabs show.

const (
	WhitespaceSelection Whitespace = iota
	WhitespaceNone
	WhitespaceAll
	WhitespaceTrailing
	// WhitespaceBoundary shows whitespace but single spaces between
	// words.
	WhitespaceBoundary
)

Jump to

Keyboard shortcuts

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