Documentation
¶
Overview ¶
Package editor is a code editor and a diff viewer for MyGo'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 with editable snippets, 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 ¶
- func DefaultCompletions(c *ui.Context, panel ui.Element, m *CompletionMenu)
- func DefaultFindBar(c *ui.Context, bar ui.Element, f *FindBar)
- func DefaultGoToLine(c *ui.Context, bar ui.Element, g *GoToLineBar)
- func DefaultGutterButton(c *ui.Context, btn ui.Element, r DiffLineRange)
- func DefaultHover(c *ui.Context, panel ui.Element, h *HoverCard)
- func DefaultHunkActions(c *ui.Context, bar ui.Element, a *DiffHunkActions)
- func DefaultSeparator(c *ui.Context, sep ui.Element, s *DiffSeparator)
- func DiffView(c *ui.Context, d *DiffState) ui.Element
- func View(c *ui.Context, st *State) ui.Element
- type Binding
- type BracketMatcher
- type BracketPair
- type Buffer
- func (b *Buffer) CanRedo() bool
- func (b *Buffer) CanUndo() bool
- func (b *Buffer) Edit(edits ...Edit)
- func (b *Buffer) Language() *Language
- func (b *Buffer) Len() int
- func (b *Buffer) Line(i int) string
- func (b *Buffer) LineCount() int
- func (b *Buffer) LineEnding() string
- func (b *Buffer) MarkSaved()
- func (b *Buffer) Modified() bool
- func (b *Buffer) Offset(p Pos) int
- func (b *Buffer) Pos(offset int) Pos
- func (b *Buffer) Redo() bool
- func (b *Buffer) Reset(text string)
- func (b *Buffer) Set(text string)
- func (b *Buffer) SetLanguage(l *Language)
- func (b *Buffer) SetLineEnding(ending string)
- func (b *Buffer) Slice(start, end int) string
- func (b *Buffer) Snapshot() Snapshot
- func (b *Buffer) String() string
- func (b *Buffer) Transact(fn func())
- func (b *Buffer) Undo() bool
- func (b *Buffer) Version() uint64
- func (b *Buffer) WriteTo(w io.Writer) (int64, error)
- type Change
- type Command
- type Completion
- type CompletionKind
- type CompletionMenu
- func (m *CompletionMenu) Choose(i int)
- func (m *CompletionMenu) Close()
- func (m *CompletionMenu) Font() ui.Font
- func (m *CompletionMenu) Item(i int) ui.Element
- func (m *CompletionMenu) Items() []Completion
- func (m *CompletionMenu) LineHeight() float32
- func (m *CompletionMenu) Prefix() string
- func (m *CompletionMenu) Selected() int
- func (m *CompletionMenu) Theme() *Theme
- type CompletionRequest
- type CursorShape
- type Diagnostic
- type DiffAnnotation
- type DiffHunk
- type DiffHunkActions
- type DiffIndicators
- type DiffInline
- type DiffLayout
- type DiffLineRange
- type DiffSeparator
- type DiffSide
- type DiffState
- func (d *DiffState) Accept(i int)
- func (d *DiffState) ActiveSide() DiffSide
- func (d *DiffState) CollapseAll()
- func (d *DiffState) CurrentHunk() (i int, inside bool)
- func (d *DiffState) Cursor() int
- func (d *DiffState) CursorPos() Pos
- func (d *DiffState) ExpandAll()
- func (d *DiffState) Find(query string)
- func (d *DiffState) GoToHunk(i int)
- func (d *DiffState) Hunks() []DiffHunk
- func (d *DiffState) LineTop(side DiffSide, line int) float64
- func (d *DiffState) Revert(i int)
- func (d *DiffState) Run(cmd Command) bool
- func (d *DiffState) ScrollY() float64
- func (d *DiffState) SelectedLines() (DiffLineRange, bool)
- func (d *DiffState) SetPatch(p FilePatch)
- func (d *DiffState) SetScrollY(y float64)
- func (d *DiffState) SetSelectedLines(r DiffLineRange, ok bool)
- func (d *DiffState) Stats() (added, deleted int)
- func (d *DiffState) ViewportHeight() float64
- type Edit
- type FilePatch
- type FindBar
- func (f *FindBar) CanReplace() bool
- func (f *FindBar) CaseSensitive() *bool
- func (f *FindBar) Close()
- func (f *FindBar) Err() error
- func (f *FindBar) InSelection() *bool
- func (f *FindBar) Matches() (count, current int)
- func (f *FindBar) Next()
- func (f *FindBar) Previous()
- func (f *FindBar) Query() *string
- func (f *FindBar) QueryInput(in ui.Element) ui.Element
- func (f *FindBar) Regexp() *bool
- func (f *FindBar) Replace()
- func (f *FindBar) ReplaceAll()
- func (f *FindBar) Replacement() *string
- func (f *FindBar) ReplacementInput(in ui.Element) ui.Element
- func (f *FindBar) Replacing() bool
- func (f *FindBar) SelectAll()
- func (f *FindBar) SetReplacing(on bool)
- func (f *FindBar) Status() string
- func (f *FindBar) WholeWord() *bool
- type Folder
- type GoToLineBar
- type GutterMark
- type Highlighter
- type HoverCard
- type HoverRequest
- type IndentStyle
- type Indenter
- type Inlay
- type Language
- type LineBackground
- type LineNumbers
- type PatchHunk
- type Pos
- type Range
- type Selection
- type Severity
- type Snapshot
- func (s Snapshot) Chunks(start, end int, fn func(text string) bool)
- func (s Snapshot) Len() int
- func (s Snapshot) Line(i int) string
- func (s Snapshot) LineCount() int
- func (s Snapshot) LineEnd(i int) int
- func (s Snapshot) LineOf(offset int) int
- func (s Snapshot) LineStart(i int) int
- func (s Snapshot) Offset(p Pos) int
- func (s Snapshot) Pos(offset int) Pos
- func (s Snapshot) Slice(start, end int) string
- func (s Snapshot) String() string
- func (s Snapshot) Version() uint64
- func (s Snapshot) WriteTo(w io.Writer) (int64, error)
- type Snippet
- type State
- func (st *State) Cursor() int
- func (st *State) CursorPos() Pos
- func (st *State) Diagnostics() []Diagnostic
- func (st *State) Find(query string)
- func (st *State) FindMatches() (count, current int)
- func (st *State) Focused() bool
- func (st *State) Fold(line int)
- func (st *State) FoldImports()
- func (st *State) Folded() []int
- func (st *State) GoTo(p Pos)
- func (st *State) Insert(text string)
- func (st *State) InsertSnippet(s *Snippet) bool
- func (st *State) LineTop(line int) float64
- func (st *State) Run(cmd Command) bool
- func (st *State) ScrollTo(line int)
- func (st *State) ScrollY() float64
- func (st *State) Select(start, end int)
- func (st *State) SelectedText() string
- func (st *State) Selection() Selection
- func (st *State) Selections() []Selection
- func (st *State) SetDiagnostics(version uint64, ds []Diagnostic)
- func (st *State) SetInlays(inlays []Inlay)
- func (st *State) SetScrollY(y float64)
- func (st *State) SetSelections(sels ...Selection)
- func (st *State) SetSuggestion(offset int, text string)
- func (st *State) ShowCompletions(start int, items []Completion)
- func (st *State) ShowHover(start, end int, text string, build func(c *ui.Context))
- func (st *State) Unfold(line int)
- func (st *State) ViewportHeight() float64
- func (st *State) VisibleLines() (first, last int)
- type SyntaxSelector
- type TextBackground
- type Theme
- type Token
- type TokenKind
- type TokenStyle
- type Tokenizer
- type TokenizerFunc
- type Whitespace
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 ¶
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 ¶
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 View ¶
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 ¶
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 (*Buffer) 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) LineCount ¶
LineCount returns how many lines the text has: one more than its newlines.
func (*Buffer) LineEnding ¶
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 ¶
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) Reset ¶
Reset replaces the text and forgets the undo history, as for a file loaded anew, and makes it the saved text.
func (*Buffer) SetLanguage ¶
SetLanguage sets the language that highlights the text, and that comments, brackets and indentation follow; nil is plain text.
func (*Buffer) SetLineEnding ¶
func (*Buffer) 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) 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.
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 ¶
CommandNamed returns the command of a name String returns.
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
// Snippet inserts a parsed template, overriding Insert and Label.
// Kind alone only chooses an icon; it never interprets Insert.
Snippet *Snippet
// 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 ¶ added in v0.5.0
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 ¶
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 ¶
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 ¶
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 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
// SplitPercent is the percentage of a split view's width the old
// side takes, from 0 to 100, half when 0: the user drags the line
// between the sides to change it, or moves it with the arrows once it
// has the keyboard focus, as ui.SplitPercent's divider, and the app
// keeps it to show the sides as the user left them. Each side keeps
// the room of its gutter and 12 columns of text, where the view is
// wide enough for both, and the share is kept for when it is again.
SplitPercent float32
// 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
// KeepScrollbars and NoScrollbars are those of State: the scroll
// bars stay with the pointer away, or are taken away with their room.
KeepScrollbars bool
NoScrollbars 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) ActiveSide ¶ added in v0.5.0
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 ¶ added in v0.5.0
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 ¶ added in v0.5.0
Cursor returns the offset of the newest caret of the active side, in its text.
func (*DiffState) CursorPos ¶ added in v0.5.0
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 ¶ added in v0.5.0
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 ¶
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) LineTop ¶ added in v0.8.0
LineTop returns the top of a line of a side, from 0, in DIPs below the top of the diff's first row, as the last frame laid the diff out: less ScrollY, it is where the line shows in the viewer, as State's LineTop. The separators, the annotations and the room a split view leaves across from lines of the other side take their heights; unchanged lines collapsed into a separator take none, and are at its top. In a unified view, a line the new text deleted is among the deleted lines above its change, and an unchanged line of the old text where it is in the new. LineTop of a side's count of lines is the height of the whole diff, as a minimap scales it.
func (*DiffState) Run ¶ added in v0.5.0
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) ScrollY ¶ added in v0.8.0
ScrollY returns how far the diff's rows are scrolled up, in DIPs, as the last frame laid them out, however they were scrolled: by the wheel, the keys, the scroll bar, GoToHunk or SetScrollY. It is the new side's, which the old side of a split view shares, 0 for a viewer as high as its lines (FitContent). SetScrollY scrolls them, as far as they scroll, as a minimap beside the diff does when it is clicked or dragged.
func (*DiffState) SelectedLines ¶
func (d *DiffState) SelectedLines() (DiffLineRange, bool)
SelectedLines returns the lines selected by their numbers, and whether there are.
func (*DiffState) SetPatch ¶
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. Each hunk is highlighted on its own, from the start of its first line, as git diff colors it: a comment or string the hunk before ends in does not go on into it. A Language.Highlighter of the app's sees the texts whole.
func (*DiffState) SetScrollY ¶ added in v0.8.0
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) ViewportHeight ¶ added in v0.8.0
ViewportHeight returns the height of the part of the diff the viewer shows, in DIPs, as the last frame laid it out: from ScrollY to ScrollY plus ViewportHeight, against LineTop, is what is in view. A viewer as high as its lines (FitContent) is that high.
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 ¶
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.
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 (*FindBar) CaseSensitive ¶
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) InSelection ¶
func (*FindBar) Matches ¶
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) Query ¶
Query and Replacement are the texts of the bar's fields, to bind inputs to, with QueryInput and ReplacementInput.
func (*FindBar) QueryInput ¶
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) 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 (*FindBar) ReplacementInput ¶
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 ¶
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) SetReplacing ¶
type Folder ¶
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 ¶
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) Diagnostics ¶
func (h *HoverCard) Diagnostics() []Diagnostic
Diagnostics are the diagnostics of the text hovered.
type HoverRequest ¶
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 ¶
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 ¶
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
// Imports matches a line that imports, as one starting with import:
// a run of them folds as one, the lines in brackets of each with
// them, and State.FoldImports folds the first.
Imports *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.
//
// A patch's texts (DiffState.SetPatch) are its hunks' lines one after
// another: the default highlighter starts each hunk in state 0, as
// the start of a text, while a Highlighter sees one text.
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 ¶
LanguageFor returns the language of a file by its name, as "main.go" or "Makefile", or nil when MyGo knows none for it.
func LanguageNamed ¶
LanguageNamed returns the language MyGo 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.
type LineBackground ¶ added in v0.5.0
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.
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.
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 ¶
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 ¶
Len, LineCount and String return the length in bytes, the number of lines and the text of the snapshot.
func (Snapshot) LineStart ¶
LineStart and LineEnd return the bytes line i starts and ends at, before its newline.
func (Snapshot) Pos ¶
Pos returns the line and column of byte offset, and Offset the byte of a line and column.
type Snippet ¶ added in v0.8.0
type Snippet struct {
// contains filtered or unexported fields
}
Snippet is an immutable code template with numbered tab stops, parsed by ParseSnippet. It can be shared by completions and editor states. Its zero value is an empty template.
func ParseSnippet ¶ added in v0.8.0
ParseSnippet parses the tab-stop subset of TextMate/LSP snippets: $1 and ${1}, placeholders such as ${1:name}, and $0 for the final stop. Numbers are non-negative 32-bit integers. Stops are visited in numeric order, with 0 last (the end when omitted). References to the same number share its default and are edited together; empty stops at the same byte coalesce as ordinary carets do.
Escape $, } and backslash with a backslash. Defaults are plain text: nested placeholders, variables, choices and transformations return an error, as do conflicting defaults for the same number and invalid UTF-8. Text is inserted literally, with CRLF normalized to LF, without adjusting indentation. Parsing an unsupported server snippet lets the app offer a plain-text completion instead.
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
// KeepScrollbars keeps the thumbs of the scroll bars, and the marks
// of the carets on the vertical one, showing while the text has
// anywhere to scroll, rather than only while the pointer is over the
// editor or drags a thumb, as ui's KeepScrollbars does for a scroll
// container; they look the same either way.
// NoScrollbars takes the scroll bars away, with the marks of changes,
// matches and diagnostics on them, and their room, which goes to the
// text; the wheel, the keys and SetScrollY still scroll it.
KeepScrollbars bool
NoScrollbars 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)
// HoverDelay is how long the pointer rests on the text before the
// hover is asked for: a tooltip's, 600 ms, when zero or less.
HoverDelay time.Duration
// NoPointerHover shows no hover as the pointer rests, an app's nor a
// diagnostic's, as VS Code's editor.hover.enabled off: ShowHover, as
// Cmd+K Cmd+I, still asks for one at the caret.
NoPointerHover bool
// 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
// TextBackgrounds fill ranges of the text with colors, under the
// text and over line backgrounds, as the words a merge changed:
// across wrapped rows, tabs and wide characters as the editor lays
// them out, not the lines folds hide. As LineBackgrounds, they stay
// where they are as the text is edited: compute them again when the
// buffer's Version changes.
TextBackgrounds []TextBackground
// 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) Diagnostics ¶
func (st *State) Diagnostics() []Diagnostic
Diagnostics returns the diagnostics shown, where the edits since moved them.
func (*State) Find ¶
Find opens the find bar with query, and selects its first match after the caret.
func (*State) FindMatches ¶
FindMatches returns how many matches the find bar has, and which is chosen, from 0.
func (*State) Focused ¶
Focused reports whether the editor had the keyboard focus in the last frame.
func (*State) Fold ¶
Fold folds the lines indented under line, up to its closing bracket, or the run of imports it starts, as the gutter's marker does; Unfold unfolds them.
func (*State) FoldImports ¶ added in v0.6.4
func (st *State) FoldImports()
FoldImports folds the first run of imports of the text, or the first import alone by its brackets, as editors can on opening a file (Language's Imports).
func (*State) GoTo ¶
GoTo puts the caret at a line and column, from 0, and scrolls it to the middle of the editor.
func (*State) InsertSnippet ¶ added in v0.8.0
InsertSnippet replaces each selection with s and selects its first numbered placeholders. Tab and Shift+Tab visit stops; Escape, undo, an external buffer edit or moving outside the active fields ends the session. A new snippet replaces the session, rather than nesting it. Redo restores the insertion and its selections, without restarting a snippet session. It reports whether it inserted, and leaves a read-only editor unchanged. Call it on the UI thread, as other State methods.
func (*State) LineTop ¶ added in v0.7.0
LineTop returns the top of a line, from 0, in DIPs below the top of the first, as the last frame laid the lines out: less ScrollY, it is where the line shows in the editor. The lines a fold hides take no room, and LineTop of the count of lines is the height of them all. With SoftWrap, the lines of a long text far from the view may take the rows they are estimated to for a few frames, until they are measured.
func (*State) ScrollY ¶ added in v0.7.0
ScrollY returns how far the editor's lines are scrolled up, in DIPs, 0 for an editor as high as its lines (FitContent); SetScrollY scrolls them, as far as they scroll, as editors side by side scroll together.
func (*State) Select ¶
Select selects the text from start to end, a caret alone at end when they are equal.
func (*State) SelectedText ¶
SelectedText returns the text of the selections, joined by newlines.
func (*State) Selection ¶
Selection returns the newest selection, the one input methods and scrolling follow.
func (*State) Selections ¶
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 ¶
SetInlays shows inlay hints in the lines, as types and parameter names: they move with the edits until set again.
func (*State) SetScrollY ¶ added in v0.7.0
func (*State) SetSelections ¶
SetSelections sets the selections, the last the newest, and scrolls it into view.
func (*State) SetSuggestion ¶
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 ¶
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) ViewportHeight ¶ added in v0.8.0
ViewportHeight returns the height of the part of the text the editor shows, in DIPs, as the last frame laid it out: from ScrollY to ScrollY plus ViewportHeight, against LineTop, is what is in view, as a minimap beside the editor shows it. An editor as high as its lines (FitContent) is that high.
func (*State) VisibleLines ¶ added in v0.5.0
VisibleLines returns the first and the last line, from 0, that the last frame showed, those hidden by folds among them.
type SyntaxSelector ¶
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 TextBackground ¶ added in v0.7.0
TextBackground fills bytes Start to End of the text with Color. Ranges past the end of the text, as an edit leaves them until they are computed again, are cut to it; empty ones fill nothing. A range across lines fills the text of each, not past its end.
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 ¶
DefaultTheme returns the code theme for a window's theme: its background and text, with GitHub's colors for code.
func (*Theme) SeverityColor ¶
SeverityColor returns the color of diagnostics of a severity.
type Token ¶
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 ¶
TokenStyle is how a kind of token shows.
type Tokenizer ¶
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 ¶
TokenizerFunc is a function that is a Tokenizer.
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 )
Source Files
¶
- brackets.go
- buffer.go
- build.go
- commands.go
- difflayout.go
- diffmodel.go
- diffparts.go
- diffside.go
- diffview.go
- display.go
- doc.go
- edit.go
- editor.go
- find.go
- fold.go
- gitdiff.go
- input.go
- keymap.go
- languages.go
- lexer.go
- lexers.go
- lines.go
- lsp.go
- multicursor.go
- paint.go
- parts.go
- patch.go
- selection.go
- snippet.go
- state.go
- syntax.go
- theme.go
- view.go