editor 实验性
实验性
本包属于实验层:任何 0.x 版本都可能有不兼容变化(docs/release.md「API 稳定性」)。
import "github.com/tangoui/tango/ui/editor"本页由
site/tools/apigen从源码注释生成(按 darwin 构建标签选文件),请勿手改。
Package editor is the code editor. It follows Monaco's split between the text model and the editor:
- A Model is one document: its text, language, highlighter and undo history. Several editors can show the same Model (a split view); a ModelPool keeps one Model per URI.
- A State is one editor's view of a Model: its selections, viewport and Options. The application holds it and passes it to the View every frame. SaveViewState / RestoreViewState carry the per-editor state across model switches.
The Model and State parts of the package do not depend on package ui: they measure no text and draw nothing. The View sets the Viewport sizes it measured (line height, viewport and content widths) and passes caret x positions to RevealX; State turns keyboard-level intents (Move, Insert, Delete, Undo, Redo, ScrollBy) into Model edits, selection changes and scroll positions.
Offsets are UTF-8 byte offsets into the buffer's LF-normalised text (see package buffer). Caret movement by Char steps over grapheme clusters; see grapheme.go for the implemented subset of UAX #29.
Every edit, undo and redo is passed to the Model's Highlighter as edits (buffer.Buffer.LastChange for undo and redo), so it never has to re-tokenize the whole document after an undo.
Experimental: this package's API may change in any 0.x release (see docs/release.md, "API 稳定性").
常量
const (
CtxEditorFocus = "editorFocus"
CtxEditorTextFocus = "editorTextFocus"
CtxTextInputFocus = "textInputFocus"
CtxEditorReadonly = "editorReadonly"
CtxEditorHasSelection = "editorHasSelection"
CtxEditorHasMultipleSelections = "editorHasMultipleSelections"
CtxEditorLangID = "editorLangId"
CtxEditorTabMovesFocus = "editorTabMovesFocus"
CtxFoldingEnabled = "foldingEnabled"
CtxIsMac = "isMac"
CtxIsWindows = "isWindows"
CtxIsLinux = "isLinux"
)Built-in context keys, Monaco's names, for keybinding when clauses and command preconditions:
editorFocus the view has keyboard focus (and its window is active)
editorTextFocus same (the editor has no inner widgets yet)
textInputFocus same
editorReadonly edits are refused this frame
editorHasSelection some selection is not empty
editorHasMultipleSelections more than one selection (multiple cursors)
editorLangId the Model's language id ("go", "plaintext")
editorTabMovesFocus "Tab moves focus" mode (editor.action.toggleTabFocusMode)
foldingEnabled folding is on (Options.Folding, not a large file; folding.go)
isMac, isWindows, isLinux the keymap's platform
The application adds keys of its own with ViewW.Context; its function is asked first, so it may also override a built-in key.
const (
FoldingKindComment = "comment"
FoldingKindImports = "imports"
FoldingKindRegion = "region"
)Folding range kinds (Monaco's FoldingRangeKind values).
const (
MenuGroupNavigation = "navigation" // first (go to definition, ...)
MenuGroupModification = "1_modification" // edits of the text
MenuGroupCutCopyPaste = "9_cutcopypaste" // the clipboard
MenuGroupCommands = "z_commands" // the command palette
)Monaco's group names of the editor context menu.
const (
LargeFileSize = 20 * 1024 * 1024
LargeFileLines = 300 * 1000
)Large-file thresholds: Monaco 0.56's TextModel.LARGE_FILE_SIZE_THRESHOLD (20 MB) and LARGE_FILE_LINE_COUNT_THRESHOLD (300 000 lines), with largeFileOptimizations on (its default).
const DefaultFontSize = 14DefaultFontSize is the default Options.FontSize in logical pixels.
Monaco 0.56's fontSize default is platform dependent (12 on macOS, 14 elsewhere); the editor uses 14 everywhere so the layout is identical on every platform (milestone 1).
const DefaultOccurrencesHighlightDelay = 0DefaultOccurrencesHighlightDelay is DefaultOptions' OccurrencesHighlightDelay, in milliseconds.
const DefaultTabSize = 4DefaultTabSize is a new Model's tab size (Monaco's tabSize default).
const DefaultWordWrapColumn = 80DefaultWordWrapColumn is Monaco's wordWrapColumn default.
const MenuEditorContext = "EditorContext"MenuEditorContext is the editor's context menu (Monaco's MenuId.EditorContext), for RegisterMenuItem.
const PlainText = "plaintext"PlainText is the language of a Model whose URI matches no language.
函数
func DefaultRegistry
func DefaultRegistry() *monarch.RegistryDefaultRegistry returns the process-wide grammar registry NewState uses (all built-in languages). Grammars added to it (plugins) are seen by Models created afterwards; existing Models must Reset their Highlighter with the new Lexer (see monarch.Registry.Add) or SetLanguage again.
func GuessIndentation
func GuessIndentation(snap buffer.Snapshot, defaultTabSize int, defaultInsertSpaces bool) (tabSize int, insertSpaces bool)GuessIndentation guesses the tab size and whether the document indents with spaces from the indentation of its first 10000 lines, as Monaco 0.56's guessIndentation: lines indented with tabs against lines indented with two or more spaces decide insertSpaces (a tie keeps defaultInsertSpaces); with spaces, the most frequent difference in spaces between consecutive non-blank lines among 2, 4, 6, 8, 3, 5, 7 (in that order of preference) is the tab size, with 2 winning over 4 when it occurs at least 2/3 as often. Indentation that looks like alignment (a continuation under a line ending in a comma) is ignored unless its width is defaultTabSize and defaultInsertSpaces is set. With tabs, or nothing to go by, the defaults are returned.
Only the indentation of each line is read (plus, for the alignment check, a few characters of the previous line) through a bounded window, so a long line costs about as much as a short one (at most one window of a few KB; see guessWindow), not its length.
func ModelLines
func ModelLines(src *Model, from, to int, decos []Decoration) (paintFn func(*paint.List, ZonePaint), version uint64)ModelLines returns a view zone Paint drawing the lines [from, to) of src (clamped to its text) one per row, unwrapped, with src's syntax colors and the zone's theme, plus the Background, Border and Inline styles of decos (offsets of src's current text; the other options are not drawn), scrolling with the text. version is the drawing's ViewZone.Version for the current text, decorations and highlighting (it changes with them); it is 0 while the lines' tokens are not final, so the editor fingerprints the drawing until they are. Call it again after src changes. A line longer than 2000 characters is drawn up to there.
Experimental: part of the diff view's editor API (docs/specs/diff-view.md).
func RegisterCommand
func RegisterCommand(cmd Command)RegisterCommand adds cmd to the global command table, replacing a command with the same ID (as VS Code's CommandsRegistry: the last registration wins). It panics when the ID or Run is missing or the Precondition does not parse: those are programming errors.
func RegisterMenuItem
func RegisterMenuItem(menu string, item MenuItem)RegisterMenuItem adds item to the global menu named menu (MenuEditorContext for the editor's context menu), after the items already there (Monaco's MenuRegistry.appendMenuItem). It panics when the item has neither a command nor a submenu, or a When does not parse: those are programming errors. Items a view adds for itself go through ViewW.MenuItems.
func SetSystemLocales
func SetSystemLocales(os, ui []string)SetSystemLocales sets the locales "_os" (the system's) and "_vscode" (the user interface's) stand for in UnicodeHighlightOptions.AllowedLocales, as BCP 47 names Monaco's data is keyed by ("de", "pt-BR", "zh-hans"; matched exactly). A nil slice restores that name's default: for os the locale of $LC_ALL, $LC_MESSAGES or $LANG, for ui "en". The host calls it at startup; it is safe to call from any goroutine, and views drawn afterwards use the new tables.
func SetZoomLevel
func SetZoomLevel(z float64)SetZoomLevel sets the editor zoom level, clamped to [-5, 20]. Views apply it from their next frame; the application redraws the windows that show editors other than the one that changed it.
func ZoomLevel
func ZoomLevel() float64ZoomLevel returns the editor zoom level (0 by default).
类型
AutoClosingEditStrategy
type AutoClosingEditStrategy stringAutoClosingEditStrategy is when typing over or deleting an auto-closed character acts on the pair (Monaco's EditorAutoClosingEditStrategy).
const (
// AutoClosingEditAlways acts on any matching pair.
AutoClosingEditAlways AutoClosingEditStrategy = "always"
// AutoClosingEditAuto acts only on characters the editor auto-closed,
// while the caret stays between the pair.
AutoClosingEditAuto AutoClosingEditStrategy = "auto"
// AutoClosingEditNever never acts on the pair.
AutoClosingEditNever AutoClosingEditStrategy = "never"
)AutoClosingStrategy
type AutoClosingStrategy stringAutoClosingStrategy is when a pair is auto-closed (Monaco's EditorAutoClosingStrategy).
const (
// AutoCloseAlways closes the pair wherever the caret is.
AutoCloseAlways AutoClosingStrategy = "always"
// AutoCloseLanguageDefined closes the pair when the character after
// the caret is one of the language's autoCloseBefore characters (or a
// closing bracket), and not in the tokens its notIn lists.
AutoCloseLanguageDefined AutoClosingStrategy = "languageDefined"
// AutoCloseBeforeWhitespace closes the pair when a blank or the line
// end follows the caret.
AutoCloseBeforeWhitespace AutoClosingStrategy = "beforeWhitespace"
// AutoCloseNever never closes the pair.
AutoCloseNever AutoClosingStrategy = "never"
)AutoIndentStrategy
type AutoIndentStrategy stringAutoIndentStrategy is how much the editor adjusts the indentation (Monaco's autoIndent option, EditorAutoIndentStrategy).
const (
// AutoIndentNone: Enter inserts a bare line break.
AutoIndentNone AutoIndentStrategy = "none"
// AutoIndentKeep: Enter keeps the current line's indentation.
AutoIndentKeep AutoIndentStrategy = "keep"
// AutoIndentBrackets: also indents after an opening bracket and
// splits a bracket pair over three lines.
AutoIndentBrackets AutoIndentStrategy = "brackets"
// AutoIndentAdvanced: also applies the language's onEnter rules.
AutoIndentAdvanced AutoIndentStrategy = "advanced"
// AutoIndentFull: also applies the language's indentation rules on
// Enter, on typing, on Tab in a blank line and when moving lines.
AutoIndentFull AutoIndentStrategy = "full"
)AutoSurroundStrategy
type AutoSurroundStrategy stringAutoSurroundStrategy is which characters typed over a selection wrap it (Monaco's EditorAutoSurroundStrategy).
const (
// AutoSurroundLanguageDefined wraps with the language's surrounding
// pairs, brackets and quotes.
AutoSurroundLanguageDefined AutoSurroundStrategy = "languageDefined"
// AutoSurroundQuotes wraps with quotes only.
AutoSurroundQuotes AutoSurroundStrategy = "quotes"
// AutoSurroundBrackets wraps with brackets only.
AutoSurroundBrackets AutoSurroundStrategy = "brackets"
// AutoSurroundNever never wraps.
AutoSurroundNever AutoSurroundStrategy = "never"
)BracketGuideMode
type BracketGuideMode stringBracketGuideMode is which bracket pairs get guides (Monaco's guides.bracketPairs and guides.bracketPairsHorizontal: true, "active", false).
const (
// BracketGuidesOff draws none.
BracketGuidesOff BracketGuideMode = "false"
// BracketGuidesOn draws them for every pair.
BracketGuidesOn BracketGuideMode = "true"
// BracketGuidesActive draws them for the primary caret's pair only.
BracketGuidesActive BracketGuideMode = "active"
)Command
type Command struct {
// ID is the command's identifier, Monaco's command id where Monaco has
// the command.
ID string
// Label is the title shown in the command palette and menus.
Label string
// Precondition is a when expression (package when) over the editor's
// context keys (see contextkeys.go) that must hold for the command to
// run; empty means always.
Precondition string
// Mutates marks a command that edits the text: it is refused while the
// view is read-only.
Mutates bool
// Run runs the command with the arguments of the keybinding rule (or
// the caller of Execute) and reports whether it did something.
Run func(st *State, args any) bool
}Command is an editor command: something a keybinding, a menu or the command palette runs on a State by ID (State.Execute). IDs are Monaco's ("cursorWordLeft", "editor.action.selectAll").
func Commands
func Commands() []CommandCommands returns the registered commands sorted by ID (for the command palette).
func LookupCommand
func LookupCommand(id string) (Command, bool)LookupCommand returns the registered command id.
CommentsOptions
type CommentsOptions struct {
// InsertSpace puts a space after a line comment token and inside the
// tokens of a block comment (comments.insertSpace: true).
InsertSpace bool
// IgnoreEmptyLines leaves blank lines alone when toggling, adding or
// removing line comments over several lines (comments.ignoreEmptyLines:
// true).
IgnoreEmptyLines bool
}CommentsOptions are the settings of the comment commands (Monaco's comments option).
Decoration
type Decoration struct {
Start, End int
Options *DecorationOptions
}Decoration is a decorated range: UTF-8 byte offsets [Start, End) of the text, and how it is drawn.
Experimental: part of the decorations API (docs/specs/diff-view.md).
func DecorationFromLSP
func DecorationFromLSP(snap buffer.Snapshot, startLine, startUTF16, endLine, endUTF16 int, o *DecorationOptions) DecorationDecorationFromLSP returns the decoration of an LSP range: zero-based lines and UTF-16 columns of snap (clamped to the text).
Experimental: part of the decorations API (docs/specs/diff-view.md).
func LineDecoration
func LineDecoration(snap buffer.Snapshot, first, last int, o *DecorationOptions) DecorationLineDecoration returns a decoration of the lines first..last of snap (clamped): from the start of first to the end of last (not the start of the next line, which a WholeLine decoration would include).
Experimental: part of the decorations API (docs/specs/diff-view.md).
DecorationOptions
type DecorationOptions struct {
// Description names the decoration for debugging and screen readers.
Description string
// Stickiness is what the ends do when text is typed at them.
Stickiness Stickiness
// ZIndex orders overlapping decorations: higher ones are drawn later
// (over the lower ones). Ties are ordered by owner name, then by the
// position in the owner's list.
ZIndex int
// WholeLine draws Background (and Border) across the text area on
// every line the range touches, from the line of Start to the line of
// End (Monaco's isWholeLine; a range ending at the start of a line
// includes that line).
WholeLine bool
// ShowIfCollapsed draws an empty range (on its line: whole-line
// background, margin, line number and overview marks); without it an
// empty range is not drawn at all.
ShowIfCollapsed bool
// Background fills the range's characters (Monaco's className), or
// with WholeLine its lines. Transparent: none.
Background color.NRGBA
// Border strokes a one pixel border inside each filled box.
Border color.NRGBA
// Squiggle draws a wavy diagnostic underline across the visible text
// of the range. Transparent disables it. Empty ranges have no underline.
Squiggle color.NRGBA
// Inline changes how the range's glyphs are drawn without changing
// their layout (Monaco's inlineClassName); nil: no change.
Inline *InlineStyle
// Gutter is a mark in the gutter's line decorations margin on every
// line of the range (Monaco's linesDecorationsClassName); nil: none.
Gutter *GutterMark
// MarginBackground fills the whole gutter on the range's lines
// (Monaco's marginClassName). Transparent: none.
MarginBackground color.NRGBA
// LineNumberColor is the color of the line numbers of the range's
// lines (Monaco's lineNumberClassName). Transparent: unchanged.
LineNumberColor color.NRGBA
// Overview marks the range's lines on the overview ruler; nil: none.
Overview *OverviewStyle
}DecorationOptions is how a decoration is drawn: a subset of Monaco's IModelDecorationOptions. One *DecorationOptions may be shared by many decorations (Monaco's ModelDecorationOptions.register); do not change it after passing it to SetDecorations (the editor copies it then, so a later change is not seen until it is set again).
Experimental: part of the decorations API (docs/specs/diff-view.md).
Direction
type Direction intDirection is the direction of a Move or Delete. For the vertical units (Line, Page) Backward is up and Forward is down.
const (
Backward Direction = iota
Forward
)FoldingRange
type FoldingRange struct {
Start, End int
// Kind is FoldingKindComment, FoldingKindImports, FoldingKindRegion or
// "" (Monaco's FoldingRangeKind). The built-in strategy leaves it ""
// (as Monaco's indentation provider), so editor.foldAllBlockComments
// and editor.foldAllMarkerRegions then find their ranges by the text
// of the start line.
Kind string
}FoldingRange is a foldable span of model lines: Start is shown, Start+1 .. End are hidden when it is folded. Lines are 0-based and inclusive.
FoldingRangeProvider
type FoldingRangeProvider interface {
FoldingRanges(ctx context.Context, snap buffer.Snapshot) ([]FoldingRange, error)
}FoldingRangeProvider computes the folding ranges of a document (Monaco's FoldingRangeProvider). The editor calls it on the UI goroutine when the ranges of a new text version are first needed (a fold command, the gutter's folding controls), so it must answer quickly: a provider backed by a slow service answers from its last result. Ranges may come in any order; ranges outside the document, of a single line, starting on the same line as an earlier one or crossing an enclosing one are dropped. An error, or nil ranges, falls back to the built-in strategy (as Monaco does when every provider returns null).
FoldingStrategy
type FoldingStrategy stringFoldingStrategy is how folding ranges are computed (Monaco's foldingStrategy option).
const (
// FoldingAuto uses the registered FoldingRangeProvider, else the
// indentation.
FoldingAuto FoldingStrategy = "auto"
// FoldingIndentation always uses the indentation (and the language's
// folding markers).
FoldingIndentation FoldingStrategy = "indentation"
)GuidesOptions
type GuidesOptions struct {
// Indentation draws a vertical line at each indentation level
// (guides.indentation: true).
Indentation bool
// HighlightActiveIndentation draws the guide of the primary caret's
// block with editorIndentGuide.activeBackground
// (guides.highlightActiveIndentation: true).
HighlightActiveIndentation bool
// BracketPairs draws bracket pair guides (guides.bracketPairs:
// false): a vertical line from each bracket pair's opening line to its
// closing line, for every pair or only the primary caret's
// (bracketguides.go). "" is BracketGuidesOff.
BracketPairs BracketGuideMode
// BracketPairsHorizontal draws, with the bracket pair guides, the
// horizontal lines to the brackets (guides.bracketPairsHorizontal:
// "active"). "" is BracketGuidesOff.
BracketPairsHorizontal BracketGuideMode
// HighlightActiveBracketPair draws the guides of the primary caret's
// pair in editorBracketPairGuide.activeBackground
// (guides.highlightActiveBracketPair: true).
HighlightActiveBracketPair bool
}GuidesOptions are the guide lines drawn in the text (Monaco's guides).
GutterClick
type GutterClick struct {
Line int
Position geom.Point
Button input.Button
}GutterClick reports a zero-based document Line and the pointer Position in UI logical coordinates. Button is ButtonLeft or ButtonRight.
GutterMark
type GutterMark struct {
// GlyphMargin places the mark in the separate glyph lane, when enabled.
GlyphMargin bool
// Background fills the margin's cell.
Background color.NRGBA
// Bar is a 3 pixel bar at the cell's left edge (a change bar).
Bar color.NRGBA
// Sign is one or two characters centred in the cell on the line's
// first row (a diff's "+" or "−"), drawn in SignColor.
Sign string
SignColor color.NRGBA
}GutterMark is a decoration's mark in the gutter's line decorations margin between the line numbers (or folding controls) and the text.
Experimental: part of the decorations API (docs/specs/diff-view.md).
InlayHint
type InlayHint struct {
Offset int
Text string
Foreground color.NRGBA
Background color.NRGBA
}InlayHint inserts a visual label before a UTF-8 byte Offset in the document. The offset may be at a line end. Equal offsets retain input order. A transparent Foreground uses the editor's subdued foreground.
InlineStyle
type InlineStyle struct {
// Color replaces the token color (transparent: unchanged).
Color color.NRGBA
// Underline and Strikethrough draw a line under or through the glyphs.
Underline, Strikethrough bool
// Opacity multiplies the glyphs' alpha (0: unchanged).
Opacity float32
}InlineStyle changes how glyphs are drawn without changing their layout (no bold or italic: those change the shaping).
Experimental: part of the decorations API (docs/specs/diff-view.md).
InsideWordArgs
type InsideWordArgs struct{ OnlyWord bool }InsideWordArgs are the arguments of deleteInsideWord (Monaco's {onlyWord}): OnlyWord leaves the blanks around the word.
LineNumberFunc
type LineNumberFunc func(line int) (label string, ok bool)LineNumberFunc returns the line number label of model line line (zero-based); ok false (or an empty label) shows none.
Experimental: part of the diff view's editor API (docs/specs/diff-view.md).
LineNumbersMode
type LineNumbersMode stringLineNumbersMode is how the gutter shows line numbers (Monaco's lineNumbers option).
const (
// LineNumbersOn shows absolute line numbers.
LineNumbersOn LineNumbersMode = "on"
// LineNumbersOff hides the line numbers.
LineNumbersOff LineNumbersMode = "off"
// LineNumbersRelative shows each line's distance to the primary
// caret's line, and that line's own number (left aligned).
LineNumbersRelative LineNumbersMode = "relative"
// LineNumbersInterval shows the numbers of every tenth line, of the
// last line and of the primary caret's line.
LineNumbersInterval LineNumbersMode = "interval"
)LineRange
type LineRange struct{ Start, End int }LineRange is the model lines [Start, End) (zero-based, half open), as diff.LineRange.
Experimental: part of the hidden areas API (docs/specs/diff-view.md).
LocaleSet
type LocaleSet struct {
// contains filtered or unexported fields
}LocaleSet is the set of locale names of UnicodeHighlightOptions.AllowedLocales (Monaco's allowedLocales record: the names whose value is true). The zero value is Monaco's default {"_os": true, "_vscode": true}; AllowLocales() with no names is the empty set (the _default table). LocaleSets compare with ==, so Options stays comparable.
func AllowLocales
func AllowLocales(names ...string) LocaleSetAllowLocales returns the set of the names (Monaco's allowedLocales with each name true).
func LocaleSetOf
func LocaleSetOf(m map[string]bool) LocaleSetLocaleSetOf returns the set of the names m maps to true, as Monaco validates allowedLocales; nil is the default set.
func (LocaleSet) IsDefault
func (s LocaleSet) IsDefault() boolIsDefault reports whether s is the default set {"_os", "_vscode"}.
func (LocaleSet) Names
func (s LocaleSet) Names() []stringNames returns the names of s, sorted.
MatchBracketsMode
type MatchBracketsMode stringMatchBracketsMode is when the brackets around the caret are highlighted (Monaco's matchBrackets).
const (
// MatchBracketsAlways highlights the pair a caret touches, else the
// pair enclosing it.
MatchBracketsAlways MatchBracketsMode = "always"
// MatchBracketsNear highlights only the pair a caret touches.
MatchBracketsNear MatchBracketsMode = "near"
// MatchBracketsNever highlights no brackets.
MatchBracketsNever MatchBracketsMode = "never"
)MenuItem
type MenuItem struct {
// Command is the ID of the registered command the item runs. An item
// whose command is not registered is not shown. Ignored when Submenu
// is set.
Command string
// Label is the text shown; empty means the command's Label (its ID
// when that is empty too).
Label string
// Group places the item: items are sorted by group ("navigation"
// first, "" last, the others by name) with a separator between the
// groups (Monaco's group, e.g. "9_cutcopypaste").
Group string
// Order sorts the items of a group (Monaco's order; then by label).
Order float64
// When is a when expression (package when) over the view's context
// keys that must hold for the item to be shown; empty means always.
When string
// Args are the arguments the command runs with.
Args any
// Submenu makes the item a submenu of these items (sorted and grouped
// the same way); it is shown when one of them is.
Submenu []MenuItem
}MenuItem is an item of a menu (Monaco's IMenuItem / ISubmenuItem): a command, or a submenu of further items.
MinimapOptions
type MinimapOptions struct {
Enabled bool // minimap.enabled: true
Side MinimapSide // minimap.side: "right"
Size MinimapSize // minimap.size: "proportional"
MaxColumn int // minimap.maxColumn: 120
RenderCharacters bool // minimap.renderCharacters: true (false: blocks)
ShowSlider MinimapShowSlider // minimap.showSlider: "mouseover"
}MinimapOptions configures minimap. RenderCharacters (default true) draws Monaco's minimap character shapes (minimap_chars.go); off, each character is a token-colored block.
MinimapShowSlider
type MinimapShowSlider stringMinimapShowSlider is minimap.showSlider ("mouseover" by default).
const (
MinimapSliderMouseOver MinimapShowSlider = "mouseover"
MinimapSliderAlways MinimapShowSlider = "always"
)MinimapSide
type MinimapSide stringMinimapSide is minimap.side ("right" by default).
const (
MinimapRight MinimapSide = "right"
MinimapLeft MinimapSide = "left"
)MinimapSize
type MinimapSize stringMinimapSize is minimap.size ("proportional" by default).
const (
MinimapProportional MinimapSize = "proportional"
MinimapFit MinimapSize = "fit"
MinimapFill MinimapSize = "fill"
)Model
type Model struct {
// contains filtered or unexported fields
}Model is one document: its text and undo history (a buffer.Buffer), its language and configuration, and the Highlighter all the views of the document share. Create one with NewModel or ModelPool.Open and show it with NewView. Like State it is not safe for concurrent use; drive it from the UI goroutine (its Highlighter is itself safe for its background goroutine).
The application owns the Highlighter's background goroutine (highlight.Highlighter.Start): it starts it once, when Highlighter first returns non-nil, and cancels its context when the Model goes away (for a pooled Model, in ModelPool.OnWillDispose). The Model keeps that one Highlighter for its whole life, across SetLanguage, so the goroutine stays valid. A Model that starts as plain text has a nil Highlighter until SetLanguage switches it to a language with a grammar: start the goroutine from the callback that reports that switch, ModelPool.OnLanguageChange for a pooled Model, or a Subscribe callback receiving a ModelChange with Language set otherwise (check Highlighter() != nil there, and start it only once).
The text changes only through the views (State's Insert, Delete, Edit, Undo and Redo) and SetEOL: a direct Buffer().Edit, Undo or Redo bypasses the Highlighter (which then re-tokenizes the whole document), the subscribers and the mapping of the views' selections.
func NewModel
func NewModel(uri, text string, reg *monarch.Registry) *ModelNewModel returns a Model holding text, with the language chosen from the file name in uri (langs.ForFilename; for a URI with a scheme, such as "file:///src/main.go", its path) and grammars from reg. An unknown language is PlainText; a language without a Monarch grammar, or a nil reg, shows no highlighting (Highlighter returns nil). It is NewModelWithOptions with DefaultModelOptions, so the indentation is detected from text.
func NewModelWithOptions
func NewModelWithOptions(uri, text string, reg *monarch.Registry, o ModelOptions) *ModelNewModelWithOptions is NewModel with the creation options o.
func (*Model) Buffer
func (m *Model) Buffer() *buffer.BufferBuffer returns the text and undo history. Read it freely (Snapshot, AltVersion, Anchor/Resolve, PushUndoStop); change the text only through the views and SetEOL (see Model).
func (*Model) Conf
func (m *Model) Conf() *langs.ConfConf returns the language configuration, nil for plain text.
func (*Model) Decorations
func (m *Model) Decorations(owner string) []DecorationDecorations returns owner's current decorations (moved with the edits since they were set), in the order they were set: an index is a stable ID within the owner. Nil when the owner has none.
Experimental: part of the decorations API (docs/specs/diff-view.md).
func (*Model) DecorationsIn
func (m *Model) DecorationsIn(start, end int, dst []Decoration) []DecorationDecorationsIn appends to dst the Model-wide decorations (of every owner, not those of a single view: State.SetDecorations) intersecting or touching the offsets [start, end], sorted by Start. O(log D + k).
Experimental: part of the decorations API (docs/specs/diff-view.md).
func (*Model) DetectIndentation
func (m *Model) DetectIndentation()DetectIndentation sets the tab size and InsertSpaces from the current text (GuessIndentation), falling back to the creation options' values (Monaco's TextModel.detectIndentation as editor.action.detectIndentation calls it). It is the editor.action.detectIndentation command.
The fallback values are fixed when the Model is created; Monaco's command reads the current creation options from the configuration for the model's language and URI (modelService.getCreationOptions) each time. An application that changes its defaults later sets the tab size and insertSpaces itself.
func (*Model) DroppedEdits
func (m *Model) DroppedEdits() uint64DroppedEdits counts queued edits rejected after rebasing (for example, overlapping replacements). Like Model it must be read on the UI thread.
func (*Model) EOL
func (m *Model) EOL() stringEOL returns the line ending the document is saved with, "\n" or "\r\n" (see buffer.Snapshot.TextWithEOL).
func (*Model) Highlighter
func (m *Model) Highlighter() *highlight.HighlighterHighlighter returns the Highlighter, nil while the language has no grammar (plain text; milestone 1's contract). The views call Highlight and Tokens on it; the application may Start its background goroutine (see Model). The Model has one Highlighter for its whole life: SetLanguage Resets it with the new grammar (with none for plain text, when this returns nil but the instance and its goroutine live on), so a language round trip returns the same, still started, Highlighter.
func (*Model) InsertSpaces
func (m *Model) InsertSpaces() boolInsertSpaces reports whether Tab and the indentation commands indent with spaces rather than tab characters (Monaco's model option insertSpaces; detected or from ModelOptions for a new Model).
func (*Model) Language
func (m *Model) Language() stringLanguage returns the language id, PlainText when none.
func (*Model) LargeFile
func (m *Model) LargeFile() boolLargeFile reports whether the text was larger than LargeFileSize bytes or LargeFileLines lines when the Model was created (Monaco's isTooLargeForTokenization, decided once at creation as there). A large file has no folding (Monaco gives such models no hidden areas); unlike Monaco, syntax highlighting stays on. The size counts UTF-8 bytes where Monaco counts UTF-16 code units, so text outside ASCII reaches it sooner.
func (*Model) SetDecorations
func (m *Model) SetDecorations(owner string, ds []Decoration)SetDecorations replaces owner's decorations, shown in every view of the Model; no decorations remove the owner. The ranges are offsets of the current text: they are copied, ordered (an End before Start is swapped), clamped to the text and widened to whole characters, and from then on move with every edit, undo and redo (by their Options' Stickiness; a range whose text is deleted collapses). Decorations are not part of the undo history: an undo moves them as any edit does. O(D + n log n) for n decorations among D. Called from the UI goroutine, like every Model method; the views draw the change from their next frame.
Experimental: part of the decorations API (docs/specs/diff-view.md).
func (*Model) SetEOL
func (m *Model) SetEOL(eol string)SetEOL sets the line ending, "\n" or "\r\n", as an undo step of its own (Monaco's pushEOL); anything else, or the current ending, does nothing. Called from a subscriber, it runs after the notification (see Subscribe).
func (*Model) SetInsertSpaces
func (m *Model) SetInsertSpaces(on bool)SetInsertSpaces sets InsertSpaces (Monaco's updateOptions({insertSpaces})); editor.action.indentationToSpaces / ToTabs set it too.
func (*Model) SetLanguage
func (m *Model) SetLanguage(id string)SetLanguage switches to language id (a built-in language id such as "go"; anything else is PlainText): the configuration, the word pattern and the Highlighter follow, every line is re-tokenized, and subscribers and the pool's OnLanguageChange listeners are told. Setting the current language refreshes a replaced registry grammar, but does nothing when its lexer is unchanged. The Highlighter instance (and its once-started worker) is retained. Called from a subscriber, it runs after the notification.
func (*Model) SetTabSize
func (m *Model) SetTabSize(n int)SetTabSize sets the tab width (Monaco's updateOptions({tabSize})); n <= 0 means DefaultTabSize. Views see it from their next command or frame.
func (*Model) Snapshot
func (m *Model) Snapshot() buffer.SnapshotSnapshot returns the current text.
func (*Model) Subscribe
func (m *Model) Subscribe(fn func(ModelChange)) (cancel func())Subscribe calls fn after every change of the Model, synchronously, until cancel is called. Listeners run in subscription order; they may cancel themselves or subscribe others (seen from the next change).
A listener may change the Model (edit through a view, Undo, Redo, SetEOL, SetLanguage): the change is queued and applied once every listener has seen the current change, so all of them, and every view's selection, see the changes in one order. Queued changes run first in, first out; an edit's offsets (in the text the listener saw) are mapped through the queued changes applied before it, and an edit that no longer applies is dropped. Changes requested while the queue is applied are queued behind it.
func (*Model) TabSize
func (m *Model) TabSize() intTabSize returns the document's tab width in columns (Monaco's model option tabSize; detected or from ModelOptions for a new Model). Every view of the Model uses it for tab stops, Tab, outdent and re-indenting; a View's TabSize modifier overrides it for drawing and caret movement for one frame.
func (*Model) URI
func (m *Model) URI() stringURI returns the Model's URI (the file name for NewState's private model).
ModelChange
type ModelChange struct {
// Old and New are the snapshots before and after the change.
Old, New buffer.Snapshot
// Edits turn Old into New (sorted, non-overlapping, in Old's
// offsets, as buffer.Buffer.Edit takes them). Empty for language and
// EOL changes.
Edits []buffer.Edit
// Source is the view that made the edit; for undo and redo, the view
// that ran them. Nil for changes made on the Model itself (SetEOL,
// SetLanguage).
Source *State
// Undo and Redo mark undo and redo; Language a SetLanguage (Old and
// New are then the same snapshot); EOL a SetEOL or the undo or redo of
// one.
// OldLanguage and NewLanguage are set for a language notification,
// including a same-language grammar refresh.
OldLanguage, NewLanguage string
Undo, Redo, Language, EOL bool
}ModelChange describes one change of a Model, passed to its subscribers synchronously, after the change (Model.Snapshot is New).
ModelOptions
type ModelOptions struct {
// TabSize is the tab width (tabSize: 4); values <= 0 mean
// DefaultTabSize (and leave DetectIndentation as it is: the zero
// ModelOptions is tab size 4, tabs, no detection, unlike a ModelPool's
// zero Options). With DetectIndentation it is the fallback when the
// text does not tell.
TabSize int
// InsertSpaces is whether to indent with spaces (insertSpaces: true);
// the fallback likewise.
InsertSpaces bool
// DetectIndentation sets the tab size and insertSpaces from the text
// when the Model is created (detectIndentation: true; see
// GuessIndentation). Only creation and editor.action.detectIndentation
// detect: SetTabSize and SetInsertSpaces are never overridden later.
DetectIndentation bool
}ModelOptions are a Model's creation options (Monaco's ITextModelCreationOptions): the tab size and insertSpaces it starts with, and whether to detect them from the text instead.
func DefaultModelOptions
func DefaultModelOptions() ModelOptionsDefaultModelOptions returns Monaco 0.56's defaults: tab size 4, insertSpaces and detectIndentation on.
ModelPool
type ModelPool struct {
// Options are the creation options of the Models Open creates (see
// NewModelWithOptions). The zero value means DefaultModelOptions
// (detection on), so "tab size 4, tabs, no detection" cannot be
// written as the zero value: give the TabSize, as in
// ModelOptions{TabSize: 4}. A non-zero Options with TabSize 0 means
// tab size 4 with DetectIndentation as given (a zero TabSize does not
// turn detection on).
Options ModelOptions
// contains filtered or unexported fields
}ModelPool keeps one Model per URI, reference counted, so the editors showing the same document share its Model (Monaco's model service). Like Model it is not safe for concurrent use.
func NewModelPool
func NewModelPool(reg *monarch.Registry) *ModelPoolNewModelPool returns an empty pool whose Models take grammars from reg (see NewModel).
func (*ModelPool) Get
func (p *ModelPool) Get(uri string) *ModelGet returns the open Model for uri, or nil. It adds no reference.
func (*ModelPool) OnCreate
func (p *ModelPool) OnCreate(fn func(*Model)) (cancel func())OnCreate calls fn with every Model the pool creates (Monaco's onDidCreateModel).
func (*ModelPool) OnLanguageChange
func (p *ModelPool) OnLanguageChange(fn func(m *Model, old string)) (cancel func())OnLanguageChange calls fn after a pooled Model's SetLanguage, with the previous language id (Monaco's onDidChangeModelLanguage).
func (*ModelPool) OnWillDispose
func (p *ModelPool) OnWillDispose(fn func(*Model)) (cancel func())OnWillDispose calls fn with every Model about to leave the pool, while it is still usable (Monaco's onWillDisposeModel). This is where the application cancels the Model's highlighting goroutine.
func (*ModelPool) Open
func (p *ModelPool) Open(uri, text string) *ModelOpen returns the Model for uri, adding one reference. The first Open creates it from text with Options (see NewModelWithOptions) and tells the OnCreate listeners; a later Open returns the same Model and ignores text (and does not detect again). An Open of a URI whose Model is being disposed (from an OnWillDispose listener) creates a fresh Model from text, which replaces the dying one in the pool.
func (*ModelPool) Release
func (p *ModelPool) Release(m *Model)Release drops one reference to m (as returned by Open). When the last one goes, the OnWillDispose listeners are told (Get still returns m while they run), then m leaves the pool and its subscribers are dropped (States showing it stay valid to Close); a later Open of its URI creates a new Model. Releasing a Model the pool does not hold, or one being disposed, does nothing.
The application stops the Highlighter's background goroutine it started for m (see Model) in an OnWillDispose listener.
MultiCursorPasteMode
type MultiCursorPasteMode stringMultiCursorPasteMode is how pasted text is shared among several cursors (Monaco's multiCursorPaste option).
const (
// MultiCursorPasteSpread gives each cursor one line of the text when
// the text has as many lines as there are cursors.
MultiCursorPasteSpread MultiCursorPasteMode = "spread"
// MultiCursorPasteFull pastes the whole text at every cursor (unless
// it was copied from as many selections).
MultiCursorPasteFull MultiCursorPasteMode = "full"
)OccurrencesHighlightMode
type OccurrencesHighlightMode stringOccurrencesHighlightMode is where the occurrences of the word at the caret are highlighted (Monaco's occurrencesHighlight).
const (
// OccurrencesOff highlights nothing.
OccurrencesOff OccurrencesHighlightMode = "off"
// OccurrencesSingleFile highlights the occurrences in the document.
OccurrencesSingleFile OccurrencesHighlightMode = "singleFile"
// OccurrencesMultiFile is Monaco's experimental cross-document mode;
// the View treats it as OccurrencesSingleFile.
OccurrencesMultiFile OccurrencesHighlightMode = "multiFile"
)Options
type Options struct {
// FontSize is the font size in logical pixels (fontSize; see
// DefaultFontSize). Values <= 0 mean DefaultFontSize.
FontSize float32
// FontFamily selects the document font, with the default monospace fallback.
FontFamily string
// LineHeight specifies a row height in logical pixels before editor zoom.
// Non-positive values use the height derived from FontSize.
LineHeight float32
// CursorWidth specifies the insertion caret width in logical pixels.
// Non-positive values use the default 2 px.
CursorWidth float32
// ReadOnly refuses edits: every command marked Mutates (typing,
// deleting, Enter, Tab, paste, undo, redo, the line commands ...), the
// IME, the deletion of cut and dragging text; the caret, selection,
// navigation and copy keep working, and the context key
// editorReadonly is true (readOnly: false).
ReadOnly bool
// LineNumbers is how the gutter shows line numbers (lineNumbers:
// "on"); unset or unknown values are "on".
LineNumbers LineNumbersMode
// LineNumbersMinChars reserves at least this many digit widths. Zero
// uses the Monaco default of 5.
LineNumbersMinChars int
// LineDecorationsWidth specifies the logical pixel width of the line
// decorations lane, exclusive of folding controls. Zero uses 10 px.
LineDecorationsWidth float32
// GlyphMargin reserves a separate line-height-wide lane to the left of
// line numbers, for marks such as breakpoints.
GlyphMargin bool
// NoScrollBeyondLastLine stops vertical scrolling at the document's
// bottom padding instead of permitting the last row at the top.
NoScrollBeyondLastLine bool
// Comments are the settings of the comment commands (comments).
Comments CommentsOptions
// AutoClosingBrackets is when typing an opening bracket also inserts
// its closing bracket (autoClosingBrackets: "languageDefined").
AutoClosingBrackets AutoClosingStrategy
// AutoClosingQuotes is when typing a quote also inserts the closing
// quote (autoClosingQuotes: "languageDefined").
AutoClosingQuotes AutoClosingStrategy
// AutoClosingComments is when typing the start of a block comment
// pair (TypeScript's "/**") also inserts its end
// (autoClosingComments: "languageDefined").
AutoClosingComments AutoClosingStrategy
// AutoClosingOvertype is when typing a closing bracket or quote types
// over the same character after the caret (autoClosingOvertype:
// "auto", only over characters the editor auto-inserted).
AutoClosingOvertype AutoClosingEditStrategy
// AutoClosingDelete is when Backspace between an opening and a closing
// character deletes both (autoClosingDelete: "auto", only a pair the
// editor auto-closed).
AutoClosingDelete AutoClosingEditStrategy
// AutoSurround is when typing a bracket or quote over a selection
// wraps it instead of replacing it (autoSurround: "languageDefined").
AutoSurround AutoSurroundStrategy
// AutoIndent is how Enter, Tab on a blank line, typing, moving lines
// and inserting lines adjust the indentation (autoIndent: "full").
AutoIndent AutoIndentStrategy
// EmptySelectionClipboard makes Copy and Cut with a caret (no
// selection) copy or cut its whole line, and Paste of such a copy
// insert the line above the caret's line (emptySelectionClipboard:
// true).
EmptySelectionClipboard bool
// MultiCursorPaste is how pasted text is shared among several cursors
// (multiCursorPaste: "spread"); unset or unknown values are "spread".
MultiCursorPaste MultiCursorPasteMode
// DragAndDrop lets the mouse drag the selected text to another place,
// moving it, or copying it with Alt (Option) on macOS and Ctrl
// elsewhere (dragAndDrop: true).
DragAndDrop bool
// ContextMenu shows the context menu on a right click in the text
// (contextmenu: true; menu.go). Off, a right click only focuses the
// view and moves the caret there when it is outside the selections.
ContextMenu bool
// WordWrap is when long lines wrap onto several view lines (wordWrap:
// "off"; wrap.go); unset or unknown values are "off". Large files
// (Model.LargeFile) never wrap.
// editor.action.toggleWordWrap (Alt+Z) overrides it per State.
WordWrap WrapMode
// WordWrapColumn is the wrapping column of WrapColumn and WrapBounded
// (wordWrapColumn: 80); values <= 0 mean 80.
WordWrapColumn int
// WrappingIndent is the indentation of continuation rows
// (wrappingIndent: "same"); unset or unknown values are "same".
WrappingIndent WrappingIndentMode
// Folding enables code folding: the fold commands, the gutter's
// folding controls and hidden regions (folding: true; folding.go).
// Large files (Model.LargeFile) have no folding.
Folding bool
// FoldingStrategy is how the folding ranges are computed
// (foldingStrategy: "auto"); unset or unknown values are "auto".
FoldingStrategy FoldingStrategy
// FoldingHighlight gives folded regions' start lines a background
// (foldingHighlight: true).
FoldingHighlight bool
// ShowFoldingControls is when the gutter shows the folding controls
// (showFoldingControls: "mouseover"); unset or unknown values are
// "mouseover".
ShowFoldingControls ShowFoldingControls
// AnimateFoldingControls fades expanded controls in and out over 500 ms
// in mouseover mode. Collapsed controls stay visible.
AnimateFoldingControls bool
// RenderWhitespace is which blanks are drawn as marks
// (renderWhitespace: "selection"); unset or unknown values are
// "selection".
RenderWhitespace RenderWhitespaceMode
// RenderControlCharacters draws control characters (U+0000–U+001F but
// tab, and U+007F) as their Control Pictures symbols, white on dark red
// (renderControlCharacters: true).
RenderControlCharacters bool
// Guides are the indentation guides (guides).
Guides GuidesOptions
// BracketPairColorization colors brackets by nesting level and
// unmatched ones as errors (bracketPairColorization.enabled: true).
// Documents over 5 000 000 bytes (no bracket tree) are not colorized.
BracketPairColorization bool
// MatchBrackets is when the bracket pair at the caret is highlighted
// (matchBrackets: "always"); unset or unknown values are "always".
MatchBrackets MatchBracketsMode
// RenderLineHighlight is where the caret's line is highlighted
// (renderLineHighlight: "line"); unset or unknown values are "line".
RenderLineHighlight RenderLineHighlightMode
// Padding is the space above the first line and below the last
// (padding: {top: 0, bottom: 0}).
Padding PaddingOptions
// OccurrencesHighlight highlights, once the caret came to rest, the
// whole-word, case-sensitive
// occurrences of the word at the caret (occurrencesHighlight:
// "singleFile"; occurrences.go). "multiFile" works as "singleFile":
// only the text of the view's own document is matched, and only
// textually (no language documentHighlight provider yet). Large files
// (Model.LargeFile) have none.
OccurrencesHighlight OccurrencesHighlightMode
// OccurrencesHighlightDelay is how long, in milliseconds, the
// occurrences wait to be drawn once the highlighter ran, 50 ms after
// the caret came to rest (occurrencesHighlightDelay: 0). Values < 0
// mean 0.
OccurrencesHighlightDelay int
// SelectionHighlight highlights the other matches of a selection that
// spans one line (selectionHighlight: true; occurrences.go), at most
// 200 characters long (selectionHighlightMaxLength). Large files have
// none.
SelectionHighlight bool
// UnicodeHighlight marks suspicious characters with a box
// (unicodeHighlight; unicode.go).
UnicodeHighlight UnicodeHighlightOptions
// Links underlines the URLs found in the text (Monaco's LinkComputer);
// Cmd+click (Ctrl+click elsewhere) hands the URL to the host through
// ViewW.OnOpenLink (links: true; links.go). Documents over 50 MB (the
// limit of Monaco's editor worker) have none.
Links bool
// ColorDecorators draws a swatch before each CSS color literal (#rgb,
// #rgba, #rrggbb, #rrggbbaa, rgb(), rgba(), hsl(), hsla()); a click on
// it edits the color with a picker (colorDecorators: true; colors.go).
// Documents over 50 MB have none.
ColorDecorators bool
// MouseWheelZoom makes Cmd+wheel (Ctrl+wheel elsewhere) change the
// editor zoom level, as the editor.action.fontZoomIn/Out/Reset
// commands do (mouseWheelZoom: false; see SetZoomLevel).
MouseWheelZoom bool
// StickyScroll pins enclosing folding range starts (stickyScroll).
StickyScroll StickyScrollOptions
// Minimap is the token-colored document preview (minimap).
Minimap MinimapOptions
// OverviewRulerLanes is the number of marker lanes (overviewRulerLanes: 3).
// Zero hides the ruler; values are clamped to 0..3.
OverviewRulerLanes int
// OverviewRulerBorder draws the left border (overviewRulerBorder: true).
OverviewRulerBorder bool
// contains filtered or unexported fields
}Options are one editor's settings (Monaco's editor options). Each field defaults to Monaco 0.56's default (DefaultOptions); the comment names the Monaco option.
The tab size and insertSpaces are not here: like Monaco's model options (ITextModel.updateOptions) they belong to the document, so every view of it indents alike; see Model.TabSize and Model.InsertSpaces.
func DefaultOptions
func DefaultOptions() OptionsDefaultOptions returns the default Options.
OverviewMark
type OverviewMark struct {
Line int
Color color.NRGBA
Lane int
}OverviewMark is a model-line marker (zero based). Lane is a bit mask: 1 left, 2 middle, 4 right. A combination paints each selected lane.
OverviewStyle
type OverviewStyle struct {
Color color.NRGBA
// Lane is a bit mask as OverviewMark.Lane: 1 left, 2 middle, 4 right.
Lane int
}OverviewStyle is a decoration's mark on the overview ruler.
Experimental: part of the decorations API (docs/specs/diff-view.md).
PaddingOptions
type PaddingOptions struct {
// Top is the space above the first line, scrolled away with the text
// (padding.top: 0).
Top float32
// Bottom is the space below the last line (padding.bottom: 0). As in
// Monaco with scrollBeyondLastLine, scrolling stops with the last line
// at the top whatever it is, so it changes nothing visible.
Bottom float32
}PaddingOptions are the empty space above the first line and below the last (Monaco's padding), in logical pixels.
RenderLineHighlightMode
type RenderLineHighlightMode stringRenderLineHighlightMode is where the caret's line is highlighted (Monaco's renderLineHighlight).
const (
// RenderLineHighlightNone highlights nothing.
RenderLineHighlightNone RenderLineHighlightMode = "none"
// RenderLineHighlightGutter highlights the line's gutter (also with a
// selection).
RenderLineHighlightGutter RenderLineHighlightMode = "gutter"
// RenderLineHighlightLine highlights the line's text area while every
// selection is empty.
RenderLineHighlightLine RenderLineHighlightMode = "line"
// RenderLineHighlightAll is both.
RenderLineHighlightAll RenderLineHighlightMode = "all"
)RenderWhitespaceMode
type RenderWhitespaceMode stringRenderWhitespaceMode is which blanks are drawn as visible marks: a middle dot for a space, an arrow for a tab (Monaco's renderWhitespace).
const (
// RenderWhitespaceNone draws no marks.
RenderWhitespaceNone RenderWhitespaceMode = "none"
// RenderWhitespaceBoundary marks the leading and trailing blanks, tabs,
// and runs of two or more spaces.
RenderWhitespaceBoundary RenderWhitespaceMode = "boundary"
// RenderWhitespaceSelection marks the blanks inside the selections.
RenderWhitespaceSelection RenderWhitespaceMode = "selection"
// RenderWhitespaceTrailing marks the trailing blanks (all of a blank
// line's).
RenderWhitespaceTrailing RenderWhitespaceMode = "trailing"
// RenderWhitespaceAll marks every blank.
RenderWhitespaceAll RenderWhitespaceMode = "all"
)RevealWhere
type RevealWhere uint8RevealWhere is where RevealLine and RevealRange put what they reveal.
Experimental: part of the scrolling API (docs/specs/diff-view.md).
const (
// RevealNearest scrolls the least amount that shows it.
RevealNearest RevealWhere = iota
// RevealCenter centres it vertically.
RevealCenter
// RevealCenterIfOutside centres it unless it is fully shown already.
RevealCenterIfOutside
// RevealTop puts it at the viewport's top.
RevealTop
)ScrollEvent
type ScrollEvent struct {
// ScrollTop and ScrollLeft are the new position.
ScrollTop, ScrollLeft float64
// TopChanged: the vertical position changed (the model line at the
// top or the offset from its top); LeftChanged: the horizontal one.
TopChanged, LeftChanged bool
// Line and Offset are LineAtTop.
Line int
Offset float32
}ScrollEvent is a change of a view's scroll position (OnDidScroll).
Experimental: part of the scrolling API (docs/specs/diff-view.md).
Selection
type Selection = buffer.SelectionSelection is the selection: Anchor is where it started, Head is the caret (byte offsets). A caret has Anchor == Head.
ShowFoldingControls
type ShowFoldingControls stringShowFoldingControls is when the gutter shows the folding controls (Monaco's showFoldingControls option).
const (
// FoldingControlsAlways always shows them.
FoldingControlsAlways ShowFoldingControls = "always"
// FoldingControlsNever never shows them, and the gutter leaves no room
// for them.
FoldingControlsNever ShowFoldingControls = "never"
// FoldingControlsMouseOver shows the controls of folded ranges always
// and the others while the pointer is over the gutter.
FoldingControlsMouseOver ShowFoldingControls = "mouseover"
)State
type State struct {
// Model is the document shown. It is set by NewView; do not replace
// it (create another State with NewView, and carry the per-editor state
// over with SaveViewState / RestoreViewState).
Model *Model
Theme *theme.Theme
// Options are the editor's persistent settings: the application sets
// them (the tab size and insertSpaces are the Model's: Model.TabSize,
// Model.InsertSpaces). The View's modifiers (FontSize, TabSize, ReadOnly, LineNumbers)
// override them for one frame only and do not write them.
Options Options
// Sels are the selections, the primary first (Monaco's
// getSelections()); Head is the caret. There is always at least one.
// Set them through SetSelections, MoveCaret or Move to keep them valid
// and merged and the undo grouping right; see cursors.go.
Sels []Selection
// Viewport is the scroll position and the sizes the View measured.
Viewport Viewport
// contains filtered or unexported fields
}State is one editor's view of a Model: the selection, the viewport and the Options. The application owns it and passes it to the View every frame. Several States may show the same Model; an edit made through one moves the others' selections (see NewView). It is not safe for concurrent use; drive it from the UI goroutine.
func NewState
func NewState(text, filename string, th *theme.Theme) *StateNewState returns a State showing a private Model (NewModel with filename as the URI and grammars from DefaultRegistry) holding text.
func NewStateWithRegistry
func NewStateWithRegistry(text, filename string, th *theme.Theme, reg *monarch.Registry) *StateNewStateWithRegistry is NewState with grammars from reg.
func NewView
func NewView(m *Model, th *theme.Theme) *StateNewView returns a new editor State showing m, with DefaultOptions and the caret at the start. While it is open (until Close), an edit, undo or redo another view makes on m maps this view's selections through the edits as Monaco does: a caret where text is inserted moves after it, a caret inside deleted text moves to the start of the deletion. The first visible line follows the text the same way.
The State subscribes to m: call Close when the editor goes away, or the Model keeps it (and keeps mapping its selection) for as long as the Model lives. Close does not release a ModelPool reference; Release the Model separately.
func (*State) AddCursor
func (s *State) AddCursor(off int)AddCursor adds a caret at off (Alt+click); while there are other cursors, a selection containing off (ends included) is removed instead (Monaco's createCursor).
func (*State) AddSelectionToNextFindMatch
func (s *State) AddSelectionToNextFindMatch() (Selection, bool)AddSelectionToNextFindMatch adds a selection at the next occurrence of the primary selection's text after the last added selection, wrapping around (Monaco's editor.action.addSelectionToNextFindMatch, Cmd+D). From a single caret it first selects the word under it; later presses then add the next occurrences of that word, case-sensitively and as a whole word; from a selection, its text matches case-insensitively anywhere (see findSessionNow). When several selections do not all hold the same text (ignoring case, as Monaco's modelRangesContainSameText with the default find options), it instead selects the word under every caret. It reports the selection it added (the primary selection for the first press from a caret), false when there is none.
func (*State) Close
func (s *State) Close()Close releases the State's subscription to its Model, so the Model no longer holds or updates it. It is required when an editor goes away while its Model stays open (another view, a ModelPool). It does not release a ModelPool reference (call ModelPool.Release for that), and it is safe after the pool disposed the Model and when called twice. The State must not be used afterwards.
func (*State) ColumnSelect
func (s *State) ColumnSelect(fromLine, fromCol, toLine, toCol int)ColumnSelect selects the box from visual column fromCol of line fromLine to visual column toCol of line toLine (Monaco's column selection, Shift+Alt+drag): one selection per line, from the character boundary nearest fromCol to the one nearest toCol, the line fromLine primary. Visual columns count as vertical moves do (tabs to the next tab stop, wide characters two columns), the column grid the View draws on. Lines too short to reach into the box get no selection; when no line does, every line gets a caret at its end.
func (*State) CursorRedo
func (s *State) CursorRedo() boolCursorRedo re-applies the selections CursorUndo undid (cursorRedo).
func (*State) CursorUndo
func (s *State) CursorUndo() boolCursorUndo restores the selections (and scroll position) from before the last selection change (Monaco's cursorUndo); it reports false when there is none. Edits clear the cursor history.
func (*State) Decorations
func (s *State) Decorations(owner string) []DecorationDecorations returns the current decorations set by SetDecorations for owner on this view.
Experimental: part of the decorations API (docs/specs/diff-view.md).
func (*State) Delete
func (s *State) Delete(dir Direction, unit Unit)Delete deletes every selection, and at each caret the text between it and where Move(dir, unit) would put it, as one edit set; ranges of several cursors that overlap merge. Consecutive Char deletes form one undo step; every other delete is a step of its own. Line deletes the caret's whole line including one adjacent line break, whatever dir; LineEdge deletes to column 0 or to the line end (not to the first non-blank).
func (*State) Edit
func (s *State) Edit(edits []buffer.Edit, after Selection) errorEdit applies arbitrary edits (as buffer.Buffer.Edit: sorted, non-overlapping, in the current snapshot's offsets) and sets the selection to after, an offset pair in the new text (clamped), the only selection. It neither ends nor starts undo steps: callers group with s.Model.Buffer().PushUndoStop (except that an edit following another view's edit starts a new step). On error nothing changes.
func (*State) Execute
func (s *State) Execute(id string, args any) boolExecute runs the registered command id with args on the State and reports whether it ran and did something. It refuses unknown commands, commands whose Precondition does not hold (evaluated over the context keys of the view that last showed the State, see contextkeys.go) and Mutates commands while the view is read-only. Commands that need the view (vertical moves by layout x, the clipboard, revealing the caret horizontally) use the view that last showed the State; without one they fall back to the State's own column model, and clipboard commands do nothing.
func (*State) Folded
func (s *State) Folded() []FoldingRangeFolded returns the folded regions, by start line.
func (*State) FoldingRanges
func (s *State) FoldingRanges() []FoldingRangeFoldingRanges returns the folding ranges of the current text (nil while folding is off), by start line.
func (*State) HiddenAreaAt
func (s *State) HiddenAreaAt(line int) (owner string, ok bool)HiddenAreaAt returns the owner hiding model line line in this view (the first by name when several do); false when none does (the line may still be inside a folded region).
Experimental: part of the hidden areas API (docs/specs/diff-view.md).
func (*State) HiddenAreas
func (s *State) HiddenAreas(owner string) []LineRangeHiddenAreas returns the lines owner hides in this view, moved with the edits since they were set, in the order set.
Experimental: part of the hidden areas API (docs/specs/diff-view.md).
func (*State) Highlighter
func (s *State) Highlighter() *highlight.HighlighterHighlighter returns the Model's highlighter, nil for plain text.
func (*State) Insert
func (s *State) Insert(text string)Insert replaces every selection with text (typing, paste, IME commit) and puts each caret after the inserted text, as one edit set. Line breaks are normalised as by buffer.Snapshot.Apply. Typing a single character at carets (no selection) continues the current undo step; anything else is a step of its own.
func (*State) LargeFile
func (s *State) LargeFile() boolLargeFile reports whether the State's Model is a large file (Model.LargeFile): folding, word wrap and the occurrences and selection highlights are off.
func (*State) LineAtTop
func (s *State) LineAtTop() (line int, offset float32)LineAtTop returns the model line at the viewport's top edge (whose block, or the zones before the first line, the edge is in) and the pixels from that line's top to the edge: ScrollTop() == LineTop(line) + offset. The offset is negative over the top padding and the zones before the first line.
Experimental: part of the scrolling API (docs/specs/diff-view.md).
func (*State) LineBlock
func (s *State) LineBlock(line int) (top float64, textRows, zoneRows int)LineBlock returns the top of model line line (LineTop), its text rows and the rows of the view zones after it: its block of (textRows+zoneRows) rows. A hidden line has no rows.
Experimental: part of the scrolling API (docs/specs/diff-view.md).
func (*State) LineTop
func (s *State) LineTop(line int) float64LineTop returns the top of the first text row of model line line (0 based, clamped) in ScrollTop's coordinates (Monaco's getTopForLineNumber). A hidden line's top is the bottom of the block of the shown line before it (its text rows and zones). It measures no line.
Experimental: part of the scrolling API (docs/specs/diff-view.md).
func (*State) Move
func (s *State) Move(dir Direction, unit Unit, extend bool)Move moves every caret by unit in dir; with extend it extends each selection. Without extend, moving by Char from a non-empty selection collapses it to its start (Backward) or end (Forward). Vertical moves keep each cursor's goal column. Cursors that meet merge. Move does not scroll (except Page); call RevealCaret after keyboard moves.
Deviation from Monaco: a vertical move without extend starts from the caret (Head) of a non-empty selection; Monaco's moveUp / moveDown start from the selection's start (up) or end (down).
func (*State) MoveCaret
func (s *State) MoveCaret(to int, extend bool)MoveCaret puts the caret at offset to (clamped to the document, and moved back to the start of a UTF-8 character it falls inside) and removes the secondary cursors, as a click does in Monaco. With extend the primary selection's anchor stays and the selection grows or shrinks; otherwise it collapses to the caret. It is what a click or a drag maps to.
func (*State) OnDidScroll
func (s *State) OnDidScroll(fn func(ScrollEvent)) (cancel func())OnDidScroll calls fn when the view's scroll position changed, compared as the model line at the top and the pixels from its top (LineAtTop) and ScrollLeft: rows above becoming known while wrapping move no picture and are not reported. The View checks after its build (the wheel), after applying its input (keys, clicks, reveals) and at the end of its paint; changes made directly between frames (SetScrollTop, Viewport) are reported at the next check. fn may scroll other views, not this one. cancel removes fn.
Experimental: part of the scrolling API (docs/specs/diff-view.md).
func (*State) Primary
func (s *State) Primary() SelectionPrimary returns the primary selection, Sels[0] (Monaco's getSelection()).
func (*State) Redo
func (s *State) Redo() boolRedo re-applies the last undone step and restores the selections from after it in this view; it reports false when there is nothing to redo. During a Model notification it is queued and reports true.
func (*State) RemoveSecondaryCursors
func (s *State) RemoveSecondaryCursors() boolRemoveSecondaryCursors keeps only the primary selection (Esc).
func (*State) RestoreViewState
func (s *State) RestoreViewState(v ViewState)RestoreViewState restores a state SaveViewState returned, possibly for an earlier version of the text: out-of-range values are clamped to the document (lines to the last line, offsets to the text, OffsetY below the line height, scroll offsets to >= 0). Overlapping selections merge; without selections the caret goes to the document start.
func (*State) RevealCaret
func (s *State) RevealCaret()RevealCaret scrolls vertically the least amount that makes the caret's view line fully visible (its top when the viewport is shorter than a line). Horizontal reveal needs the caret's x, which only the View can measure: see RevealX.
func (*State) RevealLine
func (s *State) RevealLine(line int, where RevealWhere)RevealLine scrolls vertically to show the first row of model line line (clamped; a hidden line shows where it would be) as where says. While wrapping, the lines up to a viewport above it are measured first.
Experimental: part of the scrolling API (docs/specs/diff-view.md).
func (*State) RevealRange
func (s *State) RevealRange(start, end int, where RevealWhere)RevealRange scrolls vertically to show the rows of the offsets [start, end] as where says: the whole range when it fits in the viewport, otherwise its start. While wrapping, the lines up to a viewport above it are measured first.
Experimental: part of the scrolling API (docs/specs/diff-view.md).
func (*State) RevealX
func (s *State) RevealX(x0, x1 float32)RevealX scrolls horizontally the least amount that makes content x range [x0, x1] (the caret, as measured by the View) visible.
func (*State) RowsOf
func (s *State) RowsOf(line int) intRowsOf returns the text rows of model line line: 1 without wrapping, its measured rows while wrapping (it measures the line, keeping the picture in place), 0 when hidden.
Experimental: part of the scrolling API (docs/specs/diff-view.md).
func (*State) SaveViewState
func (s *State) SaveViewState() ViewStateSaveViewState returns the editor's scroll position, selections and folded regions.
func (*State) ScrollBy
func (s *State) ScrollBy(dy, dx float32)ScrollBy scrolls by dy pixels down and dx pixels right, clamped to the document (vertically to the last line at the top, horizontally to ContentWidth when known).
func (*State) ScrollHeight
func (s *State) ScrollHeight() float64ScrollHeight returns the scrollable height in pixels: the view lines, the top padding and a viewport's height (the last line can scroll to the top), as the overview ruler measures the document.
Experimental: part of the scrolling API (docs/specs/diff-view.md).
func (*State) ScrollLeft
func (s *State) ScrollLeft() float32ScrollLeft returns the horizontal scroll position in pixels.
Experimental: part of the scrolling API (docs/specs/diff-view.md).
func (*State) ScrollTop
func (s *State) ScrollTop() float64ScrollTop returns the vertical scroll position: the pixels of the document above the viewport's top edge, the top padding included.
Experimental: part of the scrolling API (docs/specs/diff-view.md).
func (*State) SelectHighlights
func (s *State) SelectHighlights() boolSelectHighlights selects every occurrence of the primary selection's text (or of the word under an empty caret) with the same matching rules as AddSelectionToNextFindMatch (Monaco's editor.action.selectHighlights, Cmd+Shift+L); the occurrence at the primary selection stays primary. It reports false when there is nothing to select.
func (*State) SetDecorations
func (s *State) SetDecorations(owner string, ds []Decoration)SetDecorations replaces owner's decorations shown in this view only (Monaco's ownerId filter): they are stored on the Model and move with its text like Model.SetDecorations', and go away with Close. The owner names of a view and of the Model are separate.
Experimental: part of the decorations API (docs/specs/diff-view.md).
func (*State) SetHiddenAreas
func (s *State) SetHiddenAreas(owner string, rs []LineRange)SetHiddenAreas replaces the lines owner hides in this view; no ranges remove the owner. Ranges are lines of the current text, clamped to it; empty ones are dropped. They follow the text from then on (lines inserted at their edges join them). The view keeps at least one line visible: ranges hiding every line leave the first one shown.
Experimental: part of the hidden areas API (docs/specs/diff-view.md).
func (*State) SetInlayHints
func (s *State) SetInlayHints(version uint64, hints []InlayHint) boolSetInlayHints replaces this view's visual hints for the given snapshot version. It returns false and keeps the current hints if a newer document version is active. Hints expire on a document edit. Pass nil to clear them. Empty or multiline labels and invalid offsets are ignored. Offsets on a rune boundary inside a grapheme snap left. Unwrapped long lines use the editor's chunked layout and omit hints.
func (*State) SetLineAtTop
func (s *State) SetLineAtTop(line int, offset float32)SetLineAtTop scrolls so that the viewport's top edge is offset pixels below the top of model line line (LineAtTop's inverse), clamped to the document.
Experimental: part of the scrolling API (docs/specs/diff-view.md).
func (*State) SetOverviewMarks
func (s *State) SetOverviewMarks(owner string, marks []OverviewMark)SetOverviewMarks replaces owner's marks in this view, not in the shared Model. The input is copied; nil or empty removes the owner. The host requests a frame, as with changes to Options or selections.
func (*State) SetScrollLeft
func (s *State) SetScrollLeft(px float32)SetScrollLeft scrolls horizontally to px, clamped to the content width the View last measured.
Experimental: part of the scrolling API (docs/specs/diff-view.md).
func (*State) SetScrollTop
func (s *State) SetScrollTop(px float64)SetScrollTop scrolls vertically to px (see ScrollTop), clamped to the document (the last line may scroll up to the top).
Experimental: part of the scrolling API (docs/specs/diff-view.md).
func (*State) SetSelections
func (s *State) SetSelections(sels []Selection)SetSelections sets the selections, the primary first: each is clamped to the document and onto character boundaries, and overlapping (or touching, when one is empty) selections merge as in Monaco. A change of selection ends the current undo step and is recorded for cursorUndo. An empty sels does nothing.
func (*State) SetViewZones
func (s *State) SetViewZones(owner string, zs []ViewZone)SetViewZones replaces owner's zones in this view; no zones remove the owner. AfterLine is clamped to the current text. The view keeps its top model line in place.
Experimental: part of the view zones API (docs/specs/diff-view.md).
func (*State) Snapshot
func (s *State) Snapshot() buffer.SnapshotSnapshot returns the current text.
func (*State) SyntaxCommandIncomplete
func (s *State) SyntaxCommandIncomplete() boolreindentLines re-indents every line by the language's indentation rules (Monaco's ReindentLinesAction, getReindentEditOperations): from the first line on, a line matching increaseIndentPattern indents the lines after it, one matching decreaseIndentPattern outdents itself and the rest, one matching indentNextLinePattern indents only the next line, and lines matching unIndentedLinePattern keep the indentation they get but do not change it for the others. Lines starting inside a string are left alone. The indentation is written in the Model's InsertSpaces style. A language without indentation rules does nothing. SyntaxCommandIncomplete reports whether the last trimTrailingWhitespace or reindentLines command could not classify all required lines within its syntax budget. Trim keeps unclassified whitespace; reindent makes no changes. This is not a promise that a command completed within one frame: scanning the text is O(n), and one atomic lexer call can overshoot the shared budget.
func (*State) ToggleWordWrap
func (s *State) ToggleWordWrap()ToggleWordWrap turns word wrap off when lines wrap, else on (to Options.WordWrap when that is not "off", else "on"), for this State only, overriding Options.WordWrap until toggled back (VS Code's editor.action.toggleWordWrap, Alt+Z). The View applies it from the next paint, keeping the top model line in place.
func (*State) Type
func (s *State) Type(text string)Type types text as from the keyboard: each character (grapheme cluster) goes through the typing assistance in turn, with the Enter rules for a line break ("\r\n" and "\r" count as one). Use Insert to insert text as is (paste, programmatic edits).
func (*State) Undo
func (s *State) Undo() boolUndo reverts the Model's last undo step (whichever view made it) and restores the selections from before it in this view; it reports false when there is nothing to undo. During a Model notification it is queued (see Model.Subscribe) and reports true.
func (*State) ViewZones
func (s *State) ViewZones(owner string) []ViewZoneViewZones returns owner's zones in this view, AfterLine moved with the edits since they were set, in the order set.
Experimental: part of the view zones API (docs/specs/diff-view.md).
func (*State) VisibleLines
func (s *State) VisibleLines() (first, last int)VisibleLines returns the first and last (inclusive) view lines that are at least partly visible (the same as model lines without word wrap). Without a viewport size it returns TopLine twice.
func (*State) WordWrap
func (s *State) WordWrap() WrapModeWordWrap returns the word wrap mode in effect: the one ToggleWordWrap set, else Options.WordWrap. Large files never wrap (Monaco's ViewModelLinesFromModelAsIs; largefile.go).
Stickiness
type Stickiness uint8Stickiness is what a decoration's ends do when text is typed exactly at them (Monaco's TrackedRangeStickiness).
Experimental: part of the decorations API (docs/specs/diff-view.md).
const (
// AlwaysGrowsWhenTypingAtEdges: text typed at either end goes inside
// (Monaco's default).
AlwaysGrowsWhenTypingAtEdges Stickiness = iota
// NeverGrowsWhenTypingAtEdges: text typed at either end stays outside.
NeverGrowsWhenTypingAtEdges
// GrowsOnlyWhenTypingBefore: text typed at the start goes inside, at
// the end outside.
GrowsOnlyWhenTypingBefore
// GrowsOnlyWhenTypingAfter: text typed at the end goes inside, at the
// start outside.
GrowsOnlyWhenTypingAfter
)StickyScrollOptions
type StickyScrollOptions struct {
Enabled bool
MaxLineCount int
}StickyScrollOptions configures stickyScroll (enabled: true, maxLineCount: 5). Scopes come from the editor's folding ranges, including its provider.
SuggestOptions
type SuggestOptions struct {
Labels []string // one per candidate, in display order
Selected *int // maintained by the caller and keyboard navigation; -1 for none
Accept func(int)
Dismiss func()
Details func(int) // optional body for the selected candidate
Name string // accessible name of the candidate list
// Width, DetailsWidth and MaxHeight are logical pixels. Zero uses
// 240, 300 and 240 respectively, bounded by the window size.
Width, DetailsWidth, MaxHeight float32
}SuggestOptions configures a caret-anchored completion list.
TypeArgs
type TypeArgs struct{ Text string }TypeArgs are the arguments of the type command (VS Code's {text}), typed through the typing assistance (State.Type); a map[string]any or map[string]string with a "text" entry, or a plain string, works too.
UnicodeHighlightOptions
type UnicodeHighlightOptions struct {
// NonBasicASCII marks every character outside basic ASCII
// (unicodeHighlight.nonBasicASCII: "inUntrustedWorkspace", off here).
NonBasicASCII UnicodeHighlightSetting
// InvisibleCharacters marks characters that take no visible space
// (unicodeHighlight.invisibleCharacters: true).
InvisibleCharacters bool
// AmbiguousCharacters marks characters that look like basic ASCII
// ones, as Cyrillic "а" looks like "a" (unicodeHighlight
// .ambiguousCharacters: true).
AmbiguousCharacters bool
// IncludeComments also marks characters in comments
// (unicodeHighlight.includeComments: "inUntrustedWorkspace", off here).
IncludeComments UnicodeHighlightSetting
// IncludeStrings also marks characters in strings
// (unicodeHighlight.includeStrings: true).
IncludeStrings bool
// AllowedCharacters are never marked (unicodeHighlight
// .allowedCharacters, a set of characters in Monaco; here a string of
// them).
AllowedCharacters string
// AllowedLocales are the locales whose ambiguous characters tables
// apply (unicodeHighlight.allowedLocales: {_os: true, _vscode: true},
// the zero LocaleSet; "_os" and "_vscode" are SetSystemLocales'
// locales). A character ambiguous in one of these locales' own
// alphabets is not marked: AllowLocales("ru") stops marking the
// Cyrillic "а" (unicode_locales.go). A set, not a map, so Options
// stays comparable.
AllowedLocales LocaleSet
}UnicodeHighlightOptions are the suspicious characters marked with a box (Monaco's unicodeHighlight; unicode.go).
UnicodeHighlightSetting
type UnicodeHighlightSetting stringUnicodeHighlightSetting is an option of Monaco's unicodeHighlight that takes true, false or "inUntrustedWorkspace".
const (
UnicodeHighlightTrue UnicodeHighlightSetting = "true"
UnicodeHighlightFalse UnicodeHighlightSetting = "false"
// UnicodeHighlightInUntrustedWorkspace is on in an untrusted
// workspace only. The editor has no workspace trust: it counts as
// trusted, so this is false.
UnicodeHighlightInUntrustedWorkspace UnicodeHighlightSetting = "inUntrustedWorkspace"
)Unit
type Unit intUnit is how far a Move or Delete goes.
const (
// Char is one grapheme cluster; at a line edge it crosses the line
// break.
Char Unit = iota
// Word moves to the start (Backward) or end (Forward) of the previous or
// next word, by the language's wordPattern or, without one, runs of
// Unicode letters, digits, marks and '_'. At a line edge it continues on
// the adjacent line.
Word
// Line moves up or down one line (one view line while wrapping),
// keeping the goal column.
Line
// LineEdge is Home / End. Home goes to the first non-blank character,
// or to column 0 when already there. On a wrapped line Home and End
// first go to the edges of the view line (Monaco).
LineEdge
// Page moves up or down by the number of lines that fit in the viewport
// and scrolls by the same amount.
Page
// Doc is the start or end of the document.
Doc
)ViewState
type ViewState struct {
// TopLine and OffsetY are the vertical scroll position: TopLine is the
// document (model) line at the top, so it stays meaningful when
// wrapping or folding changes (Viewport.TopLine is a view line; a top
// inside a wrapped line is saved as that line's first row). A top in
// the view zones after the line is saved as the offset from the line's
// top: OffsetY then exceeds a line height (restoring clamps it to the
// zones there are).
TopLine int
OffsetY float32
// ScrollX is the horizontal scroll in pixels.
ScrollX float32
// Selections are the selections, the primary first.
Selections []Selection
// Folded are the start lines of the folded regions. Restoring folds
// the folding ranges of the current text starting there (Monaco keeps
// their end lines and a checksum too; a start line that no longer
// starts a range is not folded).
Folded []int
}ViewState is the per-editor state worth keeping while an editor shows another Model, and restoring when it comes back (Monaco's saveViewState / restoreViewState).
ViewW
type ViewW struct {
// contains filtered or unexported fields
}ViewW is the code editor view of a State: it draws the visible lines with syntax colors, line numbers, the current-line highlight, the selection and the blinking caret, scrolls on the mouse wheel and trackpad, and edits the State from the keyboard (keys run commands through a keymap; see command.go and keymap.DefaultRules), the mouse and the IME.
The View measures and shapes only the visible lines (plus two above and below); lines longer than longLineRunes are cut into chunks and only the chunks in the visible horizontal range are tokenized and shaped (see longLine). With word wrap (Options.WordWrap, editor.action.toggleWordWrap) the lines are view lines: a long model line is shown as several rows, each shaped on its own, and only the lines around the viewport are wrapped (wrap.go, viewlines.go). Redraws are driven by input and by the application: apart from the caret blink (a Context.WakeAt while focused), one frame after input it applied while painting and, in a large document, a frame when the folding controls' ranges are due (paint.go, foldRangesNow), and one frame when the occurrences of the word at the caret are due, and a frame after each frame that left a document search (the occurrences or the selection's matches) unfinished (occurrences.go: a long search is spread over frames), the View never requests frames on its own, not even while highlighting is incomplete. An application that starts the Highlighter's background goroutine passes c.Invalidator() (or ui.Invalidate) as its ready callback, so newly final tokens are drawn when they arrive.
func View
func View(c *ui.Context, st *State) *ViewWView shows st. The application holds st; the View sets st.Viewport's measured sizes and scrolls it.
func (*ViewW) Box
func (w *ViewW) Box() *ui.BoxBox returns the view's box (ID, rect).
func (*ViewW) Changed
func (w *ViewW) Changed() boolChanged reports whether the text was edited through the View this frame. It applies the frame's input, so call it after the modifiers (ReadOnly ...); without a call the input is applied when the view paints.
func (*ViewW) CompletionAnchor
func (w *ViewW) CompletionAnchor() (geom.Rect, bool)CompletionAnchor returns the primary caret's rectangle in UI logical coordinates, using the current caret and the last laid-out viewport. It processes pending input like Changed. The result is unavailable before layout or when the caret is outside the visible text area.
func (*ViewW) CompletionKeys
func (w *ViewW) CompletionKeys(count int, selected *int, accept func(int), dismiss func()) *ViewWCompletionKeys gives an open completion list keyboard control while this writable view has focus. Unmodified Up and Down wrap across count candidates, Home and End select the ends, Enter and Tab confirm, and Escape dismisses. Use -1 for no selection. Nil accept or dismiss leaves the corresponding keys to the editor. Pass zero count to turn it off. Call before Changed or CompletionAnchor; the application draws the list.
func (*ViewW) Context
func (w *ViewW) Context(fn func(key string) (any, bool)) *ViewWContext adds application context keys for this frame's keybinding when clauses and command preconditions: fn is asked before the built-in keys (see contextkeys.go) and reports false for keys it does not define.
func (*ViewW) Focused
func (w *ViewW) Focused() boolFocused reports whether the view has keyboard focus.
func (*ViewW) FoldingProvider
func (w *ViewW) FoldingProvider(p FoldingRangeProvider) *ViewWFoldingProvider sets the provider of the folding ranges (milestone 3: the language server), used while Options.FoldingStrategy is "auto"; nil restores the built-in strategy. The provider is kept by the State until changed: keep passing the same value (a pointer) every frame, as a new value makes the ranges be recomputed.
func (*ViewW) FontSize
func (w *ViewW) FontSize(px float32) *ViewWFontSize sets the font size in logical pixels this frame (default: st.Options.FontSize); values <= 0 are ignored.
func (*ViewW) GlyphMarginLineAtPoint
func (w *ViewW) GlyphMarginLineAtPoint(p geom.Point) (int, bool)GlyphMarginLineAtPoint maps a point in the dedicated glyph margin to a zero-based document line. Use it inside OnGutterClick for breakpoints.
func (*ViewW) GutterLineAtPoint
func (w *ViewW) GutterLineAtPoint(p geom.Point) (int, bool)GutterLineAtPoint maps a point in the laid-out gutter to a zero-based document line. Wrapped rows share a line. Padding and view zones have no line. Sticky rows report the line they show.
func (*ViewW) HoverOffset
func (w *ViewW) HoverOffset() (int, bool)HoverOffset reports the nearest UTF-8 byte offset underneath the pointer when it is over the view's visible text area. Gutter, sticky headers and overlapping widgets are excluded. Use MountContent to show content at that offset, retaining the offset while the pointer is inside the popup.
func (*ViewW) InlayHintAtPoint
func (w *ViewW) InlayHintAtPoint(p geom.Point) (int, bool)InlayHintAtPoint returns the source byte offset of the rendered hint at a UI logical point. It reports false in the gutter, outside the viewport, and over areas where no hint is drawn.
func (*ViewW) Keymap
func (w *ViewW) Keymap(km *keymap.Keymap) *ViewWKeymap sets the keymap that turns this frame's keys into commands (default: keymap.DefaultRules for the current platform, with a chord state of the view's own). Keep the same Keymap across frames: it holds the pending chord. Several views may share one; a view that loses focus clears its pending chord.
func (*ViewW) Layout
func (w *ViewW) Layout(opts ...layout.Option) *ViewWLayout applies layout options to the view's box (it grows by default).
func (*ViewW) LineNumbers
func (w *ViewW) LineNumbers(on bool) *ViewWLineNumbers shows or hides the line numbers this frame (default: st.Options.LineNumbers).
func (*ViewW) LineNumbersFunc
func (w *ViewW) LineNumbersFunc(fn LineNumberFunc, maxChars int, gen uint64) *ViewWLineNumbersFunc shows fn's labels instead of the line numbers this frame, while line numbers are shown (Options.LineNumbers not off): right aligned, the caret's line in the active color (the relative and interval modes do not apply). The numbers' column is maxChars digits wide (at least Options.LineNumbersMinChars); gen tells the View that the labels changed: increment it whenever fn would return other labels for the same lines (the whole view is redrawn then). nil fn restores the numbers.
Experimental: part of the diff view's editor API (docs/specs/diff-view.md).
func (*ViewW) MenuItems
func (w *ViewW) MenuItems(items ...MenuItem) *ViewWMenuItems adds items to this view's context menu, after the registered ones (MenuEditorContext): the application's or a plugin's items for this editor only. Call it every frame; the items of a frame that does not call it are gone. A When that does not parse hides its item.
func (*ViewW) MountContent
func (w *ViewW) MountContent(offset int, place ui.Placement, body func(), opts ...layout.Option) *ui.BoxMountContent builds an overlay at a document offset, for example a rich hover or a quick-fix affordance. It returns nil when OffsetAnchor is unavailable. The body and layout options control size and styling, and the caller controls what frames display it. Use an anchored placement such as ui.BottomStart, which flips above the row near the window edge.
func (*ViewW) MountFind
func (w *ViewW) MountFind(body func(), opts ...layout.Option) *ui.BoxMountFind mounts a caller-owned find/replace panel at the editor's top right. It reserves Monaco's 419 px default width, limited by the editor's available width. Pass layout options to override the panel size. The editor owns the overlay's focus return target when the caller closes it.
func (*ViewW) OffsetAnchor
func (w *ViewW) OffsetAnchor(offset int) (geom.Rect, bool)OffsetAnchor returns the visible character position at a UTF-8 byte offset in window logical coordinates. It processes input like Changed. Folded, offscreen and out-of-bounds positions have no anchor.
func (*ViewW) OffsetAtPoint
func (w *ViewW) OffsetAtPoint(p geom.Point) (int, bool)offsetAt returns the document offset at window point p (the last painted geometry): the nearest grapheme boundary of the view line under p; above the first line the document start, below the last its end. OffsetAtPoint maps a point in UI logical coordinates to the nearest UTF-8 byte offset, using the last laid-out text viewport. It returns false before layout or outside the text area, including the gutter.
func (*ViewW) OnDocumentChange
func (w *ViewW) OnDocumentChange(fn func(ModelChange)) *ViewWOnDocumentChange observes each document change made by this view while it processes input, including undo and redo. The caret and selections have already been updated. Call Changed during build to process input there. To observe edits made outside this view's input, use Model.Subscribe.
func (*ViewW) OnGlyphMarginClick
func (w *ViewW) OnGlyphMarginClick(fn func(GutterClick)) *ViewWOnGlyphMarginClick handles primary clicks and secondary presses inside the dedicated glyph margin. Events outside the margin go to OnGutterClick when set, otherwise they retain the editor's normal gutter behavior.
func (*ViewW) OnGutterClick
func (w *ViewW) OnGutterClick(fn func(GutterClick)) *ViewWOnGutterClick handles primary clicks and secondary presses in the gutter. Handled clicks leave the selection in place. An active folding control still receives primary clicks. Call Changed during build to handle the event there, for example to open a context menu.
func (*ViewW) OnOpenLink
func (w *ViewW) OnOpenLink(fn func(url string)) *ViewWOnOpenLink sets the function a Cmd+click (Ctrl+click elsewhere) on a link calls with its URL (Monaco's LinkDetector opening the link). The View keeps the last function set; nil turns opening off.
func (*ViewW) OnPasteImage
func (w *ViewW) OnPasteImage(fn func() bool) *ViewWOnPasteImage sets the fallback when Paste finds no clipboard text. Read the image through sys/clipboard and return true if handled. On macOS this also enables the native Paste menu for image-only clipboards while this writable view has focus.
func (*ViewW) ReadOnly
func (w *ViewW) ReadOnly(on bool) *ViewWReadOnly makes the view refuse edits this frame (typing, deleting, Enter, Tab, paste, cut, undo, redo, IME); the caret, selection, navigation and copy keep working. A frame that does not call it is read-only only when st.Options.ReadOnly is set.
func (*ViewW) Suggest
func (w *ViewW) Suggest(o SuggestOptions) *ui.BoxSuggest mounts a scrolling completion list at the caret, with an optional adjacent details pane. Call it during build before Changed or any anchor query. It processes pending input with CompletionKeys plus Page Up/Down. The caller owns the list lifetime and should clear it in Accept and Dismiss. When the caret is outside the viewport, it returns nil and leaves the keys to the editor. Read-only views do not display suggestions.
func (*ViewW) TabSize
func (w *ViewW) TabSize(n int) *ViewWTabSize sets the tab width in columns this frame (default: the Model's TabSize), for drawing and for the caret movement the State does until the next frame; values <= 0 are ignored. It does not change the Model's TabSize, which Tab and the indentation commands use.
ViewZone
type ViewZone struct {
// ID identifies the zone within its owner (the redraw hints).
ID uint64
// AfterLine is the model line (zero-based) the zone follows; -1 puts
// it before the first line.
AfterLine int
// Rows is the height in rows (line heights); a zone of no rows is not
// shown.
Rows int
// MinWidth is the width the zone's content needs, in logical pixels
// (the horizontal scroll range; Monaco's minWidthInPx).
MinWidth float32
// ShowInHidden keeps the zone shown when AfterLine is hidden (folded
// or in a hidden area): it moves to the shown line before it.
ShowInHidden bool
// Version is the zone's drawing version: whatever Paint and
// PaintGutter draw depends only on it, the ZonePaint geometry (size and
// OriginX, relative to the zone's rectangle) and the theme, and the
// owner increments it when that changes. 0 lets the editor fingerprint
// the drawing commands the callbacks emit every frame instead.
Version uint64
// Fixed keeps the text area part from scrolling horizontally
// (OriginX is the text area's left edge): the zone is redrawn on
// every horizontal scroll.
Fixed bool
// Paint draws the text area part (nil: the editor background);
// PaintGutter the gutter part (nil: the gutter background). They run
// in the View's paint, clipped to the part's visible rectangle.
Paint func(l *paint.List, z ZonePaint)
PaintGutter func(l *paint.List, z ZonePaint)
// SuppressMouseDown leaves the caret where it is when the zone is
// pressed (without it, as Monaco, the caret goes to the end of the
// line above for a press in the zone's upper half, to the start of
// the line below for the lower half).
SuppressMouseDown bool
// OnPointer, when set, sees the presses, releases and moves over the
// zone (a release goes to the zone pressed).
OnPointer func(e ZonePointer)
// Cursor is the pointer shape over the zone (the default arrow when
// zero).
Cursor input.Cursor
// Label names the zone for screen readers.
Label string
}ViewZone is a block of whole rows after a model line, drawn by its owner. The editor copies it: change a zone by setting the owner's zones again.
Experimental: part of the view zones API (docs/specs/diff-view.md).
Viewport
type Viewport struct {
// TopLine is the first view line at least partly visible. While
// wrapping it may move without the picture moving, when the rows of
// lines above it become known (see viewLines); SaveViewState records
// the model line instead.
TopLine int
// OffsetY is how many pixels of TopLine are scrolled above the top
// edge, in [0, LineHeight); on line 0 it goes down to -PadTop, the top
// padding showing above it.
OffsetY float32
// ScrollX is the horizontal scroll in pixels, >= 0.
ScrollX float32
Height, Width float32
LineHeight float32
ContentWidth float32
// PadTop and PadBottom are Options.Padding, set by the View.
PadTop, PadBottom float32
// NoScrollBeyondLastLine limits scrolling to the document and padding.
NoScrollBeyondLastLine bool
}Viewport is the visible part of the document. The scroll position is TopLine plus OffsetY pixels (an integer line index keeps it exact on documents with millions of lines, where a float32 pixel offset would not be). Lines here are view lines: with word wrap a model line may take several (viewlines.go); without it view and model lines are the same. The View sets the sizes it measured: Height and Width of the text area, LineHeight, and ContentWidth, the width of the widest line it knows (0 when unknown).
Vertical scrolling follows Monaco's default scrollBeyondLastLine: the last line may scroll up to the top of the viewport. Options.Padding adds PadTop pixels above the first line (scrolled to the top, OffsetY is -PadTop on line 0). PadBottom does not change the scroll range: with scrollBeyondLastLine Monaco's largest scrollTop is paddingTop + the lines' height - a line height, the last line at the top (viewLayout.js).
WrapMode
type WrapMode stringWrapMode is when lines wrap (Monaco's wordWrap option).
const (
// WrapOff never wraps.
WrapOff WrapMode = "off"
// WrapOn wraps at the viewport width.
WrapOn WrapMode = "on"
// WrapColumn wraps at Options.WordWrapColumn.
WrapColumn WrapMode = "wordWrapColumn"
// WrapBounded wraps at the smaller of the viewport width and
// Options.WordWrapColumn.
WrapBounded WrapMode = "bounded"
)WrappingIndentMode
type WrappingIndentMode stringWrappingIndentMode is the indentation of continuation rows (Monaco's wrappingIndent option).
const (
// WrapIndentNone starts continuation rows at column 0.
WrapIndentNone WrappingIndentMode = "none"
// WrapIndentSame indents them like the model line.
WrapIndentSame WrappingIndentMode = "same"
// WrapIndentIndent indents them one tab stop more than the line.
WrapIndentIndent WrappingIndentMode = "indent"
// WrapIndentDeep indents them two tab stops more than the line.
WrapIndentDeep WrappingIndentMode = "deepIndent"
)ZoneArea
type ZoneArea uint8ZoneArea is the part of a zone a pointer event is in.
Experimental: part of the view zones API (docs/specs/diff-view.md).
const (
ZoneText ZoneArea = iota
ZoneGutter
)ZonePaint
type ZonePaint struct {
// Rect is the part's whole rectangle in window coordinates (the text
// area's or the gutter's width, Rows line heights); rows outside the
// view are clipped away.
Rect geom.Rect
// OriginX is the window x of content x 0: the text area's left edge
// minus the horizontal scroll (the left edge for a Fixed zone and for
// the gutter).
OriginX float32
// RowH is the row height.
RowH float32
// FirstRow is the first row of the zone in the view (rows before it
// are scrolled above the top).
FirstRow int
Theme *theme.Theme
// contains filtered or unexported fields
}ZonePaint is where a zone part is drawn.
Experimental: part of the view zones API (docs/specs/diff-view.md).
ZonePointer
type ZonePointer struct {
Kind input.PointerKind // Press, Release or Move
// Pos is relative to the top-left corner of the part's rectangle
// (ZonePaint.Rect).
Pos geom.Point
Area ZoneArea
Clicks int
}ZonePointer is a pointer event over a zone.
Experimental: part of the view zones API (docs/specs/diff-view.md).