Skip to content

editor.View 代码编辑器视图 ​

editor.View 把 ui/editor.State 渲染成可编辑的代码视图,提供语法高亮、行号、选择、撤销重做、只读和大文档虚拟滚动。

何时使用 ​

  • 需要在自绘页面中编辑 Go、TypeScript、Python 等带语法高亮的代码时。
  • 多个文件需要各自保留模型、选区、滚动位置和撤销历史时。
  • 需要只读查看、行号、Tab 缩进或链接点击等编辑器交互时。
  • 只编辑 Markdown 文本并需要工具栏和实时预览时,用 MarkdownEditor;只展示短代码片段时,用 CodeBlock 更轻量。

在线体验 ​

CodeEditor 代码编辑器 · 在线体验真实 Go 组件
在独立页面打开 ↗

查看此场景的 Go 源码 ↗

基本用法 ​

下面代码放在应用的页面文件中;完整的 main 和窗口初始化见打开自绘窗口。State 和 Model 应在页面状态中复用,而不是每帧新建。

go
package main

import (
    "time"

    "github.com/tangoui/tango/ui"
    "github.com/tangoui/tango/ui/editor"
    editortheme "github.com/tangoui/tango/ui/editor/theme"
    "github.com/tangoui/tango/ui/layout"
)

var codeState *editor.State

func page(c *ui.Context) {
    if codeState == nil {
        model := editor.NewModel("main.go", "package main\n\nfunc main() {}\n", editor.DefaultRegistry())
        codeState = editor.NewView(model, editortheme.Base("vs"))
    }
    if h := codeState.Highlighter(); h != nil {
        snapshot := codeState.Snapshot()
        if !h.Highlight(snapshot, snapshot.LineCount(), 3*time.Millisecond) {
            c.WakeAt(c.Now().Add(16 * time.Millisecond))
        }
    }
    editor.View(c, codeState).LineNumbers(true).Layout(layout.H(320))
}

func main() {}

Model 保存文档和撤销历史,State 保存选区、视口和编辑器设置,View 每帧负责绘制和接收输入。有限的高亮预算让大文档在前台分帧完成高亮;视图销毁时调用 codeState.Close() 释放模型订阅。

常见用法 ​

只读、行号、字体和 Tab 大小 ​

视图修饰器只影响当前帧。TabSize(n) 调整本帧的显示列宽和光标移动,Tab 键和缩进命令使用 Model.SetTabSize(n) 设置的模型宽度。ReadOnly(true) 仍允许选择、滚动和复制,但阻止修改。

go
package main

import (
    "github.com/tangoui/tango/ui"
    "github.com/tangoui/tango/ui/editor"
    editortheme "github.com/tangoui/tango/ui/editor/theme"
    "github.com/tangoui/tango/ui/layout"
)

var readOnlyState = editor.NewView(
    editor.NewModel("config.json", "{\n  \"enabled\": true\n}\n", editor.DefaultRegistry()),
    editortheme.Base("vs-dark"),
)

func page(c *ui.Context) {
    readOnly := true
    editor.View(c, readOnlyState).
        ReadOnly(readOnly).
        LineNumbers(true).
        FontSize(14).
        TabSize(2).
        Layout(layout.H(260))
}

func main() {}

切换多个文件并保留编辑状态 ​

每个文件使用自己的 Model 和 State,切换时从 map 取回原状态即可。不要只替换同一个 Model 的文本来模拟文件,否则会混用撤销历史和选区。

go
package main

import (
    "github.com/tangoui/tango/ui"
    "github.com/tangoui/tango/ui/editor"
    editortheme "github.com/tangoui/tango/ui/editor/theme"
    "github.com/tangoui/tango/ui/layout"
)

var (
    activeFile = "main.go"
    fileStates = map[string]*editor.State{}
    fileText = map[string]string{
        "main.go": "package main\n\nfunc main() {}\n",
        "app.ts":  "export const ready: boolean = true;\n",
    }
)

func stateFor(file string) *editor.State {
    if st := fileStates[file]; st != nil {
        return st
    }
    st := editor.NewView(editor.NewModel(file, fileText[file], editor.DefaultRegistry()), editortheme.Base("vs"))
    fileStates[file] = st
    return st
}

func page(c *ui.Context) {
    editor.View(c, stateFor(activeFile)).LineNumbers(true).Layout(layout.H(300))
}

func main() {}

文件关闭时遍历对应的 State 调用 Close();如果只是暂时切换文件,保留状态对象即可。

接收编辑变化并自定义布局 ​

Changed() 表示当前帧发生了文本编辑、撤销或重做。Layout 接收普通布局选项,可以把编辑器放进固定高度、可增长的列或卡片内容区。

go
package main

import (
    "github.com/tangoui/tango/ui"
    "github.com/tangoui/tango/ui/editor"
    editortheme "github.com/tangoui/tango/ui/editor/theme"
    "github.com/tangoui/tango/ui/layout"
)

var changedState = editor.NewView(
    editor.NewModel("note.txt", "先编辑这段文本。\n", editor.DefaultRegistry()),
    editortheme.Base("vs"),
)

func page(c *ui.Context) {
    view := editor.View(c, changedState).Layout(layout.H(220), layout.Grow(1))
    if view.Changed() {
        markDocumentDirty()
    }
    if view.Focused() {
        ui.Text(c, "编辑器已聚焦").Tertiary()
    }
}

func markDocumentDirty() {}

func main() {}

Changed() 应在渲染同一帧中读取;实际保存内容时从 changedState.Snapshot() 取得快照,而不是依赖渲染层的临时文本。

处理编辑器中的链接 ​

编辑器会识别文档中的链接。macOS 上按住 Cmd 点击链接,其他平台按住 Ctrl 点击,OnOpenLink 会收到 URL。应用决定打开位置。视图会保留最后一次设置的回调,OnOpenLink(nil) 关闭该动作。

go
package main

import (
    "github.com/tangoui/tango/ui"
    "github.com/tangoui/tango/ui/editor"
    editortheme "github.com/tangoui/tango/ui/editor/theme"
)

var linkState = editor.NewView(
    editor.NewModel("README.md", "查看 https://tangoui.example/docs\n", editor.DefaultRegistry()),
    editortheme.Base("vs"),
)

func page(c *ui.Context) {
    editor.View(c, linkState).OnOpenLink(func(url string) {
        openURL(url)
    })
}

func openURL(url string) {}

func main() {}

不要在回调中无条件执行外部命令;生产应用应按允许的协议和域名校验 URL。

主题与样式 ​

editor.NewView 接收 *theme.Theme,常用 editortheme.Base("vs") 或 editortheme.Base("vs-dark");编辑器会据此绘制语法颜色和背景。LineNumbers、FontSize、TabSize、ReadOnly 是视图级修饰器,Keymap 和 Context 用于高级快捷键集成。编辑器不是普通表单控件,不读取 theme.Components 的输入框令牌。

注意事项 ​

  • Model、State 和高亮器要在稳定状态中复用;每帧调用 NewView 会丢失光标、撤销历史和滚动位置。
  • 大文档只在可见行附近布局和着色;应用层不要在每帧复制完整文本。需要保存时使用 Snapshot()。
  • UI 线程驱动 State,异步加载或保存完成后通过页面的失效机制唤醒 UI,不要从后台 goroutine 直接修改选区。
  • ReadOnly 不是安全边界;保存或执行代码前仍应在应用层做权限检查。自定义语义包装可使用 view.Box() 设置 A11yLabel。
  • 视图关闭时调用 State.Close();多个 State 共享 Model 时,只有所有视图都不再使用后才释放 Model。

示例代码 ​

以下是上方在线演示运行的 Go 源码(来自官方 gallery),点击标题展开。函数接收的 c *ui.Context 由窗口的 UI 循环每帧传入,接入方式见 Go GUI 入门。

CodeEditor 代码编辑器

gallery 演示 CodeEditor 的 Render 函数,源码 page_code_editor.go#L186。

加载中…

CodeEditor 大文档与虚拟滚动

gallery 演示 CodeEditorLarge 的 Render 函数,源码 page_code_editor.go#L200。

加载中…

API ​

签名与说明由 site/tools/compdoc 从 Go 源码和文档注释提取;点击名称跳到 Go API 参考 的对应条目。

入口函数 ​

editor.View ​

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

View shows st. The application holds st; the View sets st.Viewport's measured sizes and scrolls it.

返回 *ViewW,可链式调用的方法见 ViewW 方法。

相关类型与成员 ​

editor.Model ​

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.

editor.State ​

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.

ViewW 方法 ​

editor.ViewW: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.

方法说明签名
BoxBox returns the view's box (ID, rect).Box() *ui.Box
ChangedChanged reports whether the text was edited through the View this frame.Changed() bool
CompletionAnchorCompletionAnchor returns the primary caret's rectangle in UI logical coordinates, using the current caret and the last laid-out viewport.CompletionAnchor() (geom.Rect, bool)
CompletionKeysCompletionKeys gives an open completion list keyboard control while this writable view has focus.CompletionKeys(count int, selected *int, accept func(int), dismiss func()) *ViewW
ContextContext 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.Context(fn func(key string) (any, bool)) *ViewW
FocusedFocused reports whether the view has keyboard focus.Focused() bool
FoldingProviderFoldingProvider sets the provider of the folding ranges (milestone 3: the language server), used while Options.FoldingStrategy is "auto"; nil restores the built-in strategy.FoldingProvider(p FoldingRangeProvider) *ViewW
FontSizeFontSize sets the font size in logical pixels this frame (default: st.Options.FontSize); values <= 0 are ignored.FontSize(px float32) *ViewW
GlyphMarginLineAtPointGlyphMarginLineAtPoint maps a point in the dedicated glyph margin to a zero-based document line.GlyphMarginLineAtPoint(p geom.Point) (int, bool)
GutterLineAtPointGutterLineAtPoint maps a point in the laid-out gutter to a zero-based document line.GutterLineAtPoint(p geom.Point) (int, bool)
HoverOffsetHoverOffset reports the nearest UTF-8 byte offset underneath the pointer when it is over the view's visible text area.HoverOffset() (int, bool)
InlayHintAtPointInlayHintAtPoint returns the source byte offset of the rendered hint at a UI logical point.InlayHintAtPoint(p geom.Point) (int, bool)
KeymapKeymap 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).Keymap(km *keymap.Keymap) *ViewW
LayoutLayout applies layout options to the view's box (it grows by default).Layout(opts ...layout.Option) *ViewW
LineNumbersLineNumbers shows or hides the line numbers this frame (default: st.Options.LineNumbers).LineNumbers(on bool) *ViewW
LineNumbersFuncLineNumbersFunc 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).LineNumbersFunc(fn LineNumberFunc, maxChars int, gen uint64) *ViewW
MenuItemsMenuItems 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.MenuItems(items ...MenuItem) *ViewW
MountContentMountContent builds an overlay at a document offset, for example a rich hover or a quick-fix affordance.MountContent(offset int, place ui.Placement, body func(), opts ...layout.Option) *ui.Box
MountFindMountFind mounts a caller-owned find/replace panel at the editor's top right.MountFind(body func(), opts ...layout.Option) *ui.Box
OffsetAnchorOffsetAnchor returns the visible character position at a UTF-8 byte offset in window logical coordinates.OffsetAnchor(offset int) (geom.Rect, bool)
OffsetAtPointoffsetAt 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(p geom.Point) (int, bool)
OnDocumentChangeOnDocumentChange observes each document change made by this view while it processes input, including undo and redo.OnDocumentChange(fn func(ModelChange)) *ViewW
OnGlyphMarginClickOnGlyphMarginClick handles primary clicks and secondary presses inside the dedicated glyph margin.OnGlyphMarginClick(fn func(GutterClick)) *ViewW
OnGutterClickOnGutterClick handles primary clicks and secondary presses in the gutter.OnGutterClick(fn func(GutterClick)) *ViewW
OnOpenLinkOnOpenLink sets the function a Cmd+click (Ctrl+click elsewhere) on a link calls with its URL (Monaco's LinkDetector opening the link).OnOpenLink(fn func(url string)) *ViewW
OnPasteImageOnPasteImage sets the fallback when Paste finds no clipboard text.OnPasteImage(fn func() bool) *ViewW
ReadOnlyReadOnly makes the view refuse edits this frame (typing, deleting, Enter, Tab, paste, cut, undo, redo, IME); the caret, selection, navigation and copy keep working.ReadOnly(on bool) *ViewW
SuggestSuggest mounts a scrolling completion list at the caret, with an optional adjacent details pane.Suggest(o SuggestOptions) *ui.Box
TabSizeTabSize 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.TabSize(n int) *ViewW

Model 方法 ​

editor.Model: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.

方法说明签名
BufferBuffer returns the text and undo history.Buffer() *buffer.Buffer
ConfConf returns the language configuration, nil for plain text.Conf() *langs.Conf
DecorationsDecorations 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.Decorations(owner string) []Decoration
DecorationsInDecorationsIn 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.DecorationsIn(start, end int, dst []Decoration) []Decoration
DetectIndentationDetectIndentation 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).DetectIndentation()
DroppedEditsDroppedEdits counts queued edits rejected after rebasing (for example, overlapping replacements).DroppedEdits() uint64
EOLEOL returns the line ending the document is saved with, "\n" or "\r\n" (see buffer.Snapshot.TextWithEOL).EOL() string
HighlighterHighlighter returns the Highlighter, nil while the language has no grammar (plain text; milestone 1's contract).Highlighter() *highlight.Highlighter
InsertSpacesInsertSpaces 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).InsertSpaces() bool
LanguageLanguage returns the language id, PlainText when none.Language() string
LargeFileLargeFile 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).LargeFile() bool
SetDecorationsSetDecorations replaces owner's decorations, shown in every view of the Model; no decorations remove the owner.SetDecorations(owner string, ds []Decoration)
SetEOLSetEOL 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.SetEOL(eol string)
SetInsertSpacesSetInsertSpaces sets InsertSpaces (Monaco's updateOptions({insertSpaces})); editor.action.indentationToSpaces / ToTabs set it too.SetInsertSpaces(on bool)
SetLanguageSetLanguage 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.SetLanguage(id string)
SetTabSizeSetTabSize sets the tab width (Monaco's updateOptions({tabSize})); n <= 0 means DefaultTabSize.SetTabSize(n int)
SnapshotSnapshot returns the current text.Snapshot() buffer.Snapshot
SubscribeSubscribe calls fn after every change of the Model, synchronously, until cancel is called.Subscribe(fn func(ModelChange)) (cancel func())
TabSizeTabSize returns the document's tab width in columns (Monaco's model option tabSize; detected or from ModelOptions for a new Model).TabSize() int
URIURI returns the Model's URI (the file name for NewState's private model).URI() string

State 方法 ​

editor.State: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.

字段说明类型
ModelModel is the document shown.*Model
Theme*theme.Theme
OptionsOptions are the editor's persistent settings: the application sets them (the tab size and insertSpaces are the Model's: Model.TabSize, Model.InsertSpaces).Options
SelsSels are the selections, the primary first (Monaco's getSelections()); Head is the caret.[]Selection
ViewportViewport is the scroll position and the sizes the View measured.Viewport

State 的方法:

方法说明签名
AddCursorAddCursor adds a caret at off (Alt+click); while there are other cursors, a selection containing off (ends included) is removed instead (Monaco's createCursor).AddCursor(off int)
AddSelectionToNextFindMatchAddSelectionToNextFindMatch 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).AddSelectionToNextFindMatch() (Selection, bool)
CloseClose releases the State's subscription to its Model, so the Model no longer holds or updates it.Close()
ColumnSelectColumnSelect 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.ColumnSelect(fromLine, fromCol, toLine, toCol int)
CursorRedoCursorRedo re-applies the selections CursorUndo undid (cursorRedo).CursorRedo() bool
CursorUndoCursorUndo restores the selections (and scroll position) from before the last selection change (Monaco's cursorUndo); it reports false when there is none.CursorUndo() bool
DecorationsDecorations returns the current decorations set by SetDecorations for owner on this view.Decorations(owner string) []Decoration
DeleteDelete 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.Delete(dir Direction, unit Unit)
EditEdit 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.Edit(edits []buffer.Edit, after Selection) error
ExecuteExecute runs the registered command id with args on the State and reports whether it ran and did something.Execute(id string, args any) bool
FoldedFolded returns the folded regions, by start line.Folded() []FoldingRange
FoldingRangesFoldingRanges returns the folding ranges of the current text (nil while folding is off), by start line.FoldingRanges() []FoldingRange
HiddenAreaAtHiddenAreaAt 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).HiddenAreaAt(line int) (owner string, ok bool)
HiddenAreasHiddenAreas returns the lines owner hides in this view, moved with the edits since they were set, in the order set.HiddenAreas(owner string) []LineRange
HighlighterHighlighter returns the Model's highlighter, nil for plain text.Highlighter() *highlight.Highlighter
InsertInsert replaces every selection with text (typing, paste, IME commit) and puts each caret after the inserted text, as one edit set.Insert(text string)
LargeFileLargeFile reports whether the State's Model is a large file (Model.LargeFile): folding, word wrap and the occurrences and selection highlights are off.LargeFile() bool
LineAtTopLineAtTop 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.LineAtTop() (line int, offset float32)
LineBlockLineBlock 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.LineBlock(line int) (top float64, textRows, zoneRows int)
LineTopLineTop returns the top of the first text row of model line line (0 based, clamped) in ScrollTop's coordinates (Monaco's getTopForLineNumber).LineTop(line int) float64
MoveMove moves every caret by unit in dir; with extend it extends each selection.Move(dir Direction, unit Unit, extend bool)
MoveCaretMoveCaret 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.MoveCaret(to int, extend bool)
OnDidScrollOnDidScroll 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.OnDidScroll(fn func(ScrollEvent)) (cancel func())
PrimaryPrimary returns the primary selection, Sels[0] (Monaco's getSelection()).Primary() Selection
RedoRedo 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.Redo() bool
RemoveSecondaryCursorsRemoveSecondaryCursors keeps only the primary selection (Esc).RemoveSecondaryCursors() bool
RestoreViewStateRestoreViewState 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).RestoreViewState(v ViewState)
RevealCaretRevealCaret scrolls vertically the least amount that makes the caret's view line fully visible (its top when the viewport is shorter than a line).RevealCaret()
RevealLineRevealLine scrolls vertically to show the first row of model line line (clamped; a hidden line shows where it would be) as where says.RevealLine(line int, where RevealWhere)
RevealRangeRevealRange 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.RevealRange(start, end int, where RevealWhere)
RevealXRevealX scrolls horizontally the least amount that makes content x range [x0, x1] (the caret, as measured by the View) visible.RevealX(x0, x1 float32)
RowsOfRowsOf 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.RowsOf(line int) int
SaveViewStateSaveViewState returns the editor's scroll position, selections and folded regions.SaveViewState() ViewState
ScrollByScrollBy 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).ScrollBy(dy, dx float32)
ScrollHeightScrollHeight 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.ScrollHeight() float64
ScrollLeftScrollLeft returns the horizontal scroll position in pixels.ScrollLeft() float32
ScrollTopScrollTop returns the vertical scroll position: the pixels of the document above the viewport's top edge, the top padding included.ScrollTop() float64
SelectHighlightsSelectHighlights 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.SelectHighlights() bool
SetDecorationsSetDecorations 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.SetDecorations(owner string, ds []Decoration)
SetHiddenAreasSetHiddenAreas replaces the lines owner hides in this view; no ranges remove the owner.SetHiddenAreas(owner string, rs []LineRange)
SetInlayHintsSetInlayHints replaces this view's visual hints for the given snapshot version.SetInlayHints(version uint64, hints []InlayHint) bool
SetLineAtTopSetLineAtTop 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.SetLineAtTop(line int, offset float32)
SetOverviewMarksSetOverviewMarks replaces owner's marks in this view, not in the shared Model.SetOverviewMarks(owner string, marks []OverviewMark)
SetScrollLeftSetScrollLeft scrolls horizontally to px, clamped to the content width the View last measured.SetScrollLeft(px float32)
SetScrollTopSetScrollTop scrolls vertically to px (see ScrollTop), clamped to the document (the last line may scroll up to the top).SetScrollTop(px float64)
SetSelectionsSetSelections 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.SetSelections(sels []Selection)
SetViewZonesSetViewZones replaces owner's zones in this view; no zones remove the owner.SetViewZones(owner string, zs []ViewZone)
SnapshotSnapshot returns the current text.Snapshot() buffer.Snapshot
SyntaxCommandIncompletereindentLines 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.SyntaxCommandIncomplete() bool
ToggleWordWrapToggleWordWrap 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).ToggleWordWrap()
TypeType 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).Type(text string)
UndoUndo 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.Undo() bool
ViewZonesViewZones returns owner's zones in this view, AfterLine moved with the edits since they were set, in the order set.ViewZones(owner string) []ViewZone
VisibleLinesVisibleLines returns the first and last (inclusive) view lines that are at least partly visible (the same as model lines without word wrap).VisibleLines() (first, last int)
WordWrapWordWrap returns the word wrap mode in effect: the one ToggleWordWrap set, else Options.WordWrap.WordWrap() WrapMode

相关链接 ​

以 MIT 许可发布