Documentation
¶
Overview ¶
Package extension is the contract between Emetos and its extensions (SPEC §10.15, D18).
An extension is a Go package compiled into Emetos: a folder under extensions/ that has a function of type Factory, listed in extensions.All. There is no plugin loading and no extension process. This package is the only Emetos package an extension may import (internal/archtest checks it), so everything an extension can do is in the API interface below and the interfaces it returns.
Lifetime ¶
Every window tab is a scope. Emetos calls the Factory of an extension to get a fresh Extension for each scope that needs it, once one of the ActivationEvents in its Manifest happens in that scope, and calls Activate with the Context of the activation and an API bound to the scope. The Context is cancelled when the extension is deactivated: its window tab closes, the user disables it, or Emetos quits. Everything the extension started (goroutines, timers, processes) must end with it. Everything it contributed through the API (commands, keybindings, menu items, settings, status bar items) is removed by Emetos at the same time.
Failures stay inside the extension ¶
An error returned by Activate, and a panic in any call Emetos makes into the extension (Activate, a command handler, a status bar callback, a notification action) are caught at that call. The extension is deactivated in that scope for the rest of the session, a notification says so once, and the log gets the error with its route. Other scopes, and the editor, are not touched. An error that a command handler returns is not a failure of the extension: it is the error of the command, and is shown to the user like the error of any command.
Events ¶
Extensions never call each other: they publish events and send requests through API.Events. A topic is dotted names (markdown.preview.open); an extension publishes and handles the topics under its own id and those its Manifest declares (Manifest.Events), and Emetos publishes the core events (TopicDocumentOpened and its siblings) in every workspace. The value of an event is copied as JSON, so no live object crosses and a receiver can do what it likes with what it got. Events reach the subscribers of the scope on the UI thread, later, in order; the events of fast topics (typing) arrive once per frame as one batch. A request is answered by the handler of its topic, never blocks, and calls its reply function once, with the reply or an error (EventNoHandler, EventTimeout, EventCanceled, EventHandlerFailed).
Other window tabs ¶
Events never leave their scope unless the user allowed it (SPEC §10.15 "Event sharing"). An extension that wants the events of other window tabs lists the topics in Manifest.Events.CrossTab, subscribes with FromOtherScopes (or asks with ToOtherScopes, or reads with FromScope), and the user is asked in its tab, once, whether the events of the other tab may reach it. The answer is a link in one direction; the extension is told with TopicSharingRevoked when it goes. Until there is a link nothing arrives, and a topic outside CrossTab is never asked about.
Languages ¶
An extension adds languages by declaring them: Contributes.Languages is a file system with the package.json of a VS Code extension at its root (the languages, the grammars and the settings defaults of languages) and the files it names. Emetos adds them to the registry of the process while the extension is enabled in some window tab, before any file opens, so the extension needs no code to be a language pack; the bundled languages are such extensions. Several tabs may have the extension enabled: the languages are added once and taken away when the last tab lets go of them.
A language server (Contributes.LanguageServers) is started and stopped by Emetos as part of the activation. The extension reads its state with API.LanguageServers (to show it, as the Go extension does in the status bar), restarts it, and shows its Output channel; with LanguageServerSpec.OwnUI Emetos leaves the status item and the "program not found" notification to the extension. LanguageServers().SetLauncher lets the extension decide what to run at each start (where the program is, its version, the root of the project, the options from the current settings). The extension may also ask the server for its commands and code actions (LanguageServers().Commands, ExecuteCommand and ApplyCodeAction), send it the requests of its own protocol and hear its notifications (Request, OnNotification), and edit documents (Documents().Apply). The settings of an extension may have keys of their own (Contributes.Settings: go.gopls), API.QuickPick shows a list to choose from, such as the menu of a status bar item, and API.InputBox asks for a line of text.
A second view of the workspace ¶
API.Workspace().NewHeadlessView makes a second view of the workspace that is drawn off screen: a workbench with its own focus, cursors and scroll positions over the same documents, whose pictures the extension receives (HeadlessView.OnFrame) and whose input it sends (SendKey, SendPointer, SendScroll). Remote Work (SPEC §10.18) shows the workspace to another machine with it.
An example ¶
package hello
import (
"context"
"github.com/rm4n0s/emetos/extension"
)
// New is the Factory of the extension; extensions/all.go lists it.
func New() extension.Extension { return &hello{} }
type hello struct{}
func (*hello) Manifest() extension.Manifest {
return extension.Manifest{
ID: "hello", Name: "Hello", Version: "0.1.0",
Description: "Greets the user.",
ActivationEvents: []string{extension.OnCommand("hello.greet")},
Contributes: extension.Contributes{
Commands: []extension.CommandSpec{{ID: "hello.greet", Title: "Greet", Category: "Hello"}},
},
}
}
func (*hello) Activate(ctx context.Context, api extension.API) error {
return api.Commands().Handle("hello.greet", func(ctx context.Context, args any) error {
api.Notifications().Info("Hello from " + api.Scope().Name)
return nil
})
}
The command is in the palette before the extension is activated; running it activates the extension in the scope where it was run, and then runs the handler.
Index ¶
- Constants
- Variables
- func CheckManifest(m Manifest) error
- func CheckPattern(pattern string) error
- func CheckTopic(topic string) error
- func ContentURI(scheme, path string) string
- func CoreRequestTopics() []string
- func EventValue[T any](e Event) (T, error)
- func EventValues[T any](e Event) ([]T, error)
- func GroupOfArgs(args any) int
- func MatchTopic(pattern, topic string) bool
- func OnCommand(commandID string) string
- func OnDebug(debugType string) string
- func OnEditor(kindID string) string
- func OnFile(glob string) string
- func OnLanguage(languageID string) string
- func OnView(viewID string) string
- func OnWindowTab(kind string) string
- func ParseCommandLink(dest string) (id string, args any, err error)
- func PatternWithin(pattern string, list []string) bool
- func QualifiedServerID(extensionID string, spec LanguageServerSpec) string
- func QuickDiffArgs(uri string, changes []LineChange, index int) any
- func ResourceURIs(args any) []string
- func RestartServerCommand(extensionID string) string
- func SettingValue[T any](s Settings, key string) (T, error)
- func ShowViewCommand(containerID string) string
- func SplitContentURI(uri string) (scheme, path string, ok bool)
- func SplitEvent(event string) (name, arg string)
- func StateValue[T any](s State, key string) (T, bool)
- func ToggleViewCommand(viewID string) string
- func TraceSetting(extensionID string, spec LanguageServerSpec) string
- func ValidBadge(badge string) bool
- func ValidSettingScope(scope string) bool
- func ValidSettingType(typ string) bool
- func ValidTerminalVariable(name, value string) bool
- func WithOrigin(ctx context.Context, o Origin) context.Context
- type API
- type ActionButton
- type ActiveDocument
- type ActiveEditor
- type ActiveMerge
- type AsyncEventHandler
- type Banner
- type BannerAction
- type BannerHandle
- type Banners
- type BranchCoverage
- type BreakpointSpec
- type Clipboard
- type CodeAction
- type CodeActionKinds
- type CodeActionProvider
- type CodeActionRequest
- type CodeLens
- type CodeLensProvider
- type Command
- type CommandHandler
- type CommandInfo
- type CommandSpec
- type Commands
- type CommandsExecuteReply
- type CommandsExecuteRequest
- type CommandsList
- type CompletionItem
- type CompletionKind
- type CompletionList
- type CompletionProvider
- type CompletionTrigger
- type ContentProvider
- type ContentRegistration
- type ContextKeys
- type Contributes
- type CoverageCount
- type CoverageDetails
- type Debug
- type DebugAdapter
- type DebugAdapterFactory
- type DebugAdapterKind
- type DebugAdapterTracker
- type DebugAdapterTrackerFactory
- type DebugBreakpoint
- type DebugBreakpointsChange
- type DebugConfiguration
- type DebugConfigurationProvider
- type DebugConsole
- type DebugConsoleMode
- type DebugProviderTrigger
- type DebugSession
- type DebugSessionCustomEvent
- type DebugSnippet
- type DebugStartOptions
- type DebugTarget
- type DebuggerSpec
- type DeclarationCoverage
- type Decorations
- type DefinitionProvider
- type Diagnostic
- type DialogButton
- type DialogResult
- type DialogSpec
- type DialogType
- type Dialogs
- type DiffEditorContext
- type DiffSpec
- type DocumentChange
- type DocumentCloseRequest
- type DocumentClosed
- type DocumentContent
- type DocumentEditReply
- type DocumentEditRequest
- type DocumentHandle
- type DocumentHighlight
- type DocumentHighlightProvider
- type DocumentInfo
- type DocumentOpenRequest
- type DocumentSaved
- type DocumentSelector
- type DocumentSymbol
- type DocumentSymbolProvider
- type DocumentTab
- type DocumentURIRequest
- type Documents
- type EditorActionSpec
- type EditorDecorations
- type EditorDrag
- type EditorKind
- type EditorKindSpec
- type EditorOpenOptions
- type EditorRevealReply
- type EditorRevealRequest
- type EditorSelection
- type EditorTab
- type EditorTabContent
- type Editors
- type Event
- type EventDecl
- type EventHandler
- type EventReply
- type EventSpec
- type Events
- type Extension
- type Factory
- type FileChange
- type FileChooser
- type FileChooserOptions
- type FileCoverage
- type FileDecoration
- type FileDecorationProvider
- type FileDecorations
- type FileEntry
- type FileFilter
- type FileList
- type FileReplacement
- type FileViewContent
- type FileViewOpenOptions
- type FileViewProvider
- type FileViewSpec
- type FileViewTab
- type FileViews
- type FilesChanged
- type FilesListReply
- type FilesListRequest
- type FilesPathRequest
- type FilesReadReply
- type FormattingOptions
- type FormattingProvider
- type HeadlessView
- type HistoryArg
- type HistoryItem
- type HistoryItemRef
- type HistoryOptions
- type HistoryProvider
- type HistoryRange
- type HistoryRefsChange
- type HistoryRegistration
- type HistoryStatistics
- type Hover
- type HoverProvider
- type InputBox
- type InputBoxButton
- type InputBoxOptions
- type KeyEvent
- type KeyKind
- type Keybinding
- type Keybindings
- type LanguageServerSpec
- type LanguageServers
- type Languages
- type LaunchRequest
- type LineAnnotation
- type LineChange
- type Location
- type Manifest
- type Marker
- type Markup
- type MenuItem
- type Menus
- type MergeEditorCompleted
- type MergeLabels
- type MultiDiffProvider
- type MultiDiffRegistration
- type MultiDiffResource
- type MultiDiffSpec
- type NotificationAction
- type NotificationProgress
- type NotificationSeverity
- type Notifications
- type OpenSpec
- type Origin
- type Origins
- type Output
- type OutputChannel
- type PanelViewSpec
- type Parameter
- type PointerEvent
- type PointerKind
- type Position
- type PrepareRenameResult
- type Problems
- type ProgressOptions
- type ProposedChange
- type ProposedResult
- type QuickDiffKind
- type QuickDiffProvider
- type QuickDiffRegistration
- type QuickPick
- type QuickPickItem
- type QuickPickOptions
- type Range
- type RangeEdit
- type RangeFormattingProvider
- type ReadOption
- type ReadOptions
- type ReferenceProvider
- type RenameProvider
- type ReplaceFailure
- type ReplaceReport
- type RequestOption
- type RequestOptions
- type ResourceChange
- type ResourceDecorations
- type ResourceGroup
- type ResourceGroupSpec
- type ResourceState
- type SCMArg
- type SCMInput
- type ScopeFilter
- type ScopeInfo
- type ScopeKind
- type ScrollEvent
- type Selection
- type ServerLaunch
- type ServerLauncher
- type ServerState
- type ServerStatus
- type SettingSpec
- type Settings
- type Severity
- type SharingRevoked
- type Signature
- type SignatureHelp
- type SignatureHelpProvider
- type Size
- type SourceControl
- type SourceControlSpec
- type SourceControls
- type State
- type StatementCoverage
- type StatusAlignment
- type StatusBar
- type StatusCommand
- type StatusHandle
- type StatusItem
- type StatusKind
- type SubmenuSpec
- type SubscribeOption
- type SubscribeOptions
- type TabClose
- type TasksRunReply
- type TasksRunRequest
- type TerminalContribution
- type TerminalEnvironment
- type TerminalVariables
- type TestController
- type TestItem
- type TestItemCollection
- func (c *TestItemCollection) Add(item *TestItem) error
- func (c *TestItemCollection) All() []*TestItem
- func (c *TestItemCollection) Delete(id string) bool
- func (c *TestItemCollection) Get(id string) *TestItem
- func (c *TestItemCollection) Replace(items []*TestItem) error
- func (c *TestItemCollection) Size() int
- type TestItemData
- type TestMessage
- type TestRun
- type TestRunHandler
- type TestRunKind
- type TestRunProfile
- type TestRunProfileOptions
- type TestRunRequest
- type TestStackFrame
- type TestTreeChange
- type TestTreeChangeKind
- type Tests
- type TextChange
- type TextDocument
- type TextEdit
- type TextReplacement
- type TextReplacer
- type TextSearchFile
- type TextSearchMatch
- type TextSearchOptions
- type TextSearchQuery
- type TextSearchSummary
- type Timeline
- type TimelineArg
- type TimelineItem
- type TimelineOptions
- type TimelinePaging
- type TimelineProvider
- type TimelineRegistration
- type Timelines
- type Token
- type Validation
- type ValidationLevel
- type ViewActionSpec
- type ViewContainerSpec
- type ViewContent
- type ViewDocumentChange
- type ViewHandle
- type ViewNotification
- type ViewSpec
- type ViewWelcomeSpec
- type Views
- type WatchSpec
- type WindowFocus
- type WindowTab
- type WindowTabContent
- type WindowTabKind
- type WindowTabKindSpec
- type WindowTabs
- type Workspace
- type WorkspaceEdit
- type WorkspaceInfo
Constants ¶
const ( // MenuCommandPalette is the command palette; an item whose When does not hold hides its command there. MenuCommandPalette = "CommandPalette" // MenuFile, MenuEdit, MenuSelection, MenuView, MenuGo and MenuHelp are the menus of the menu bar. MenuFile = "MenubarFileMenu" MenuEdit = "MenubarEditMenu" MenuSelection = "MenubarSelectionMenu" MenuView = "MenubarViewMenu" MenuGo = "MenubarGoMenu" MenuHelp = "MenubarHelpMenu" // MenuTerminal is the Terminal menu of the menu bar, which has an item only when an extension adds one. MenuTerminal = "MenubarTerminalMenu" // MenuEditorTabsNew is the menu of the "+" button after the last tab of an editor group, with a row for each kind of // editor that can be made; the core has New Text File, and the groups of the others are ordered after it ("2_terminal"). // An item of an extension in it runs its command with {"groupId": n}, the group whose button was pressed // (GroupOfArgs reads it), so that the editor opens in that group. The value is Emetos's own name. MenuEditorTabsNew = "EditorTabsNew" // MenuManage is the Manage menu: the gear at the bottom of the activity bar. MenuManage = "GlobalActivity" // MenuEditorContext is the context menu of the text editor. MenuEditorContext = "EditorContext" // MenuExplorerContext is the context menu of the Explorer. An item of an extension in it runs its command with // the arguments ExplorerArgs describes (ResourceURIs reads them), and its when-clause can use resourceLangId, // resourceFilename, resourceExtname and resourcePath of the row that was pressed. MenuExplorerContext = "ExplorerContext" )
The ids of the menus an extension may add items to.
const ( // TopicCommandsList answers CommandsList. TopicCommandsList = "emetos.commands.list" // TopicCommandsExecute takes CommandsExecuteRequest and answers CommandsExecuteReply. It needs PrivilegeCommandsExecute. TopicCommandsExecute = "emetos.commands.execute" // TopicFilesList takes FilesListRequest and answers FilesListReply. TopicFilesList = "emetos.files.list" // TopicFilesStat takes FilesPathRequest and answers FileEntry. TopicFilesStat = "emetos.files.stat" // TopicFilesRead takes FilesPathRequest and answers FilesReadReply. TopicFilesRead = "emetos.files.read" // TopicDocumentOpen takes DocumentOpenRequest and answers DocumentInfo. TopicDocumentOpen = "emetos.document.open" // TopicDocumentRead takes DocumentURIRequest and answers DocumentContent. TopicDocumentRead = "emetos.document.read" // TopicDocumentEdit takes DocumentEditRequest and answers DocumentEditReply. TopicDocumentEdit = "emetos.document.edit" // TopicDocumentSave takes DocumentURIRequest and answers DocumentSaved. TopicDocumentSave = "emetos.document.save" // TopicDocumentClose takes DocumentCloseRequest and answers DocumentClosed. TopicDocumentClose = "emetos.document.close" // TopicEditorReveal takes EditorRevealRequest and answers EditorRevealReply. TopicEditorReveal = "emetos.editor.reveal" )
The core request topics (SPEC §10.19 "Core request topics"): Emetos itself answers them, in the scope of every workspace window tab, for every extension. A window tab of an extension has no answer to them (EventNoHandler). Their errors reach the requester as they are, with the tag of the failure (not wrapped in EventHandlerFailed).
const ( // MaxFilesReadSize is the most bytes TopicFilesRead returns; a larger file fails with CoreFileTooLarge. A request may // ask for less (FilesPathRequest.MaxBytes). MaxFilesReadSize = 2 << 20 // DefaultFilesListLimit and MaxFilesListLimit are the entries a TopicFilesList reply holds when the request names no // limit, and at most. DefaultFilesListLimit = 1000 MaxFilesListLimit = 5000 // MaxFilesListDepth is the deepest a TopicFilesList may go; the default depth is 1 (the children of the folder). MaxFilesListDepth = 16 // MaxDocumentReadSize is the most bytes of text TopicDocumentRead returns (CoreDocumentTooLarge above it). MaxDocumentReadSize = 8 << 20 // MaxDocumentEdits and MaxDocumentEditBytes are the most edits, and the most bytes of replacement text, of one // TopicDocumentEdit (CoreEditTooLarge above them). MaxDocumentEdits = 10000 MaxDocumentEditBytes = 4 << 20 )
The limits of the core request topics.
const ( // RefusedWindowTab: the commands of the workspace tabs and the window tabs (emetos.workspaceTab.*, emetos.windowTab.*). RefusedWindowTab = "windowTab" // RefusedQuit: quitting Emetos and closing the window. RefusedQuit = "quit" // RefusedWindow: new windows and switching windows, and the terminal program of the desktop (scm.openInTerminal), which would open // a window on the screen of the host that the client does not see (the integrated terminal is the client's own, D51). RefusedWindow = "window" // RefusedFolder: opening, replacing or closing the folder, and the lists of recent folders and files. RefusedFolder = "folder" // RefusedProfile: the profiles. RefusedProfile = "profile" // RefusedSettings: commands that open or write the settings, the keybindings or the themes of the user or the profile // (the settings of the workspace are allowed), and the links between window tabs. RefusedSettings = "settings" // RefusedRemote: the commands of the extensions that share a workspace or control another one. RefusedRemote = "remote" // RefusedOutside: the commands of the extensions that reach outside the workspace: the databases a connection names, and (the // container extensions, M18) the engine's socket. A client has no say in what the host connects to (SPEC §10.24). RefusedOutside = "outside" )
The reasons a command is refused to the clients of a workspace (CommandInfo.RefusedClass), SPEC §10.19 "Confinement".
const ( // EntryFile, EntryDir and EntrySymlink are a regular file, a folder and a symbolic link (listed, never followed). // EntryOther is a fifo, a socket or a device, which no topic reads. EntryFile = "file" EntryDir = "dir" EntrySymlink = "symlink" EntryOther = "other" )
The kinds of FileEntry.
const ( // TopicDocumentOpened: a document was opened or restored in the workspace. Payload DocumentInfo. TopicDocumentOpened = "emetos.document.opened" // TopicDocumentChanged: the text of a document changed. A fast topic. Payload DocumentChange. TopicDocumentChanged = "emetos.document.changed" // TopicDocumentSaved: a document was written to disk. Payload DocumentSaved. TopicDocumentSaved = "emetos.document.saved" // TopicDocumentClosed: a document was closed. Payload DocumentClosed. TopicDocumentClosed = "emetos.document.closed" // TopicEditorActiveChanged: another text editor became the active one, or none is. Payload ActiveEditor. TopicEditorActiveChanged = "emetos.editor.activeChanged" // TopicEditorSelectionChanged: the selections of the active editor changed. A fast topic. Payload EditorSelection. TopicEditorSelectionChanged = "emetos.editor.selectionChanged" // TopicWorkspaceOpened: the workspace of the scope was opened (published once, after the extensions that start with // it were activated). Payload WorkspaceInfo. TopicWorkspaceOpened = "emetos.workspace.opened" // TopicWorkspaceClosed: the workspace of the scope is closing; subscribers get it before they are deactivated. // Payload WorkspaceInfo. TopicWorkspaceClosed = "emetos.workspace.closed" // TopicWindowTabActivated: the window tab of the scope became the one the window shows. Payload WorkspaceInfo. TopicWindowTabActivated = "emetos.windowTab.activated" // TopicFilesChanged: files of the folder of the workspace were created, changed, deleted or renamed, as the watcher // of the folder saw it, or the list of files that Workspace().Files gives changed. Payload FilesChanged. It is not // published for a workspace with no folder. TopicFilesChanged = "emetos.files.changed" // TopicWindowFocusChanged: the window gained or lost the keyboard focus (as the desktop says it); the Git extension // refreshes when it comes back. Published in the scope of the active window tab only. Payload WindowFocus. TopicWindowFocusChanged = "emetos.window.focusChanged" // TopicMergeEditorCompleted: the user completed a merge in the merge editor (Complete Merge): the result was saved and the editor is // closing. The Git extension stages the file on it. Payload MergeEditorCompleted. Published in the scope of the window tab that has // the merge editor. TopicMergeEditorCompleted = "emetos.mergeEditor.completed" // TopicSharingRevoked: a link that let the events of another window tab reach this one was removed, or that tab // became private. It is published in the receiving tab. Payload SharingRevoked. TopicSharingRevoked = "emetos.sharing.revoked" )
The core events Emetos publishes in every workspace scope (SPEC §10.15). The payload of each is a JSON object; the types below describe them.
const ( // FileCreated: a new file. FileChanged: a file whose content changed. FileDeleted: a file or a folder that is gone. FileCreated = "created" FileChanged = "changed" FileDeleted = "deleted" // FileRenamed: an item moved from OldPath to Path. FileRenamed = "renamed" // FileRescan: events were lost below Path (or a folder was deleted or renamed): read everything below it again. FileRescan = "rescan" // FileListed: the list of files that Workspace().Files gives changed (the walk of the folder found more files or // ended): read it again. Path is empty. FileListed = "listed" )
The kinds of FileChange.
const ( // RevokedLinkRemoved: the user removed the link (Extensions > Event Sharing). RevokedLinkRemoved = "removed" // RevokedPrivate: the tab the events came from was made private. RevokedPrivate = "private" )
The reasons of a SharingRevoked.
const ( MaxHeadlessPixels = 3840 * 2160 MaxHeadlessSide = 7680 )
MaxHeadlessPixels is the area of the largest headless view, in pixels (a 4K display), and MaxHeadlessSide the longest side it may have.
const ( // ButtonPrimary is the left button. ButtonPrimary uint8 = 1 << iota // ButtonSecondary is the right button. ButtonSecondary // ButtonMiddle is the wheel button. ButtonMiddle )
The bits of PointerEvent.Buttons.
const ( // HistoryArgItem is the history item the menu is for. HistoryArgItem = "historyItem" // HistoryArgRef is the ID of the reference a menu of a badge is for. HistoryArgRef = "historyItemRef" // HistoryArgRange is the range of changes an incoming or outgoing row opens. HistoryArgRange = "historyRange" )
The members of the arguments that a menu of the Graph gives a command (HistoryArgs).
const ( // LineChangeOriginalStart is OriginalStartLineNumber. LineChangeOriginalStart = "originalStartLineNumber" // LineChangeOriginalEnd is OriginalEndLineNumber. LineChangeOriginalEnd = "originalEndLineNumber" // LineChangeModifiedStart is ModifiedStartLineNumber. LineChangeModifiedStart = "modifiedStartLineNumber" // LineChangeModifiedEnd is ModifiedEndLineNumber. LineChangeModifiedEnd = "modifiedEndLineNumber" )
The members of a LineChange as the arguments of a command carry it (VS Code's names).
const ( // DiffArgOriginalURI is the URI of the original document of the diff editor. DiffArgOriginalURI = "originalUri" // DiffArgModifiedURI is the URI of the modified document of the diff editor. DiffArgModifiedURI = "modifiedUri" // DiffArgOriginalWithModifiedChanges is the original text with the changes of the hunk, or of the selection, applied. DiffArgOriginalWithModifiedChanges = "originalWithModifiedChanges" )
The members of the arguments the toolbars of the diff editor's gutter give a command (DiffEditorContext).
const ( // ExplorerArgURI and ExplorerArgURIs are the names of the two members. ExplorerArgURI = "uri" ExplorerArgURIs = "uris" )
ExplorerArgs are the arguments of a command that the context menu of the Explorer (MenuExplorerContext) runs, when the command is an extension's (SPEC §10.15 "Menus", step 18.3): {"uri": "file:///path", "uris": ["file:///path", ...]}. uri is the row that was pressed (the folder of the workspace when the empty part of the tree was), uris are the rows the command works on: the whole selection when the pressed row is one of them, else the pressed row alone. A menu item whose own Args are an object keeps them: the two members are added to it.
const ( // MenuSCMTitle is the title bar of the Source Control view and of each repository header (scm/title). MenuSCMTitle = "SCMTitle" // MenuSCMRepository is the actions inline in the header of a repository (scm/repository). MenuSCMRepository = "SCMSourceControlInline" // MenuSCMSourceControl is the context menu of a repository (scm/sourceControl). MenuSCMSourceControl = "SCMSourceControl" // MenuSCMResourceGroupContext is the actions and the context menu of a group (scm/resourceGroup/context). MenuSCMResourceGroupContext = "SCMResourceGroupContext" // MenuSCMResourceStateContext is the actions and the context menu of a resource (scm/resourceState/context). MenuSCMResourceStateContext = "SCMResourceContext" // MenuSCMResourceFolderContext is the actions and the context menu of a folder in the tree view (scm/resourceFolder/context). MenuSCMResourceFolderContext = "SCMResourceFolderContext" // MenuSCMChangeTitle is the title bar of the peek of a change (scm/change/title). MenuSCMChangeTitle = "SCMChangeContext" // MenuSCMHistoryTitle is the title bar of the Graph view (scm/history/title). MenuSCMHistoryTitle = "SCMHistoryTitle" // MenuSCMHistoryItemContext is the context menu of a commit of the Graph (scm/historyItem/context). MenuSCMHistoryItemContext = "SCMHistoryItemContext" // MenuSCMHistoryItemRefContext is the context menu of a branch or tag badge of the Graph (scm/historyItemRef/context). MenuSCMHistoryItemRefContext = "SCMHistoryItemRefContext" // MenuTimelineItemContext is the context menu of an item of the Timeline view (timeline/item/context). MenuTimelineItemContext = "TimelineItemContext" // MenuEditorContent is the prominent buttons over the content of an editor (editor/content). MenuEditorContent = "EditorContent" // MenuEditorTitle is the actions in the title bar of an editor (editor/title). MenuEditorTitle = "EditorTitle" // MenuMultiDiffFileToolbar is the actions in the header of a file of the multi-file diff editor (multiDiffEditor/resource/title); // they are read with the Context of the MultiDiffResource and run with its Args. MenuMultiDiffFileToolbar = "MultiDiffEditorFileToolbar" // MenuDiffEditorGutterHunk is the toolbar in the gutter of a hunk of the diff editor (diffEditor/gutter/hunk). MenuDiffEditorGutterHunk = "DiffEditorHunkToolbar" // MenuDiffEditorGutterSelection is the toolbar in the gutter of a selection of the diff editor (diffEditor/gutter/selection). MenuDiffEditorGutterSelection = "DiffEditorSelectionToolbar" )
The ids of the menus of the Source Control view and of the places that Git adds to; the values are the MenuId names of VS Code's workbench, as the other Menu constants (the contribution points of a VS Code package.json, scm/title and the like, are named by the keys of its menus).
const ( // SCMArgSourceControl is the Handle of the source control. SCMArgSourceControl = "sourceControl" // SCMArgGroup is the ID of the group of a group or a resource. SCMArgGroup = "group" // SCMArgURI is the URI of a resource. SCMArgURI = "uri" // SCMArgContextValue is the ContextValue of a group or a resource. SCMArgContextValue = "contextValue" )
The members of the arguments that a menu of the Source Control view gives a command (SCMArgs).
const ( // TimelineArgSource is the ID of the provider of the item. TimelineArgSource = "source" // TimelineArgID is the ID of the item. TimelineArgID = "id" // TimelineArgURI is the URI of the file whose history the view shows. TimelineArgURI = "uri" // TimelineArgContextValue is the ContextValue of the item. TimelineArgContextValue = "contextValue" // TimelineArgArgs is the Args of the item. TimelineArgArgs = "args" // TimelineArgLabel is the Label of the item. TimelineArgLabel = "label" )
The members of an argument that a menu of the Timeline view gives a command (TimelineArgs).
const ContentScheme = "emetos-virtual:"
ContentScheme is the start of the URI of the read-only documents an extension provides (SPEC §7.1, §10.30): the document of the scheme "git" with the path "abc/HEAD/src/a.go" is "emetos-virtual:/git/abc/HEAD/src/a.go". The scheme is also what the context key resourceScheme holds for such a document, so that the when-clauses of VS Code's git extension (resourceScheme == git) work.
const CorePublisher = "emetos"
CorePublisher is the Publisher of the core events.
const MaxFileChanges = 500
MaxFileChanges is the most changes a FilesChanged carries.
const MaxLineAnnotationHover = 64 * 1024
MaxLineAnnotationHover is how many bytes the markdown of a hover may have; a longer one is cut.
const MaxLineAnnotationText = 1000
MaxLineAnnotationText is how many runes of the text of an annotation are kept; a longer text is cut (the editor clips it at the edge of the editor anyway).
const MaxLineAnnotations = 10000
MaxLineAnnotations is how many annotations one Set may give; more makes the call fail with ExtensionEditorDecorationsInvalid.
const MaxReadFileSize = 2 << 20
MaxReadFileSize is the largest file Workspace().ReadFile reads.
const MultiDiffKindPattern = `^[A-Za-z][A-Za-z0-9.-]*$`
MultiDiffKindPattern is what the Kind of a MultiDiffProvider looks like: a word of letters, digits, dots and hyphens that starts with a letter ("git.changes").
const (
// OnStartup activates the extension when a scope is made.
OnStartup = "onStartup"
)
The activation events of a Manifest.
const ( // PrivilegeCommandsExecute lets the extension run commands, those of Emetos and those of every extension, in its // scope, with the core request topic TopicCommandsExecute. The commands that reach outside the workspace stay refused // (CoreCommandRefused). PrivilegeCommandsExecute = "commands.execute" )
The privileges of a Manifest (SPEC §10.19 "Privileges"). The host grants them only to the extensions on its fixed allowlist (emetos.terminal); they lift a rule inside the extension's own scope and never reach another scope.
const TagContentBinary = "ContentBinary"
TagContentBinary is the tag of the error that a ContentProvider's Text returns for content that is not text. The window shows the notice it shows for a file that looks binary ("The file is not displayed in the editor because it is either binary or uses an unsupported text encoding.") and opens nothing. An extension makes the error with its own tag name and passes the tag "ContentBinary"; the window finds it with errors.Is on a value of this tag.
const TagMultiDiffGone = "MultiDiffGone"
TagMultiDiffGone is the tag of the error that a MultiDiffProvider's Resources returns for a set that is not there any more (the repository was closed, the commit was dropped). The window closes the tab of the set without a word, as it drops the diff of a repository that is gone; any other error is shown in the tab. An extension makes the error with its own tag name and passes the tag "MultiDiffGone"; the window finds it with errors.Is on a value of this tag.
const TasksID = "emetos.tasks"
TasksID is the id of the Tasks extension. It is activated by its commands and its tab, so a requester that is not the user (the window, for a debug session) activates it first (exthost.Scope.Activate).
const TerminalID = "emetos.terminal"
TerminalID is the id of the Terminal extension, which the host grants PrivilegeCommandsExecute (and no other privilege), for the commands of VS Code's terminal that run a command of another extension (workbench.action.terminal.searchWorkspace).
const TestNoDuration time.Duration = -1
TestNoDuration is the duration of a result that has none (VS Code's undefined).
const TopicTasksRun = "emetos.tasks.runTask"
TopicTasksRun is the request that runs a task of the Tasks extension (emetos.tasks): it takes TasksRunRequest and answers TasksRunReply when the task has ended. The reply takes as long as the task does, so the requester gives the request a context with a deadline that fits (a request without one is answered with EventTimeout after 10 seconds); cancelling the context stops the task. It fails with EventNoHandler when the Tasks extension is not running, and the handler's own errors are the tags TaskNotFound, TaskBusy, TaskNoFolder, TaskStartFailed and TaskRequestInvalid.
Variables ¶
var ErrDebugOpenLaunchJSON = &errors.Error{Tag: "DebugOpenLaunchFile"}
ErrDebugOpenLaunchJSON is what a Resolve function returns to cancel the launch and have launch.json shown (VS Code's null result). It has the tag of the host's own sentinel, so that errors.Is finds it.
Functions ¶
func CheckManifest ¶
CheckManifest checks a manifest the way Emetos does before it keeps an extension: the id, the name and the activation events and the topics it declares. An extension's own test can call it. The errors have the tags ExtensionIDInvalid, ExtensionIDReserved, ExtensionNameMissing, ExtensionEventInvalid (an unknown event, onStartup with an argument, an event that takes an argument without one), and EventTopicInvalid or EventPatternInvalid for a topic or pattern the manifest declares that is malformed, and ExtensionWindowTabIDForeign, ExtensionWindowTabDuplicate and ExtensionWindowTabInvalid for the window tab kinds, and ExtensionServerInvalid and ExtensionServerDuplicate for the language servers, and ExtensionSettingDeclInvalid and ExtensionSettingDeclDuplicate for the settings it declares, and ExtensionPrivilegeUnknown for a privilege that is none of the two, and ExtensionContextKeyDeclInvalid for a context key it declares that is not a word or words joined by dots or is declared twice, and ExtensionContextKeyDeclForeign for one under emetos. that is not under its own id, and ExtensionSubmenuInvalid, ExtensionSubmenuDuplicate and ExtensionMenuItemInvalid for the submenus and the menu items that open one, and ExtensionViewWelcomeInvalid for welcome content that names no view or has no contents, and ExtensionDebuggerInvalid and ExtensionDebuggerDuplicate for the debuggers and ExtensionBreakpointInvalid for the breakpoint languages.
func CheckPattern ¶
CheckPattern checks a subscription pattern: a topic whose segments may be * (any one segment), and whose last segment may be ** (one or more segments, however many). The error has the tag EventPatternInvalid.
func CheckTopic ¶
CheckTopic checks the name of a topic: one or more segments of letters, digits, hyphens and underscores joined by dots. The error has the tag EventTopicInvalid.
func ContentURI ¶
ContentURI is the URI of the document of a scheme and a path: ContentURI("git", "abc/HEAD/a.go") is "emetos-virtual:/git/abc/HEAD/a.go".
func CoreRequestTopics ¶
func CoreRequestTopics() []string
CoreRequestTopics lists the core request topics.
func EventValue ¶
EventValue decodes the value of the event as a T.
func EventValues ¶
EventValues decodes every value of the event as a T: the values of a batch, oldest first, or the one value of an event that is not a batch.
func GroupOfArgs ¶
GroupOfArgs reads the group an editor title action was run for from the argument of its command: {"groupId": n}. It is 0 for any other argument (the command was not run from an icon), which means the active group.
func MatchTopic ¶
MatchTopic tells whether a topic matches a pattern (CheckPattern). Both must be valid; an invalid one matches nothing.
func OnDebug ¶
OnDebug is the event of a debugger of the debug type being needed: a configuration of the type is resolved or started, its initial or dynamic configurations are asked for, or a tracker of its sessions is wanted (VS Code's onDebugResolve, onDebugInitialConfigurations, onDebugDynamicConfigurations and onDebugAdapterProtocolTracker in one). An extension that declares the debugger is activated by it without listing it.
func OnEditor ¶
OnEditor is the event of a tab of the editor kind with the id being shown (a restored tab, or one that is opened); an extension that declares the kind is activated by it without listing it.
func OnFile ¶
OnFile is the event of a file whose path relative to the folder of the scope matches the glob being in the folder: OnFile("go.mod") for a go.mod in the root, OnFile("**/go.mod") for one anywhere. It never happens in a scope with no folder.
func OnLanguage ¶
OnLanguage is the event of a document of the language with the id (go, markdown) being open in the scope.
func OnView ¶
OnView is the event of the view with the id being shown (from the step that adds views).
func OnWindowTab ¶
OnWindowTab is the event of a window tab of the kind with the id being opened or restored; an extension that declares the kind is activated by it without listing it.
func ParseCommandLink ¶
ParseCommandLink reads a link of a hover of the form command:<id> or command:<id>?<arguments>, where the arguments are JSON, percent-encoded as VS Code's encodeURIComponent does: an array is the list of the arguments (one argument is returned as it is, none as nil), any other value is the argument. It fails with ExtensionCommandLinkInvalid for a destination that is not a command link, one with no command id and arguments that are not JSON.
func PatternWithin ¶
PatternWithin tells whether every topic that pattern matches is matched by one of the patterns in list: the pattern is within the list. A topic is a pattern that matches itself. Invalid patterns are within nothing.
func QualifiedServerID ¶
func QualifiedServerID(extensionID string, spec LanguageServerSpec) string
QualifiedServerID is the id of a server in Emetos: the id of the extension, a dot and the ID of the spec.
func QuickDiffArgs ¶
func QuickDiffArgs(uri string, changes []LineChange, index int) any
QuickDiffArgs makes the arguments the commands of the peek of a change (MenuSCMChangeTitle) are run with: the URI of the file, the changes of the provider the shown change belongs to, and the index of the shown change among them (VS Code passes the three as separate arguments; Emetos gives the command one list, as for SCMArgs).
func ResourceURIs ¶
ResourceURIs reads the files or folders a command works on from the arguments the Explorer's context menu gave it: the URIs of the selected rows, the pressed one first; the one URI of the member "uri" when there is no list; nothing for any other argument (the command was run from the palette or from another menu).
func RestartServerCommand ¶
RestartServerCommand is the id of the command that restarts the servers of an extension in the tab (Emetos registers it for an extension that declares servers): the id of the extension and ".restartServer".
func SettingValue ¶
SettingValue reads a setting as a Go type: a string, a bool, a float64, an int, a []string, or a struct or map that the JSON of the value decodes into.
func ShowViewCommand ¶
ShowViewCommand is the id of the command that shows a side bar view container and its views: workbench.view.extension. followed by the id of the container. Emetos adds it for every container an extension declares, with the title "Show <Title>" in the command palette.
func SplitContentURI ¶
SplitContentURI is the reverse of ContentURI: the scheme and the path of a URI of provided content; false for any other URI.
func SplitEvent ¶
SplitEvent splits an activation event into its name and argument: "onLanguage:go" is ("onLanguage", "go"), and "onStartup" is ("onStartup", "").
func StateValue ¶
StateValue is the value kept under the key decoded into T, and whether there is one of that shape: a value that does not decode into T is no value.
func ToggleViewCommand ¶
ToggleViewCommand is the id of the command that shows a panel view with the focus, or hides the panel when the view has it: workbench.panel.extension. followed by the id of the view and .toggle.
func TraceSetting ¶
func TraceSetting(extensionID string, spec LanguageServerSpec) string
TraceSetting is the key of the setting that says how much of the traffic with the server is written to its Output channel: off, messages (the method and id of each message) or verbose (the messages with their bodies). Emetos registers it for every server.
func ValidBadge ¶
ValidBadge says whether a badge is allowed: empty, or at most two characters.
func ValidSettingScope ¶
ValidSettingScope tells whether the scope is one a SettingSpec may have.
func ValidSettingType ¶
ValidSettingType tells whether the type is one a SettingSpec may have: string, number, integer, boolean, array or object.
func ValidTerminalVariable ¶
ValidTerminalVariable tells whether name=value can be put in an environment: the name is not empty, has no "=" and no NUL, and the value has no NUL.
func WithOrigin ¶
WithOrigin returns a context that carries the origin of the screen that asked for the work the context belongs to. The host puts the screen that pressed F5 in the context of the functions it calls for a debug session's start (the configuration providers), because they run on a goroutine of their own, where Origins().Current is HostOrigin; a provider that asks a question passes OriginFromContext(ctx) as the Origin of the quick pick or input box, so that it shows where the person who started the session is looking (SPEC §10.31).
Types ¶
type API ¶
type API interface {
// Scope describes the scope the API is bound to.
Scope() ScopeInfo
// Log is the logger of the extension: its lines carry the id of the extension and the scope, and go to the log of
// Emetos.
Log() *slog.Logger
// Commands registers commands and their handlers.
Commands() Commands
// Keybindings adds default keybindings.
Keybindings() Keybindings
// Menus adds menu items.
Menus() Menus
// Settings registers and reads settings.
Settings() Settings
// Notifications shows notifications.
Notifications() Notifications
// StatusBar adds items to the status bar of the scope.
StatusBar() StatusBar
// Documents reads the documents of the scope.
Documents() Documents
// Views gives the views the manifest declares (side bar and panel) their content.
Views() Views
// Output makes channels of the Output panel.
Output() Output
// Problems sets markers in the Problems panel.
Problems() Problems
// Workspace reads the folder of the workspace.
Workspace() Workspace
// Context sets context keys.
Context() ContextKeys
// Editors makes the tabs of the editor area of the kinds the manifest declares.
Editors() Editors
// FileViews gives the file views the manifest declares their content.
FileViews() FileViews
// Debug starts and follows debug sessions and registers the code of the debuggers the manifest declares (SPEC §10.31).
Debug() Debug
// Tests makes test controllers: the tests an extension finds, how to run them, and what a run reports (SPEC §10.32).
Tests() Tests
// Languages gives the grammars of the languages, for highlighting.
Languages() Languages
// LanguageServers follows and controls the language servers the manifest declares.
LanguageServers() LanguageServers
// QuickPick shows a list to choose from, the way the command palette does.
QuickPick() QuickPick
// InputBox asks the user for a line of text, the way the rename and the Save As of the window do.
InputBox() InputBox
// Banners shows banners across the top of the window tab of the scope.
Banners() Banners
// FileChooser asks the user for a file with the file dialog of the desktop.
FileChooser() FileChooser
// Clipboard writes text to the clipboard of the desktop.
Clipboard() Clipboard
// WindowTabs gives the content of the window tabs of the kinds the manifest declares; it works in the scope of such a
// tab only.
WindowTabs() WindowTabs
// Events publishes and subscribes to events and sends requests to the other extensions of the scope.
Events() Events
// SourceControl creates source controls: the repositories, groups of changes and commit input of the Source Control view
// (SPEC §10.30).
SourceControl() SourceControls
// Decorations registers the providers of the colors and badges of files (SPEC §10.30 "File decorations and the Explorer").
Decorations() Decorations
// Timeline registers the providers of the history of files that the Timeline view lists (SPEC §10.30 "The Timeline view").
Timeline() Timelines
// Dialogs asks the user a question in a modal dialog.
Dialogs() Dialogs
// EditorDecorations draws texts after the end of lines in the editors (SPEC §10.30 "Blame").
EditorDecorations() EditorDecorations
// TerminalEnvironment adds variables to the environment of the terminals the Terminal extension starts (SPEC §10.30 "Passwords and
// editors").
TerminalEnvironment() TerminalEnvironment
// State keeps small values of the extension across restarts, for the folder of the scope (SPEC §10.15 "As built (step 24b.4)").
State() State
// Origins tells where the command being handled came from, when it was run in the view of a client (SPEC §10.18, D50).
Origins() Origins
// Post runs fn on the UI thread, later; it is how a goroutine that the extension started hands its result to the
// editor. fn is not run when the extension was deactivated before its turn comes, and a panic in it deactivates the
// extension. Activate, command handlers, the callbacks of the API and the event handlers run on the UI thread already.
Post(fn func())
}
API is what an extension may do in one scope. It is bound to the scope and to the activation: after the extension is deactivated every method that changes something fails. The methods may be called from the goroutines the extension started, except Documents().Read, which reads the text of a document and belongs to the UI thread (use Post).
type ActionButton ¶
type ActionButton struct {
// Command is the primary command; its Title is the label of the button and may start with "$(icon) ".
Command Command
// Secondary are the groups of commands in the dropdown of the button, a separator between the groups.
Secondary [][]Command
// Enabled says whether the button can be pressed.
Enabled bool
// Description is the text of the tooltip.
Description string
}
ActionButton is the button under the input (VS Code's SourceControlActionButton).
type ActiveDocument ¶
type ActiveDocument struct {
// URI is the document: file:///path/to/file, untitled:1.
URI string
// LanguageID is the language of the document.
LanguageID string
// Version is the version of the text the selections are in.
Version int
// Selections are all the selections of the editor, the primary one first; an empty one is a cursor. Positions are those of
// the core events: zero-based lines and columns in bytes of the UTF-8 line.
Selections []Selection
}
ActiveDocument is the text editor in front, as Documents().Active describes it (SPEC §10.28).
type ActiveEditor ¶
type ActiveEditor struct {
URI string `json:"uri"`
LanguageID string `json:"languageId,omitempty"`
}
ActiveEditor is the payload of TopicEditorActiveChanged. URI is empty when no text editor is active (the group is empty, or the active tab shows something other than a text).
type ActiveMerge ¶
type ActiveMerge struct {
// Result is the document the merge writes: the file with the conflict markers that is being resolved (file:///path), or the result
// file of "emetos --merge".
Result string
// Markers tells that the merge is of a file with conflict markers (it is the file itself), not of the four files of "emetos --merge".
Markers bool
}
ActiveMerge is the merge editor that is in front, as Documents().ActiveMergeEditor describes it.
type AsyncEventHandler ¶
type AsyncEventHandler func(ctx context.Context, ev Event, reply EventReply)
AsyncEventHandler answers a request later: it is called on the UI thread with the event, hands the work to a goroutine if it is long, and calls reply once, from any goroutine, when it is done. A second call does nothing. A request that is not answered in time ends with EventTimeout.
type Banner ¶
type Banner struct {
// Text is the message; one line, cut with an ellipsis when it is too long.
Text string
// Icon is the name of the Codicon before the text ("remote"); empty for none.
Icon string
// Actions are the buttons at the right end.
Actions []BannerAction
}
Banner is a bar across the top of the window tab, under the title bar: an icon, a line of text and buttons. An extension shows one for something that goes on in the window tab and that the user should always see and be able to end, such as the "Remote Work: laptop B connected" banner with its Disconnect button (SPEC §10.18).
type BannerAction ¶
type BannerAction struct {
// Label is the text of the button.
Label string
// Run is called on the UI thread when the button is pressed. A panic in it deactivates the extension.
Run func()
}
BannerAction is a button of a banner.
type BannerHandle ¶
type BannerHandle interface {
// Update replaces what the banner shows. It does nothing after Dispose or the end of the activation.
Update(banner Banner)
// Dispose takes the banner away; a banner that was not disposed goes with the activation.
Dispose()
}
BannerHandle changes or removes a banner.
type Banners ¶
type Banners interface {
// Show adds a banner below the ones shown before it. It fails with ExtensionBannerInvalid for a banner with no text,
// ExtensionBannersUnavailable in a scope that has no workbench to show it in and ExtensionDeactivated after the activation
// ended. Call it on the UI thread.
Show(banner Banner) (BannerHandle, error)
}
Banners shows banners in the window tab of the scope.
type BranchCoverage ¶
type BranchCoverage struct {
// Executed is how many times the branch ran.
Executed int
// Location is where the branch is, nil for the statement's own.
Location *Range
// Label is the name of the branch.
Label string
}
BranchCoverage is a branch of a statement (VS Code's BranchCoverage).
type BreakpointSpec ¶
type BreakpointSpec struct {
// Language is the id of the language.
Language string
}
BreakpointSpec declares a language where breakpoints can be set (VS Code's contributes.breakpoints). debug.allowBreakpointsEverywhere lifts the limit.
type Clipboard ¶
type Clipboard interface {
// WriteText puts the text on the clipboard. It returns at once; a clipboard that fails is reported to the user by Emetos. It
// fails with ExtensionDeactivated after the activation ended and with ExtensionClipboardUnavailable in a scope that has
// no clipboard (a window tab that is not on screen). Call it on the UI thread.
WriteText(text string) error
}
Clipboard writes to the clipboard of the desktop. An extension cannot read it.
type CodeAction ¶
type CodeAction struct {
Title string
// Kind is quickfix, refactor, refactor.extract, source.organizeImports, ...
Kind string
Diagnostics []Diagnostic
Preferred bool
// Disabled, when not empty, is why the action cannot be applied.
Disabled string
Edit *WorkspaceEdit
Command *Command
}
CodeAction is an action the user may choose.
type CodeActionKinds ¶
type CodeActionKinds interface {
// CodeActionKinds lists the kinds the provider answers, such as "source.organizeImports". It may be called often, on any goroutine.
CodeActionKinds() []string
}
CodeActionKinds is implemented by a CodeActionProvider that answers only some kinds of action (source.organizeImports): the editor then asks it only when one of them is wanted, and knows from it that the kind exists for the document, which is what enables Organize Imports (Shift+Alt+O) and the Source Action menu (SPEC §9.12 "Code actions"). A provider that does not implement it is asked for every kind and declares none. Use a language server's own list when it has one; this is for a pack that supplies an action the server does not offer.
type CodeActionProvider ¶
type CodeActionProvider interface {
ProvideCodeActions(ctx context.Context, doc TextDocument, req CodeActionRequest) ([]CodeAction, error)
}
CodeActionProvider answers code action requests.
type CodeActionRequest ¶
type CodeActionRequest struct {
// Range is the selection or the cursor.
Range Range
// Diagnostics are the problems that overlap Range.
Diagnostics []Diagnostic
// Only lists the kinds wanted (quickfix, refactor, source.organizeImports); empty is all.
Only []string
}
CodeActionRequest is what a code action provider is asked for.
type CodeLens ¶
type CodeLens struct {
// Range is the line the lens is above; only its start line counts. The lenses of one line are shown on one row, in the
// order the providers gave them.
Range Range
// Command is what the lens shows (its Title) and runs when it is clicked: a command of the editor with the first of its
// Arguments. A lens with no title is not shown.
Command Command
// Disabled shows the title dimmed and runs nothing when it is clicked: an action that is announced and not available yet.
Disabled bool
}
CodeLens is a command shown above a line of a document (SPEC §9.12 "Providers in Go", step 14.3).
type CodeLensProvider ¶
type CodeLensProvider interface {
ProvideCodeLenses(ctx context.Context, doc TextDocument) ([]CodeLens, error)
}
CodeLensProvider answers the code lenses of a document. The editor asks again after the text changed (the newest request wins) and when the extension calls Languages().RefreshCodeLenses.
type Command ¶
type Command struct {
// Title is the text of the lens, the button or the menu row.
Title string
// ID is the id of the command: one of the extension, or of the editor.
ID string
// Arguments are the arguments of a command of the language providers, as JSON values.
Arguments []json.RawMessage
// Tooltip is the text of the hover (the Source Control view).
Tooltip string
// Args are the JSON-compatible argument the Source Control view runs the command with (one value, or nil); a command has
// Args or Arguments, and Args is used when it is not nil.
Args any
}
Command is a command of the editor (not of a server) with its arguments, that an item asks to run: the command of a code lens, and the click on a resource, Ctrl+Enter in the input and the buttons of the Source Control view (VS Code's Command).
type CommandHandler ¶
CommandHandler runs a command. ctx is cancelled when the command's work is no longer wanted, and args is a JSON-compatible value or nil. A returned error is the error of the command; a panic deactivates the extension.
type CommandInfo ¶
type CommandInfo struct {
ID string `json:"id"`
Title string `json:"title,omitempty"`
Category string `json:"category,omitempty"`
// Description says what the command does; empty for most.
Description string `json:"description,omitempty"`
// Enabled tells whether the command has a handler in the workspace and its precondition holds now.
Enabled bool `json:"enabled"`
// Refused is true for a command that clients may not run (TopicCommandsExecute fails with CoreCommandRefused);
// RefusedClass is one of the Refused constants and Reason says why in words.
Refused bool `json:"refused,omitempty"`
RefusedClass string `json:"refusedClass,omitempty"`
Reason string `json:"reason,omitempty"`
}
CommandInfo is one command in the reply of TopicCommandsList.
type CommandSpec ¶
type CommandSpec struct {
// ID is the id of the command, unique in Emetos (the editor's commands are taken): hello.greet.
ID string
// Title is the name in the command palette; a command with none is not listed there.
Title string
// Category groups commands in the palette ("Hello: Greet").
Category string
// Description says what the command does, for the keyboard shortcuts editor.
Description string
// When is the condition, a when-clause over the context keys, under which the command is enabled; empty is always.
When string
// Icon is the name of the Codicon ("add", "discard") the command shows as where a menu draws icons in place of titles: the
// inline actions and the title actions of the Source Control view (VS Code's command icon). Empty for none.
Icon string
}
CommandSpec declares a command.
type Commands ¶
type Commands interface {
// Handle sets the handler of a command that the Manifest declares. It fails when the extension did not declare it.
Handle(id string, handler CommandHandler) error
// Register adds a command that the Manifest did not declare, with its handler. It fails when the id is taken. A
// command added here is not in the palette before the extension is activated.
Register(spec CommandSpec, handler CommandHandler) error
}
Commands registers the commands of an extension.
type CommandsExecuteReply ¶
type CommandsExecuteReply struct {
Result json.RawMessage `json:"result"`
}
CommandsExecuteReply is the reply of TopicCommandsExecute. A command returns no value, so Result is always null: the reply says the command ran, and its error is the error of the request.
type CommandsExecuteRequest ¶
type CommandsExecuteRequest struct {
ID string `json:"id"`
Args json.RawMessage `json:"args,omitempty"`
}
CommandsExecuteRequest is the payload of TopicCommandsExecute. Args is any JSON value (the argument the command takes).
type CommandsList ¶
type CommandsList struct {
Commands []CommandInfo `json:"commands"`
}
CommandsList is the reply of TopicCommandsList: every command of the workspace, those of Emetos and those of the extensions, ordered by id. The request carries no payload (null or {}).
type CompletionItem ¶
type CompletionItem struct {
// Label is the text of the row and, without InsertText, what is inserted.
Label string
// Detail is shown after the label, Documentation in the details pane.
Detail string
Documentation *Markup
Kind CompletionKind
Deprecated bool
Preselect bool
// SortText and FilterText replace the label in sorting and filtering.
SortText, FilterText string
// InsertText is inserted instead of the label; with Snippet it is a snippet (SPEC §9.9).
InsertText string
Snippet bool
// Range, when not nil, is the text the item replaces (it must contain the cursor and be on its line); without it the
// word before the cursor is replaced.
Range *Range
// AdditionalEdits are made together with the insertion (imports).
AdditionalEdits []RangeEdit
CommitCharacters []string
Command *Command
}
CompletionItem is a row of the suggest widget.
type CompletionKind ¶
type CompletionKind int
CompletionKind is the kind of a completion item or a symbol; the numbers are those of the LSP (CompletionItemKind and SymbolKind), which VS Code's icons follow.
const ( CompletionText CompletionKind = iota + 1 CompletionMethod CompletionFunction CompletionConstructor CompletionField CompletionVariable CompletionClass CompletionInterface CompletionModule CompletionProperty CompletionUnit CompletionValue CompletionEnum CompletionKeyword CompletionSnippet CompletionColor CompletionFile CompletionReference CompletionFolder CompletionEnumMember CompletionConstant CompletionStruct CompletionEvent CompletionOperator CompletionTypeParameter )
The completion kinds.
type CompletionList ¶
type CompletionList struct {
Items []CompletionItem
Incomplete bool
}
CompletionList is the answer of a completion provider; Incomplete asks for the request to be made again when the user types more.
type CompletionProvider ¶
type CompletionProvider interface {
ProvideCompletion(ctx context.Context, doc TextDocument, pos Position, trigger CompletionTrigger) (CompletionList, error)
}
CompletionProvider answers completion requests.
type CompletionTrigger ¶
type CompletionTrigger struct {
// Kind is "invoked" (typing or the key), "character" (a trigger character, in Character) or "incomplete" (the list
// of an earlier answer was incomplete).
Kind string
Character string
}
CompletionTrigger says why completion is asked for.
type ContentProvider ¶
type ContentProvider struct {
// Scheme names the documents: a word of letters, digits and hyphens, not the scheme of a core document ("file", "untitled",
// "emetos-virtual"), unique among the providers of the window tab. The URIs are ContentURI(Scheme, path).
Scheme string
// Label gives the name of the document in its tab (the name of the file, "main.go"); the last element of the path when nil.
Label func(uri string) string
// Language gives the id of the language of the document; when nil or when it answers "" the language is detected from the
// label, as for a file of that name.
Language func(uri string) string
// Text makes the text of the document. It runs off the UI thread, each time the document is opened and each time Changed says it
// changed, and must stop when ctx does. A failure is reported to the user, with its message; the error with the tag
// TagContentBinary is the notice of a binary file. The text may have any line ending; the document is shown with "\n".
Text func(ctx context.Context, uri string) (string, error)
}
ContentProvider makes the text of the read-only documents of one scheme (SPEC §10.30 "Diffs of changes"; VS Code's TextDocumentContentProvider). The documents are opened with Documents().OpenDiff and OpenDocument, never dirty, never saved, never backed up; after a restart a restored tab asks the provider again, and a tab whose provider is not there is dropped without a word.
type ContentRegistration ¶
type ContentRegistration interface {
// Changed tells the window that the text of the documents with these URIs may have changed (the index moved): the open ones are
// made again, off the UI thread, and the diff editors that show them are computed again. A URI that is not open costs nothing.
Changed(uris ...string)
// Dispose takes the provider away; it happens by itself when the activation ends. The tabs that show its documents stay
// open with the text they have.
Dispose()
}
ContentRegistration is a registered ContentProvider.
type ContextKeys ¶
type ContextKeys interface {
// Set gives the key a value: a bool, a string or a number. The key starts with the id of the extension and a dot
// (emetos.tasks.running) or is one of Contributes.ContextKeys, else it fails with ExtensionContextKeyForeign. The keys the
// activation set go when it ends.
Set(key string, value any) error
// Reset takes the key away.
Reset(key string)
// SetFor gives the key a value on one screen only (SPEC §10.18, D50): the window of the host (HostOrigin) or the view of a client. A
// key that describes what a person is doing on a screen, such as which terminal has the keyboard, is set like this; Set is for the keys
// that describe the workspace, which every screen sees (the host's and the views' alike). A key set with SetFor is not seen by the
// other screens, and one that is set with both is the later call's on the screen of that call. A screen that is gone is ignored.
SetFor(origin Origin, key string, value any) error
// ResetFor takes the key away on one screen.
ResetFor(origin Origin, key string)
}
ContextKeys sets the context keys of the extension, which the `when` of its views, its title actions, its commands and its keybindings read.
type Contributes ¶
type Contributes struct {
// Commands are listed in the command palette. A command whose handler is not set yet (see Commands.Handle)
// activates the extension when it is run.
Commands []CommandSpec
// Menus are items of menus; the Command of each is a command of the extension or of the editor.
Menus []MenuItem
// Keybindings are default keybindings of commands.
Keybindings []Keybinding
// ViewContainers are the containers of the side bar the extension adds: an icon in the activity bar each.
ViewContainers []ViewContainerSpec
// Views are the views of the side bar, in the containers of the extension or of Emetos. Showing one activates the
// extension (the activation event OnView).
Views []ViewSpec
// PanelViews are the tabs of the panel. Showing one activates the extension.
PanelViews []PanelViewSpec
// ViewActions are the title actions of the views.
ViewActions []ViewActionSpec
// EditorKinds are the kinds of editor tab the extension adds. Opening or restoring a tab of a kind activates the
// extension (the activation event OnEditor).
EditorKinds []EditorKindSpec
// EditorActions are the icons at the right end of the tab strip of every editor group.
EditorActions []EditorActionSpec
// FileViews are the micro-tabs of the editor tab of the files they select. Showing one activates the extension.
FileViews []FileViewSpec
// WindowTabKinds are the kinds of window tab the extension adds: an entry of the "+" menu of the strip each. Opening or
// restoring a tab of a kind activates the extension, in the scope of that tab (the activation event OnWindowTab).
WindowTabKinds []WindowTabKindSpec
// Languages is the language pack of the extension: a file system (an embed.FS, rooted with fs.Sub) that has the
// package.json of a VS Code extension at its root, with the languages (contributes.languages), the grammars
// (contributes.grammars) and the settings defaults of languages (contributes.configurationDefaults) it contributes, and
// the files they name (the language configurations, the grammars). It is nil for an extension that adds no language.
// Emetos adds the languages to its registry while the extension is enabled in at least one window tab, before any file
// opens, and takes them away when the last tab that has the extension enabled closes or turns it off (SPEC §10.15
// "As built (step 11.4)"). It needs no activation: the languages are there whether or not the extension was activated.
Languages fs.FS
// LanguageServers are the language servers the extension runs, one per window tab (SPEC §9.12 "Servers and their
// lifetime"). They are started by the host, not by Activate; the extension gets the server's Output channel, status and
// restart command for free. Declaring one adds the command <extension id>.restartServer.
LanguageServers []LanguageServerSpec
// Settings are settings the extension declares, as VS Code's contributes.configuration does: unlike the ones registered
// with Settings().Register, their keys are free (go.gopls) as long as the editor and the other extensions do not have
// them. The host registers them while the extension is enabled in a tab, before it is activated, so that the settings
// editor and the settings files know them; Settings().Get reads them. Two declarations of one key, an empty key and a
// type that is not a JSON type are refused by CheckManifest.
Settings []SettingSpec
// ContextKeys are the context keys the extension sets whose names do not start with its id, because VS Code's name for the
// same thing is read by the keybindings and the `when` clauses of users (terminalFocus, git.state). Context().Set accepts
// them as it does the keys under the id of the extension. A name is a word of letters and digits, or such words joined by
// dots, not under the id of another extension (the host refuses it) and not one of the editor's; CheckManifest refuses a
// name that is neither or is listed twice, and one under emetos. unless it is under the id of the extension itself.
ContextKeys []string
// ViewWelcome is the welcome content of views (VS Code's contributes.viewsWelcome): the text, links and buttons a view shows
// while it has nothing else to show. The view may be one of Emetos (workbench.scm, workbench.explorer.emptyView) or any other.
ViewWelcome []ViewWelcomeSpec
// and that a menu item opens with MenuItem.Submenu.
Submenus []SubmenuSpec
// WritesSettings are keys of settings that are not the extension's own (the editor's, such as editor.inlayHints.enabled) which
// Settings().Update may write for it, to the user's settings file. The clangd command Toggle inlay hints flips a setting of the
// editor, as VS Code's does. CheckManifest refuses an empty key, a key listed twice and a key the extension declares itself (it
// may write that without being listed).
WritesSettings []string
// Debuggers are the debuggers the extension contributes (VS Code's contributes.debuggers, SPEC §10.31): the debug types, the
// attributes of their configurations and what a new launch.json starts with. The code that finds the adapter is registered with
// Debug().RegisterAdapterDescriptorFactory; showing a configuration of the type activates the extension (the activation event
// OnDebug).
Debuggers []DebuggerSpec
// Breakpoints are the languages where breakpoints can be set (VS Code's contributes.breakpoints).
Breakpoints []BreakpointSpec
}
Contributes are the contributions a Manifest declares. Emetos installs them in a scope when the extension is enabled there and removes them when it is disabled or the scope closes.
type CoverageCount ¶
type CoverageCount struct{ Covered, Total int }
CoverageCount is how many of the things of a kind were covered (VS Code's TestCoverageCount).
type CoverageDetails ¶
type CoverageDetails struct {
Statements []StatementCoverage
Declarations []DeclarationCoverage
}
CoverageDetails are the details of the coverage of one file.
type Debug ¶
type Debug interface {
// RegisterAdapterDescriptorFactory registers the code that finds the adapter of the sessions of the debug type. A type has one
// factory: it fails with ExtensionDebugFactoryTaken when another extension has one, ExtensionDebugInvalid for an empty type or
// no function, ExtensionDebugUnavailable in a scope with no debug service (a host without a workbench) and ExtensionDeactivated
// after the activation ended. The function it returns removes the factory; the activation's end does it too.
RegisterAdapterDescriptorFactory(debugType string, factory DebugAdapterFactory) (dispose func(), err error)
// RegisterConfigurationProvider registers a provider for the debug type, or for every type with "*". It fails like
// RegisterAdapterDescriptorFactory, except that a type may have several providers.
RegisterConfigurationProvider(debugType string, provider DebugConfigurationProvider, trigger DebugProviderTrigger) (dispose func(), err error)
// RegisterAdapterTrackerFactory registers a tracker factory for the debug type, or for every type with "*": every session of the
// type gets a tracker. It fails like RegisterConfigurationProvider.
RegisterAdapterTrackerFactory(debugType string, factory DebugAdapterTrackerFactory) (dispose func(), err error)
// StartDebugging starts the session of the configuration or compound in the target, in the launch.json of the folder (empty: the
// first folder that has the name), and returns when its adapter has been started and has answered launch or attach. It returns
// false with no error when the launch was cancelled (a provider, an input, a failed task). The host calls the providers of the
// extensions on other goroutines, so call it from a goroutine of the extension and not from a command handler, which holds the UI
// thread.
StartDebugging(ctx context.Context, folder string, target DebugTarget, opts DebugStartOptions) (bool, error)
// StopDebugging stops the session; nil stops all of them.
StopDebugging(ctx context.Context, session DebugSession) error
// ActiveSession is the session the Call Stack has focused, or nil. Sessions lists the sessions that run, the oldest first.
ActiveSession() DebugSession
Sessions() []DebugSession
// OnDidStartSession, OnDidTerminateSession and OnDidChangeActiveSession (nil when none is active) and OnDidReceiveCustomEvent call
// fn on the UI thread; the function they return removes the listener.
OnDidStartSession(fn func(DebugSession)) (remove func())
OnDidTerminateSession(fn func(DebugSession)) (remove func())
OnDidChangeActiveSession(fn func(DebugSession)) (remove func())
OnDidReceiveCustomEvent(fn func(DebugSessionCustomEvent)) (remove func())
// Breakpoints lists the breakpoints. AddBreakpoints adds the ones that are not there and RemoveBreakpoints removes those with the
// ID, or the place, of the given ones. OnDidChangeBreakpoints reports every change.
Breakpoints() []DebugBreakpoint
AddBreakpoints(ctx context.Context, breakpoints []DebugBreakpoint) error
RemoveBreakpoints(ctx context.Context, breakpoints []DebugBreakpoint) error
OnDidChangeBreakpoints(fn func(DebugBreakpointsChange)) (remove func())
// Console is the Debug Console.
Console() DebugConsole
}
Debug is the Debug API of an extension in one scope.
type DebugAdapter ¶
type DebugAdapter struct {
// Kind is how the adapter is reached.
Kind DebugAdapterKind
// Command, Args, Env and Cwd start the program of DebugAdapterExecutable and DebugAdapterExecutableServer; Command is found in PATH
// unless it has a slash, Env are added to the environment of Emetos and an empty Cwd is the folder of Emetos.
Command string
Args []string
Env map[string]string
Cwd string
// PortPattern finds the port in a line the program prints (DebugAdapterExecutableServer): a regular expression with the named
// group "port" and, optionally, "host". Empty matches "listening at: 127.0.0.1:4711" and "listening on port 4711".
PortPattern string
// Host and Port are the address of DebugAdapterServer; an empty Host is 127.0.0.1.
Host string
Port int
// Path is the Unix socket of DebugAdapterPipeServer.
Path string
// ConsoleOutput makes the lines the program writes to its standard error, and for DebugAdapterExecutableServer to its standard output
// too, lines of the Debug Console of the session (categories stderr and stdout; the line that gives the port is left out). It is for an
// adapter that runs the debuggee as its child and leaves the output of the debuggee to its own streams (Delve); the lines go to the log
// of Emetos as well.
ConsoleOutput bool
// ServesChildren (DebugAdapterExecutableServer) says that the server program serves the sessions its adapter starts with
// startDebugging as well: a child session connects to the address of the parent's server, and the factory is not asked for it
// (js-debug's children are targets of the parent's process, which finds them by the __pendingTargetId of their configuration; VS
// Code's extension gives them the parent's server the same way). The server ends with the session that started it.
ServesChildren bool
}
DebugAdapter says where a debug adapter is and how to reach it (VS Code's DebugAdapterDescriptor); the members of its Kind are used.
type DebugAdapterFactory ¶
type DebugAdapterFactory func(ctx context.Context, session DebugSession, executable *DebugAdapter) (*DebugAdapter, error)
DebugAdapterFactory finds the adapter of a session (VS Code's DebugAdapterDescriptorFactory.createDebugAdapterDescriptor). executable is the adapter the manifest names (Program, Args, Runtime), or nil. Returning nil, nil falls back to executable; with none the session fails. It runs once for each session, when its adapter is needed, with the session's context.
type DebugAdapterKind ¶
type DebugAdapterKind int
DebugAdapterKind says how an adapter is reached.
const ( // DebugAdapterExecutable is a program that speaks DAP on its standard input and output (VS Code's DebugAdapterExecutable). DebugAdapterExecutable DebugAdapterKind = iota + 1 // DebugAdapterServer is a server that listens on a TCP port already (VS Code's DebugAdapterServer). DebugAdapterServer // DebugAdapterPipeServer is a server that listens on a Unix socket already (VS Code's DebugAdapterNamedPipeServer). DebugAdapterPipeServer // DebugAdapterExecutableServer is a program that listens on a port and prints it: Emetos starts it, reads the port and connects // (delve's `dlv dap`, js-debug). DebugAdapterExecutableServer )
The kinds of adapter.
type DebugAdapterTracker ¶
type DebugAdapterTracker struct {
// OnWillStartSession is called before the adapter is reached.
OnWillStartSession func()
// OnWillReceiveMessage gets each message Emetos sends to the adapter, as the JSON of the protocol message.
OnWillReceiveMessage func(message json.RawMessage)
// OnDidSendMessage gets each message the adapter sends to Emetos.
OnDidSendMessage func(message json.RawMessage)
// OnWillStopSession is called when the session ends.
OnWillStopSession func()
// OnError is called with the error that ended the session: the adapter could not be reached or died.
OnError func(err error)
// OnExit is called when the adapter's program exited, with its exit status (nil when it is not known).
OnExit func(code *int)
}
DebugAdapterTracker watches the messages between Emetos and an adapter (VS Code's DebugAdapterTracker). A nil function is not called. The functions run on the goroutine that reads or writes the adapter's stream, one at a time and in the order of the wire: keep them short and do not make a request of the session from them.
type DebugAdapterTrackerFactory ¶
type DebugAdapterTrackerFactory func(ctx context.Context, session DebugSession) (*DebugAdapterTracker, error)
DebugAdapterTrackerFactory makes the tracker of a session (VS Code's DebugAdapterTrackerFactory). A nil tracker watches nothing.
type DebugBreakpoint ¶
type DebugBreakpoint struct {
// ID identifies the breakpoint; Breakpoints() fills it and RemoveBreakpoints looks the breakpoint up by it, or by its place.
ID string
// URI is the file (file:///path) and Position the place in it, zero-based: with a column the breakpoint is inline.
URI string
Position Position
// Function is the name of the function of a function breakpoint.
Function string
// Disabled says that the breakpoint does not stop the program.
Disabled bool
// Condition, HitCondition and LogMessage are the expressions of a conditional breakpoint, a hit count and a logpoint.
Condition, HitCondition, LogMessage string
}
DebugBreakpoint is a breakpoint (VS Code's SourceBreakpoint and FunctionBreakpoint). A breakpoint with a Function is a function breakpoint; the others are in a line of a file.
type DebugBreakpointsChange ¶
type DebugBreakpointsChange struct {
Added, Removed, Changed []DebugBreakpoint
}
DebugBreakpointsChange is what OnDidChangeBreakpoints reports (VS Code's BreakpointsChangeEvent).
type DebugConfiguration ¶
DebugConfiguration is a launch configuration: the JSON object of launch.json (name, type, request and the attributes of the debugger). Its values are those of encoding/json: string, float64, bool, nil, []any and map[string]any.
type DebugConfigurationProvider ¶
type DebugConfigurationProvider struct {
// Provide gives the configurations to put into a new launch.json (trigger DebugTriggerInitial) or to list in the dropdown
// (DebugTriggerDynamic).
Provide func(ctx context.Context, folder string) ([]DebugConfiguration, error)
// Resolve is called before the variables of a configuration are substituted, and may fill in what is missing (the program of a
// "Debug current file"). Returning nil, nil cancels the launch silently, and nil, ErrDebugOpenLaunchJSON cancels it and shows
// launch.json.
Resolve func(ctx context.Context, folder string, cfg DebugConfiguration) (DebugConfiguration, error)
// ResolveSubstituted is called after the variables are substituted, and after the task before the session ran; nil, nil cancels.
ResolveSubstituted func(ctx context.Context, folder string, cfg DebugConfiguration) (DebugConfiguration, error)
}
DebugConfigurationProvider completes the configurations of a debug type (VS Code's DebugConfigurationProvider). The providers of a type are called in the order they were registered, each with the result of the one before; those of the type "*" come after the ones of the type. A nil function is not called. The folder is the folder of the launch.json, empty for none.
type DebugConsole ¶
type DebugConsole interface {
// Append writes the text as it is, AppendLine adds a line feed.
Append(text string)
AppendLine(text string)
}
DebugConsole writes to the Debug Console (VS Code's debug.activeDebugConsole).
type DebugConsoleMode ¶
type DebugConsoleMode int
DebugConsoleMode says whether a child session has a Debug Console of its own.
const ( // DebugConsoleSeparate sends the session's output to its own console. DebugConsoleSeparate DebugConsoleMode = iota // DebugConsoleMergeWithParent sends it to the console of the parent session. DebugConsoleMergeWithParent )
type DebugProviderTrigger ¶
type DebugProviderTrigger int
DebugProviderTrigger says when the configurations a provider gives are asked for.
const ( // DebugTriggerInitial is asked for when launch.json is created (VS Code's DebugConfigurationProviderTriggerKind.Initial). DebugTriggerInitial DebugProviderTrigger = iota // DebugTriggerDynamic is asked for when the configurations of the dropdown are listed and F5 is pressed with no launch.json (Dynamic). DebugTriggerDynamic )
type DebugSession ¶
type DebugSession interface {
// ID is the id of the session, unique in the window tab.
ID() string
// Type is the debug type and Name the name of the session (the configuration's name, made unique among the sessions).
Type() string
Name() string
// Folder is the folder of the launch.json the configuration comes from; empty for a configuration given whole.
Folder() string
// Configuration is the configuration the session runs: the resolved one, with its variables substituted.
Configuration() DebugConfiguration
// Parent is the session that started this one (the adapter's startDebugging), or nil.
Parent() DebugSession
// CustomRequest sends a request the protocol does not define to the adapter and returns the body of its response (VS Code's
// customRequest). It fails with the host's DebugNoAdapter when the session has no adapter any more.
CustomRequest(ctx context.Context, command string, args any) (json.RawMessage, error)
}
DebugSession is a debug session (VS Code's DebugSession). The value stays usable after the session ended, but its requests fail.
type DebugSessionCustomEvent ¶
type DebugSessionCustomEvent struct {
// Session is the session whose adapter sent it, Event the name of the event and Body its body as JSON.
Session DebugSession
Event string
Body json.RawMessage
}
DebugSessionCustomEvent is an event the adapter sent that the protocol does not define (VS Code's DebugSessionCustomEvent).
type DebugSnippet ¶
type DebugSnippet struct {
// Label is the name of the snippet and Description what it is for.
Label, Description string
// Body is the configuration; it needs a name, a type and a request.
Body DebugConfiguration
}
DebugSnippet is a configuration the editor offers to add.
type DebugStartOptions ¶
type DebugStartOptions struct {
// Parent makes the session a child of another, shown under it in the Call Stack.
Parent DebugSession
// LifecycleManagedByParent makes the child's stop, disconnect and restart act on the parent.
LifecycleManagedByParent bool
// Compact shows the child's threads under the parent's session, without a row of its own.
Compact bool
// ConsoleMode says which Debug Console the output goes to.
ConsoleMode DebugConsoleMode
// NoDebug runs the program without debugging.
NoDebug bool
// SuppressSaveBeforeStart does not save the files before the session starts.
SuppressSaveBeforeStart bool
// SuppressDebugToolbar, SuppressDebugStatusbar and SuppressDebugView hide those parts of the workbench for the session.
SuppressDebugToolbar, SuppressDebugStatusbar, SuppressDebugView bool
}
DebugStartOptions are the options of StartDebugging (VS Code's DebugSessionOptions).
type DebugTarget ¶
type DebugTarget struct {
Name string
Config DebugConfiguration
}
DebugTarget says what to start: the configuration or compound called Name in the launch.json of the folder, or Config given whole.
type DebuggerSpec ¶
type DebuggerSpec struct {
// Type is the debug type of the configurations ("go", "debugpy"): letters, digits, dots, hyphens and underscores.
Type string
// Label is the name shown to the user ("Go"); the type when empty.
Label string
// Languages are the ids of the languages the debugger serves: F5 with no launch.json asks the debuggers of the language of the
// active editor for a configuration.
Languages []string
// Program, Args, Runtime and RuntimeArgs are the default adapter: a program that speaks DAP on its standard input and output
// (VS Code's program and args; with Runtime the program is the first argument of the runtime). The descriptor factory gets it as
// its default and may return another; without a factory it is the adapter.
Program string
Args []string
Runtime string
RuntimeArgs []string
// ConfigurationAttributes are the JSON schemas of the attributes of a configuration, by request ("launch" and "attach"): an
// object schema with properties, required, additionalProperties and the rest of the subset Emetos checks (internal/core/debug
// CheckAttributes). launch.json is checked against them and completes from them.
ConfigurationAttributes map[string]json.RawMessage
// InitialConfigurations are the configurations a new launch.json starts with, before those the configuration providers of
// trigger DebugTriggerInitial give.
InitialConfigurations []DebugConfiguration
// ConfigurationSnippets are the configurations "Add Configuration" and the completion of launch.json offer; their strings may use
// the snippet syntax.
ConfigurationSnippets []DebugSnippet
// Variables maps the names of interactive variables to the ids of commands: ${command:pickProcess} runs the command.
Variables map[string]string
// DynamicConfigurations says that the debugger has configuration providers of trigger DebugTriggerDynamic: the dropdown of the Run
// and Debug view lists the type, and activates the extension (OnDebug) to ask for the configurations (VS Code's
// onDebugDynamicConfigurations activation event).
DynamicConfigurations bool
}
DebuggerSpec declares a debugger (VS Code's contributes.debuggers). A configuration with Type is started by this debugger.
type DeclarationCoverage ¶
DeclarationCoverage is a function or other declaration and how many times it ran (VS Code's DeclarationCoverage).
type Decorations ¶
type Decorations interface {
// Register adds a provider. It fails with ExtensionDecorationsInvalid for a nil provider, ExtensionDecorationsUnavailable in a scope
// that has no decorations service and ExtensionDeactivated after the activation ended.
Register(provider FileDecorationProvider) (FileDecorations, error)
}
Decorations registers the file decoration providers of an extension.
type DefinitionProvider ¶
type DefinitionProvider interface {
ProvideDefinition(ctx context.Context, doc TextDocument, pos Position) ([]Location, error)
}
DefinitionProvider answers go to definition.
type Diagnostic ¶
Diagnostic is a problem of a document, as the context of a code action request.
type DialogButton ¶
type DialogButton struct {
// Label is the text of the button.
Label string
// Cancel makes the button the one Escape and the close button of the dialog stand for: closing the dialog answers with it.
Cancel bool
}
DialogButton is a button of a dialog.
type DialogResult ¶
type DialogResult struct {
// Button is the index in DialogSpec.Buttons of the button that was pressed, or of the cancel button when the dialog was closed
// with Escape; -1 when it was closed and has no cancel button.
Button int
// Cancelled says the dialog was closed without pressing a button.
Cancelled bool
}
DialogResult is the answer to a dialog.
type DialogSpec ¶
type DialogSpec struct {
// Type sets the icon.
Type DialogType
// Message is the main text; with a Detail it is the title above it.
Message string
// Detail is the text under the message; its line breaks are kept.
Detail string
// Buttons are the buttons; there must be at least one. The first is the default button: it has the focus when the dialog opens
// and Enter presses it.
Buttons []DialogButton
// Origin is the screen that shows the dialog; the zero value is the origin of the command being handled (see InputBoxOptions.Origin).
Origin Origin
}
DialogSpec describes a modal dialog (VS Code's showMessage with modal: true).
type DialogType ¶
type DialogType int
DialogType is what a dialog is about; it sets the icon of the dialog.
const ( // DialogQuestion shows the information icon, as VS Code does for a question. DialogQuestion DialogType = iota // DialogInfo shows the information icon. DialogInfo // DialogWarning shows the warning icon. DialogWarning // DialogError shows the error icon. DialogError )
The types of a dialog.
type Dialogs ¶
type Dialogs interface {
// Ask shows the dialog and calls done once, on the UI thread, with the answer. The window shows one dialog at a time: a
// dialog asked while another is open waits for its turn, in the order asked. It returns at once. It fails with
// ExtensionDialogInvalid for a spec with no button or with two cancel buttons, ExtensionDialogsUnavailable in a scope that
// cannot show a dialog (a window tab that is not on screen) and ExtensionDeactivated after the activation ended. done is
// not called when the extension was deactivated before the answer; a panic in it deactivates the extension.
Ask(spec DialogSpec, done func(DialogResult)) error
}
Dialogs asks the user a question in a modal dialog of the window tab of the scope, which blocks the window tab until it is answered (SPEC §10.30 "Trusting a repository").
type DiffEditorContext ¶
type DiffEditorContext struct {
// OriginalURI and ModifiedURI are the documents of the two sides.
OriginalURI, ModifiedURI string
// OriginalWithModifiedChanges is the text of the original with the changes of the hunk, or of the selected lines, applied.
OriginalWithModifiedChanges string
}
DiffEditorContext is what a command of the toolbar in the gutter of the diff editor (MenuDiffEditorGutterHunk and MenuDiffEditorGutterSelection) is run with (VS Code's DiffEditorSelectionHunkToolbarContext). The command gets one object with the members DiffArgOriginalURI, DiffArgModifiedURI and DiffArgOriginalWithModifiedChanges, which ReadDiffEditorArgs reads.
func ReadDiffEditorArgs ¶
func ReadDiffEditorArgs(args any) (DiffEditorContext, bool)
ReadDiffEditorArgs reads the arguments DiffEditorContext.Args made; ok is false for any other value (the command was run from the palette or by a key).
func (DiffEditorContext) Args ¶
func (c DiffEditorContext) Args() any
Args is the value the command of the toolbar is run with.
type DiffSpec ¶
type DiffSpec struct {
// Left and Right are the two documents: a file (file:///path), an open untitled document, or a provided one (ContentURI). A
// provided one is made first, off the UI thread, and the diff opens when both are there.
Left, Right string
// Title is the name of the tab ("loader.go (Working Tree)"); the names of the two sides joined by an arrow when empty.
Title string
// Preview opens the diff as a preview tab, which the next preview replaces; false keeps it. A diff that is open already is
// shown again in its tab.
Preview bool
// Selection is put in the right side and revealed, when set.
Selection *Selection
// PreserveFocus keeps the keyboard where it is.
PreserveFocus bool
}
DiffSpec describes a diff editor to open (Documents().OpenDiff; VS Code's vscode.diff).
type DocumentChange ¶
type DocumentChange struct {
URI string `json:"uri"`
// Version is the version of the document after the change.
Version int `json:"version"`
// Cause is "edit", "undo", "redo", "lineEnding" (no text changed) or "setText" (the whole text was replaced and the
// history cleared).
Cause string `json:"cause"`
// Changes are the replacements, in order of position; the ranges of all of them are in the text before the change.
Changes []TextChange `json:"changes"`
}
DocumentChange is the payload of TopicDocumentChanged.
type DocumentCloseRequest ¶
type DocumentCloseRequest struct {
URI string `json:"uri"`
Discard bool `json:"discard,omitempty"`
}
DocumentCloseRequest is the payload of TopicDocumentClose. A document with unsaved changes is closed only with Discard.
type DocumentClosed ¶
type DocumentClosed struct {
URI string `json:"uri"`
}
DocumentClosed is the payload of TopicDocumentClosed.
type DocumentContent ¶
type DocumentContent struct {
URI string `json:"uri"`
LanguageID string `json:"languageId"`
Version int `json:"version"`
Text string `json:"text"`
// Dirty tells that the document has changes that are not saved.
Dirty bool `json:"dirty,omitempty"`
}
DocumentContent is the reply of TopicDocumentRead: the text of the open document, with its unsaved changes, and the version it has (DocumentInfo.Version) to send with an edit.
type DocumentEditReply ¶
type DocumentEditReply struct {
URI string `json:"uri"`
Version int `json:"version"`
Changed bool `json:"changed"`
}
DocumentEditReply is the reply of TopicDocumentEdit: the version after the edit (the same version when nothing changed).
type DocumentEditRequest ¶
type DocumentEditRequest struct {
URI string `json:"uri"`
Version int `json:"version"`
Edits []TextChange `json:"edits"`
}
DocumentEditRequest is the payload of TopicDocumentEdit: replacements of ranges of the document, made against the text of version Version. The ranges are in that text, as in DocumentChange; they must not overlap. The edits are one step of the undo history. A Version that is not the document's current one fails with CoreDocumentVersionStale.
type DocumentHandle ¶
type DocumentHandle interface {
// URI is the URI of the document (file:///path/to/file); it changes when the file is saved under another name.
URI() string
// LanguageID is the id of the language of the document.
LanguageID() string
// Version counts the changes of the text.
Version() int
// Text is the whole text, with its unsaved changes.
Text() string
// ReadOnly tells whether the document cannot be changed.
ReadOnly() bool
// Edit applies the edits as one undo step. It fails for a read-only document and for edits that overlap.
Edit(edits []TextEdit) error
// OnChange calls fn after every change of the text; the calls stop with the returned function and when the view
// ends.
OnChange(fn func(ViewDocumentChange)) (cancel func())
// TopLine is the first line (counted from 0) that the Text view of the document shows at the top, as the last text
// editor of the document scrolled; 0 when there is none.
TopLine() int
// OnScroll calls fn when a text editor of the document scrolls, with its first line; the calls stop with the returned
// function and when the view ends.
OnScroll(fn func(topLine int)) (cancel func())
// OpenFile opens a file of the folder (a path relative to the folder or absolute) in an editor of the active group;
// it is what a link to a file of the workspace does.
OpenFile(path string) error
// Folder is the folder of the workspace, or empty.
Folder() string
}
DocumentHandle is the document a file view shows. Every method runs on the UI thread. Edits go through the document of the editor, so they are undone with its undo, make the document dirty, are saved with it and kept by the hot exit.
type DocumentHighlight ¶
DocumentHighlight is an occurrence of the symbol under the cursor; Kind is 1 text, 2 read or 3 write.
type DocumentHighlightProvider ¶
type DocumentHighlightProvider interface {
ProvideDocumentHighlights(ctx context.Context, doc TextDocument, pos Position) ([]DocumentHighlight, error)
}
DocumentHighlightProvider answers the occurrences of the symbol under the cursor.
type DocumentInfo ¶
type DocumentInfo struct {
// URI is the document: file:///path/to/file, untitled:1.
URI string `json:"uri"`
// LanguageID is the language of the document: go, markdown, plaintext.
LanguageID string `json:"languageId"`
// Version is the version of the text.
Version int `json:"version"`
}
DocumentInfo is the payload of TopicDocumentOpened.
type DocumentOpenRequest ¶
type DocumentOpenRequest struct {
Path string `json:"path"`
Line int `json:"line,omitempty"`
Col int `json:"col,omitempty"`
}
DocumentOpenRequest is the payload of TopicDocumentOpen: a file of the workspace folder (relative, as for the files topics) to open in the workspace, with the cursor at Line and Col (zero-based, Col in bytes, as in the events).
type DocumentSaved ¶
type DocumentSaved struct {
URI string `json:"uri"`
Version int `json:"version"`
// As tells that the save was a Save As, which gave the document the URI.
As bool `json:"as"`
// PreviousURI is the URI the document had, for a Save As (or after a move); empty otherwise.
PreviousURI string `json:"previousUri,omitempty"`
}
DocumentSaved is the payload of TopicDocumentSaved.
type DocumentSelector ¶
type DocumentSelector struct {
// Languages are language ids (go).
Languages []string
// Pattern is a glob (VS Code's syntax: **/*.go) matched against the path of the file; empty matches none.
Pattern string
}
DocumentSelector says which documents a provider is for. A document matches when its language is one of Languages or its path matches Pattern; with neither, every document matches (with a lower score than a language match, which decides the order of the providers).
type DocumentSymbol ¶
type DocumentSymbol struct {
Name string
Detail string
// Kind is the LSP SymbolKind: File 1, Module 2, Namespace 3, Package 4, Class 5, Method 6, Property 7, Field 8,
// Constructor 9, Enum 10, Interface 11, Function 12, Variable 13, Constant 14, String 15, ... Struct 23.
Kind int
// Range is the whole symbol, SelectionRange the part to select (its name).
Range, SelectionRange Range
Children []DocumentSymbol
}
DocumentSymbol is a symbol of a document with the symbols inside it.
type DocumentSymbolProvider ¶
type DocumentSymbolProvider interface {
ProvideDocumentSymbols(ctx context.Context, doc TextDocument) ([]DocumentSymbol, error)
}
DocumentSymbolProvider answers the outline of a document.
type DocumentTab ¶
type DocumentTab struct {
// ID identifies the tab to CloseTabs for as long as it is open.
ID string
// Group is the number of the editor group that holds it.
Group int
// Kind is "text" or "diff".
Kind string
// URI is the document of a text editor; Original and Modified are the two documents of a diff editor.
URI, Original, Modified string
// Dirty says the tab has unsaved changes.
Dirty bool
// Preview says the tab is a preview.
Preview bool
}
DocumentTab is a tab of a text editor or of a diff editor, as Documents().Tabs lists it.
type DocumentURIRequest ¶
type DocumentURIRequest struct {
URI string `json:"uri"`
}
DocumentURIRequest is the payload of TopicDocumentRead and TopicDocumentSave: the URI of a document that is open in the workspace (the URI of DocumentInfo).
type Documents ¶
type Documents interface {
// Read returns the text of the document with the URI (file:///path/to/file, untitled:1): the text open in the
// scope, with its unsaved changes, or the file of the folder on disk. It fails for a document the scope does not
// have. With FromScope it reads from another window tab along a link (SPEC §10.15 "Event sharing").
Read(ctx context.Context, uri string, opts ...ReadOption) (string, error)
// Open lists the URIs of the documents open in the scope, in the order they were opened.
Open() []string
// Active describes the text editor that is in front in the scope (the one that has the focus, or had it last, in the
// active editor group), with its selections as they are now; false when none is (the group is empty, or its tab shows
// something other than a text). It is the answer TopicEditorActiveChanged and TopicEditorSelectionChanged give, for an
// extension that is activated after them and needs it at once (a command that works on the cursor). Call it on the UI
// thread.
Active() (ActiveDocument, bool)
// Show opens the file with the URI (or shows the open document) in the active editor group, with the cursor at the
// line and column (counted from 1; a column counts UTF-16 units), as a click on a problem does; a click opens a
// preview, preview false keeps the editor. It fails with ExtensionDocumentUnavailable when the scope cannot show
// documents and returns the window's error for a file that cannot be opened. Call it on the UI thread.
Show(uri string, line, column int, preview bool) error
// OpenUntitled opens a new untitled document in the active editor group, kept (not a preview), in the language with the text
// (the language of files.defaultLanguage when languageID is empty, plain text when the language does not exist), and returns
// its URI. The text is the first state of the document: its undo history is empty, so that undoing never takes it away, and,
// as with every untitled document that has a text, closing it asks to save. It fails with ExtensionDocumentUnavailable when
// the scope cannot open documents, with ExtensionDeactivated after the activation ended, and returns the window's error when
// the window tab is not on screen. Call it on the UI thread.
OpenUntitled(languageID, text string) (uri string, err error)
// Apply applies the edit to the documents and files of the scope, the way the rename of the editor applies its edit: the
// changes are made in order, the edits of one document in a run of changes are one step of its undo history, a document
// that is not open is opened in the scope (it stays open, with its changes unsaved), the cursors of the editors keep their
// places in the text, and a create makes the file on disk (an empty one). The ranges of the edits of a document are in the
// text as it is when Apply is called. It fails with ExtensionEditInvalid for a change whose kind or URI is not valid,
// with ExtensionDocumentUnavailable when the scope cannot edit documents, with ExtensionDeactivated after the activation
// ended, and returns the window's error when a change fails (an earlier change stays). Call it on the UI thread.
Apply(ctx context.Context, edit WorkspaceEdit) error
// ProvideContent registers the provider of the read-only documents of a scheme (SPEC §10.30; VS Code's
// registerTextDocumentContentProvider). It fails with ExtensionContentSchemeInvalid for a scheme that is not a word or is one of
// the core's, ExtensionContentProviderInvalid for a provider with no Text, ExtContentSchemeTaken when the window tab has
// the scheme already, ExtensionDocumentUnavailable when the scope cannot show documents, and ExtensionDeactivated after the
// activation ended.
ProvideContent(p ContentProvider) (ContentRegistration, error)
// OpenDiff opens a diff editor (SPEC §9.11) of two documents in the active editor group. The provided documents are made off the
// UI thread; the diff opens when they are there, or the failure is reported to the user (a binary file with the notice of a
// file that looks binary). A diff of the same two documents that is open is shown again, in its tab. It fails with
// ExtensionDiffInvalid for a side that is empty, with the tags of document.ParseURI (URIInvalid) for a URI that does not parse,
// with ExtContentUnknown for a provided URI that no provider makes, ExtDocumentShowUnavailable when the window tab is not on
// screen, ExtensionDocumentUnavailable when the scope cannot open documents, and with ExtensionDeactivated. Call it on the UI
// thread.
OpenDiff(spec DiffSpec) error
// OpenDocument opens a document in the active editor group with the title and the preview of the spec, reading a provided one
// off the UI thread as OpenDiff does. It fails as OpenDiff does, with ExtensionDocumentInvalid for the URI. Call it on the UI
// thread.
OpenDocument(spec OpenSpec) error
// ActiveMergeEditor describes the merge editor that is in front in the scope (SPEC §9.11): false when the active tab of the active
// editor group is not one. It is how a command that works on the merge in front (Git's "Compute Conflicts With Git") finds its file.
// It is false in a scope that has no editors. Call it on the UI thread.
ActiveMergeEditor() (ActiveMerge, bool)
// ProvideMultiDiff registers the provider of the sets of files of the multi-file diff editor of a kind (SPEC §10.30; VS Code's
// IMultiDiffSourceResolver). The window asks it for the files of a set when the set is opened, when the provider says it changed,
// and when a saved editor of the set comes back after a restart. It fails with ExtensionMultiDiffInvalid for a kind that is not a
// word or a provider with no Resources, ExtMultiDiffKindTaken when the window tab has the kind already,
// ExtensionDocumentUnavailable when the scope cannot show documents, and ExtensionDeactivated after the activation ended.
ProvideMultiDiff(p MultiDiffProvider) (MultiDiffRegistration, error)
// OpenMultiDiff opens the multi-file diff editor of a set (VS Code's _workbench.openMultiDiffEditor): one scrolling editor with a
// section for each file. The editor opens at once and fills in when the provider has made the files off the UI thread; the same
// set that is open is shown again, in its tab. It fails with ExtensionMultiDiffInvalid for a spec with a provider's set and a
// fixed one, or with neither, ExtMultiDiffKindUnknown for a kind no provider has, ExtensionDocumentUnavailable when the scope
// cannot open documents, ExtensionDeactivated, and returns ExtDocumentShowUnavailable when the window tab is not on screen. Call it
// on the UI thread.
OpenMultiDiff(spec MultiDiffSpec) error
// Tabs lists the tabs of the text editors and diff editors of the window tab, group by group, in the order of the groups.
Tabs() []DocumentTab
// CloseTabs closes the tabs, the way the close button does: a tab with unsaved changes asks first. It returns the number of
// tabs that were found (a tab that is gone is skipped). Call it on the UI thread.
CloseTabs(tabs ...DocumentTab) int
// CloseTabsAs closes the tabs the way how says: asking (CloseTabs), saving first, or dropping the unsaved changes. A save is
// not finished when it returns: the tabs close when their documents are written, and the count is that of the tabs that were found.
// Call it on the UI thread.
CloseTabsAs(how TabClose, tabs ...DocumentTab) int
// Dirty lists the URIs of the open files that have unsaved changes, in the order they were opened; an untitled document is not
// a file and is left out. It is empty in a scope that cannot show documents. Call it on the UI thread.
Dirty() []string
// SaveAll saves the open documents with these URIs, the way the Save command does, and returns when every one is written
// (VS Code's TextDocument.save of each). A document that is not open or has no unsaved changes is skipped. It blocks, so call it
// off the UI thread. It fails with ExtensionDocumentUnavailable when the scope cannot save documents, with ExtDocumentSaveUnavailable
// when the window tab is not on screen, with ExtDocumentNotSaved for the first document that was not saved (the window tab shows
// why), with the error of ctx when it ends first, and with ExtensionDeactivated after the activation ended.
SaveAll(ctx context.Context, uris []string) error
// QuickDiffOriginal returns the text the primary quick diff provider of the file with the URI (file:///path) says it is compared with,
// the one the marks of the editor use (SPEC §10.30 "Quick diff"): the index version of a file of a Git repository. ok is false when no
// provider has an original for the file. The extension that makes the original needs no call to this; it is for an extension that
// works on the modified lines (the format on save of modifications of the window uses it). It may block (it asks the providers), so
// call it off the UI thread. It fails with ExtensionQuickDiffUnavailable in a scope that has no editors, with the error of ctx when
// it ends first, and with ExtensionDeactivated after the activation ended.
QuickDiffOriginal(ctx context.Context, uri string) (text string, ok bool, err error)
// LineChanges compares two texts by lines, with the diff of the quick diff marks and of the diff editor, and returns the changed
// blocks of the modified text against the original (VS Code's ILineChange; SPEC §10.30 "The peek"): the lines of a text that ends
// with a line break have an empty last line, "\r\n" and "\n" end a line alike, and white space at the ends of lines counts. It is
// how a command that stages or reverts the lines a selection touches finds them. It runs on the calling goroutine (the diff has a
// time limit of one second, after which the texts are one change) and stops with ctx. It fails with ExtensionQuickDiffUnavailable
// in a scope that has no editors, with the error of ctx when it ends first, and with ExtensionDeactivated after the activation
// ended.
LineChanges(ctx context.Context, original, modified string) ([]LineChange, error)
}
Documents reads the documents of the scope: the open ones, and the files of the folder of a workspace scope.
type EditorActionSpec ¶
type EditorActionSpec struct {
// Command is the id of the command the icon runs: a command of the extension or of the editor.
Command string
// Icon is the name of the Codicon of the icon.
Icon string
// Tooltip is the text of the hover and the label in the "..." menu; the title of the command when empty.
Tooltip string
// When is a when-clause under which the icon is shown, read over the keys of the window and those that describe the
// editor the group shows: activeEditor (the type of the input), resourceLangId, resourceExtname, resourceFilename,
// resourceScheme and activeEditorIsDirty. Empty is always.
When string
// Order orders the icons of one extension, the lowest first.
Order float64
}
EditorActionSpec declares an editor title action: a micro icon at the right end of the tab strip of every editor group (SPEC §10.15 "Editor title action"). The icons are ordered by extension (in the order of activation) and Order; those that do not fit go into a "..." menu. The command is run with the argument {"groupId": n}, the group whose strip the icon is in (GroupOfArgs reads it), so that an action such as Open Preview to the Side opens its tab in that group.
type EditorDecorations ¶
type EditorDecorations interface {
// Set replaces everything the key holds with the annotations of the document at uri (file:///path, untitled:1). The key names the
// set, among the sets of the extension: a Set with a key that exists replaces its set whatever its document was, and an empty list
// removes it. The editors that show the document draw the annotations at once, those that open it later when they open. It fails
// with ExtensionEditorDecorationsInvalid for an empty key or URI, a negative line or more than MaxLineAnnotations annotations,
// ExtensionEditorDecorationsUnavailable in a scope that has no editors (a host without a workbench) and ExtensionDeactivated after
// the activation ended.
Set(key, uri string, annotations []LineAnnotation) error
// Clear removes the set of the key, if there is one. It happens by itself when the activation ends.
Clear(key string)
}
EditorDecorations shows annotations in the editors of the documents of the scope.
type EditorDrag ¶
type EditorDrag interface {
// Move tells the window that the pointer is at pos, in the coordinates of the window (what a pointer event of Glutter
// gives as its position).
Move(pos ui.Offset)
// End ends the drag with the pointer at pos. With drop set the tab is opened where the pointer is, if that is a place a
// tab can go, and End reports whether it was; without it (the drag was cancelled) nothing is opened. The error is that of
// Create or of the window failing to show the tab.
End(pos ui.Offset, drop bool) (opened bool, err error)
}
EditorDrag is the drag that Editors().BeginDrag started. Its methods run on the UI thread.
type EditorKind ¶
type EditorKind struct {
// Create makes the content of a tab: for a tab that Open made, with the state Open was given (as JSON), and for a tab
// that comes back after a restart, with the state it saved (nil when it saved none). The title and the marks may be
// set on tab at once. It is called once for each tab, on the UI thread.
Create func(tab EditorTab, state json.RawMessage) (EditorTabContent, error)
}
EditorKind is how an extension makes the content of the tabs of one kind.
type EditorKindSpec ¶
type EditorKindSpec struct {
// ID identifies the kind. It starts with the id of the extension and a dot (emetos.remotework.page).
ID string
// Name is the name of the kind, the title of a tab that has not set one.
Name string
// Icon is the name of the Codicon in the tab ("note", "comment-discussion"); may be empty.
Icon string
}
EditorKindSpec declares a kind of editor tab: a tab in the editor area with no file, of which several can be open (SPEC §10.15 "Editor tab"). The extension gives the kind its content with Editors().Provide and opens tabs of it with Editors().Open; the tabs come back when Emetos restarts, with the state they saved.
type EditorOpenOptions ¶
type EditorOpenOptions struct {
// Group is the id of the group to open the tab in (see GroupOfArgs); 0 is the active group. A group that is gone
// means the active group.
Group int
// Inactive opens the tab without making it the active tab of the group.
Inactive bool
}
EditorOpenOptions say where Editors().Open puts a tab.
type EditorRevealReply ¶
type EditorRevealReply struct {
URI string `json:"uri"`
}
EditorRevealReply is the reply of TopicEditorReveal.
type EditorRevealRequest ¶
type EditorRevealRequest struct {
URI string `json:"uri"`
Line int `json:"line,omitempty"`
Col int `json:"col,omitempty"`
}
EditorRevealRequest is the payload of TopicEditorReveal: show the open document in the editor of the workspace with the cursor at Line and Col (zero-based, Col in bytes).
type EditorSelection ¶
type EditorSelection struct {
URI string `json:"uri"`
// Selections are all the selections of the editor; the first is the primary one.
Selections []Selection `json:"selections"`
}
EditorSelection is the payload of TopicEditorSelectionChanged.
type EditorTab ¶
type EditorTab interface {
// ID is the instance id of the tab, unique in the workspace; it is kept across restarts.
ID() string
// Kind is the id of the kind of the tab.
Kind() string
// SetTitle sets the name on the tab; SetHint the text of its tooltip (the title when empty).
SetTitle(title string)
SetHint(hint string)
// SetDirty puts the dot of unsaved work on the tab and SetBusy the mark of work that goes on. Both are marks and
// nothing else: closing a dirty tab asks nothing, so an extension keeps its data in the state it saves.
SetDirty(dirty bool)
SetBusy(busy bool)
// SetIcon changes the Codicon of the tab (a name such as "terminal-bash"; an unknown name or "" takes the icon of the
// kind) and the color of the icon: the id of a color of the theme, of which Emetos paints the sixteen terminal.ansi*
// ones (terminal.ansiRed); "" is the color of the tab's text. The icon and its color are kept in the state of the
// window with the tab.
SetIcon(icon, color string)
// Refresh builds the widget of the tab again.
Refresh()
// Reveal makes the tab the active tab of its group (and the group the active group); with focus the keyboard focus
// goes into it.
Reveal(focus bool)
// Group is the id of the group that shows the tab, or 0 when it is in none.
Group() int
// Close closes the tab, without asking.
Close()
}
EditorTab is one tab of a kind the extension provides. Its methods run on the UI thread.
type EditorTabContent ¶
type EditorTabContent struct {
// Build makes the widget of the tab; like the widget of a view it is built inside a box that gives it the constraints
// of the editor area, clips what it paints, keeps the keyboard focus and catches a panic.
Build func(bc widgets.BuildContext) widgets.Widget
// SaveState returns the state of the tab that is kept in the state of the window (a value that encodes to JSON, nil for
// none). It is called when the tab goes off screen, when the extension is deactivated and when the window state is
// written. The state is given to the kind's Create when the tab comes back, and is copied when the tab is split.
SaveState func() (any, error)
// Save, when set, makes closing the tab while it is dirty (SetDirty) ask, as for a document: "Do you want to save the changes you
// made to <title>?" with Save, Don't Save and Cancel. The host calls it on the UI thread when the user answers Save; it writes
// the changes of the tab and calls done(true) when they are written and the tab has cleared its dirty mark (SetDirty(false)),
// or done(false) when they could not be, which keeps the tab open. done may be called later, from the UI thread (after Post).
// Don't Save closes the tab and drops its changes (OnClose is called). When the window closes and files.hotExit keeps the
// unsaved work for the next start, nothing is asked: the tab is restored with the state SaveState returned, so a tab with a
// Save puts its unsaved changes in that state. Without Save a dirty mark is only a mark and closing asks nothing.
Save func(done func(saved bool))
// OnClose is called when the tab is closed for good (not when it moves to another group, nor when the extension is
// deactivated); the state of the tab is dropped after it.
OnClose func()
// AllowCommand, when set, is asked while the keyboard focus is in the tab and a key press is bound to a command; false
// leaves the key to the focused widget of the tab (ViewContent.AllowCommand has the details). A terminal in an editor
// tab uses it as the terminal in the panel does.
AllowCommand func(commandID string) bool
}
EditorTabContent is what an extension puts in a tab. All the functions run on the UI thread, and a panic in any of them deactivates the extension in the scope, as for a view (ViewContent).
type Editors ¶
type Editors interface {
// Provide sets how the tabs of a kind the manifest declares are made, and makes the tabs of the kind that came back
// from the last session (and wait for the extension). It fails with ExtensionEditorKindNotDeclared when the manifest
// does not declare the kind, ExtensionEditorKindProvided when the activation provided it already and
// ExtensionEditorKindInvalid when Create is nil.
Provide(kindID string, kind EditorKind) error
// Open opens a new tab of the kind, whose Create gets state (any value that encodes to JSON, or nil), and returns it.
// It fails with ExtensionEditorKindNotProvided when the activation did not provide the kind, and with the error of
// Create.
Open(kindID string, state any, opts EditorOpenOptions) (EditorTab, error)
// Tabs are the open tabs of the kind that have their content, in the order they were made.
Tabs(kindID string) []EditorTab
// BeginDrag starts the drag of something of the extension (a terminal of its list, say) toward the editor area: a
// press on the widget of the extension that moves past a few pixels calls it, then the widget's pointer events call
// Move and End on the returned EditorDrag, with the positions of the window. The window shows the label at the pointer
// and highlights where a tab would go, as it does for the drag of a tab; when the pointer is released over the tab strip
// or the editor area of a group, a tab of the kind is opened there (in a new group beside it at the edges of the area)
// whose Create gets state, as Open's does. It fails with ExtensionDeactivated, ExtensionEditorsUnavailable,
// ExtensionEditorKindNotProvided, ExtensionEditorStateInvalid and the window's ExtEditorsDragBusy (another drag is going on).
BeginDrag(kindID, label string, state any) (EditorDrag, error)
// OpenProposedChange shows a change that is proposed to a file in the diff editor and waits for the user's answer (SPEC
// §10.16 "As built (step 13.3)"). The tab has the current text of the file on the left, read-only, and the proposed
// text on the right, which the user may edit; its title has Accept and Reject. The call returns when the user accepts
// or rejects, or closes the tab, which is a rejection, and gives the text of the right side then. Nothing is written
// to a file: the right side is a document of its own, and what happens to the file is up to the caller. It
// blocks, so it is called from a goroutine of the extension and never from the UI thread. When ctx ends, or the
// extension is deactivated, the tab is closed and the call fails with the error of the context
// (ExtensionProposedChangeCancelled); it fails with ExtensionProposedChangeInvalid for a change with no URI,
// ExtensionDeactivated and ExtensionEditorsUnavailable (the scope has no editor area).
OpenProposedChange(ctx context.Context, change ProposedChange) (ProposedResult, error)
}
Editors gives the extension the tabs of the editor area.
type Event ¶
type Event struct {
// Topic is the dotted name of the event: emetos.document.opened, markdown.preview.open.
Topic string
// Publisher is the id of the extension that published the event, or "emetos" for the core events.
Publisher string
// Scope is the window tab the event was published in.
Scope ScopeInfo
// Seq is the sequence number of the event: it grows with every event published in the scope, so it orders them. For
// a batch it is the number of the last value.
Seq uint64
// Data is the JSON of the value. For a batch it is the last value of the batch.
Data json.RawMessage
// Batch holds every value of the frame, oldest first, for the events of a fast topic (typing: emetos.document.changed
// and emetos.editor.selectionChanged, and the topics an extension declares with EventSpec.Fast): they are delivered
// once per frame with every change of that frame. It is nil for any other event, and never empty for a fast one.
Batch []json.RawMessage
}
Event is something that happened, as a subscriber or a handler receives it (SPEC §10.15 "Events"). It is a copy: the value was encoded to JSON when it was published, and every receiver gets bytes of its own, so nothing a receiver does reaches the publisher or another receiver.
type EventDecl ¶
type EventDecl struct {
// Publishes are the topics the extension publishes. The topics under its own id (the id and a dot) are its own
// without being listed; list one to make it Fast, and list the topics outside its id that it may publish. No two
// extensions may declare a topic that is under the id of a third one, or one of Emetos.
Publishes []EventSpec
// Handles are the topics outside its id that the extension handles with Events().Handle.
Handles []string
// Subscribes are the topics and patterns the extension subscribes to; the Extensions page shows them, and nothing
// stops an extension from subscribing to others inside its scope.
Subscribes []string
// CrossTab are the topic patterns the extension may receive from, or ask of, other window tabs (SPEC §10.15 "Event
// sharing"). Only topics within these ever cross a link, and only these are ever asked about: a subscription or a
// request with a topic outside them fails with EventCrossTabNotDeclared.
CrossTab []string
}
EventDecl are the event topics a Manifest declares.
type EventHandler ¶
EventHandler answers a request: it receives the event, on the UI thread, and returns the value of the reply or an error. The reply is copied like any value. An error that it returns reaches the requester with the tag EventHandlerFailed and is not a failure of the extension; a panic is. ctx ends when the request is answered, times out or is cancelled, or when the extension is deactivated.
type EventReply ¶
EventReply is the function an AsyncEventHandler calls with its answer.
type EventSpec ¶
type EventSpec struct {
// Topic is the dotted topic, such as git.status.changed. It may be one that the extension owns (under its id) or
// one it declares to publish (ownership, below).
Topic string
// Fast marks a stream that is delivered once per frame as a batch (Event.Batch), as typing is.
Fast bool
}
EventSpec declares a topic of the Manifest.
type Events ¶
type Events interface {
// Publish copies the value (it must encode to JSON) and delivers it to the subscribers of the topic later. It fails
// with EventTopicInvalid, EventTopicNotOwned or EventValueInvalid.
Publish(topic string, value any) error
// Subscribe calls fn, on the UI thread, with every event whose topic matches the pattern (MatchTopic), and returns the
// function that stops it. The calls stop when the extension is deactivated. A panic in fn deactivates the extension. It
// fails with EventPatternInvalid.
//
// With FromOtherScopes or FromScopes the extension also hears the events of other window tabs, along the links the
// user allowed (SPEC §10.15 "Event sharing"); the pattern must be among the CrossTab topics of the Manifest or
// Subscribe fails with EventCrossTabNotDeclared. The events of the own scope are always delivered.
Subscribe(pattern string, fn func(Event), opts ...SubscribeOption) (cancel func(), err error)
// Request sends the value to the handler of the topic, which may belong to any extension of the scope, and calls
// reply once, on the UI thread, with the reply of the handler or an error: EventNoHandler when nothing handles the
// topic, EventTimeout when the handler does not answer in time (when ctx has a deadline, then at the deadline, else
// after 10 seconds), EventCanceled when ctx is cancelled, EventHandlerFailed with the error the handler returned,
// EventHandlerPanicked when it panicked, EventHandlerGone when its extension was deactivated before it answered. It
// never blocks. It fails at once, without calling reply, with EventTopicInvalid or EventValueInvalid; reply is not
// called when the requesting extension was deactivated.
//
// With ToOtherScopes or ToScopes the handler is looked for in those window tabs, not in the own scope, and the
// request goes along the link that lets that tab's events reach this one (SPEC §10.15 "Event sharing"); the topic
// must be among the CrossTab topics of the Manifest (EventCrossTabNotDeclared). When no link exists the user is
// asked once; the reply may then carry EventSharingDenied, EventSharingRefused, EventSharingPrivate or
// EventSharingRevoked.
Request(ctx context.Context, topic string, value any, reply func(Event, error), opts ...RequestOption) error
// Handle makes fn the handler of requests of the topic, which the extension owns. A topic has one handler in a scope:
// a second Handle fails with EventHandlerTaken. It fails with EventTopicInvalid or EventTopicNotOwned.
Handle(topic string, fn EventHandler) error
// HandleAsync is Handle for a handler that answers later (see AsyncEventHandler).
HandleAsync(topic string, fn AsyncEventHandler) error
}
Events is how extensions talk: publish and subscribe, request and reply, inside one scope (SPEC §10.15). A topic is dotted segments of letters, digits, hyphens and underscores (CheckTopic). Delivery is asynchronous, on the UI thread, in order per publisher and topic; a publisher's events are also delivered to its own subscribers.
An extension publishes and handles only the topics under its own id and those it declares in the Manifest; Emetos publishes the core events (the Topic constants below) in every workspace scope.
type Extension ¶
type Extension interface {
// Manifest describes the extension. It is read before any activation, and what it declares (commands, menu items,
// keybindings) is there before the extension is activated.
Manifest() Manifest
// Activate starts the extension in one scope. ctx is cancelled when the extension is deactivated there; api is
// bound to the scope and stops working then. Contributions made through api are removed at deactivation. An error
// from Activate, or a panic, deactivates the extension in this scope for the rest of the session.
Activate(ctx context.Context, api API) error
}
Extension is what an extension's package provides.
type Factory ¶
type Factory func() Extension
Factory makes an Extension. Emetos calls it once to read the Manifest, and again for every scope in which the extension is activated, so two window tabs never share an instance. It must not start anything: all the work is in Activate.
type FileChange ¶
type FileChange struct {
// Kind is one of FileCreated, FileChanged, FileDeleted, FileRenamed, FileRescan and FileListed.
Kind string `json:"kind"`
// Path is the path relative to the folder, with forward slashes ("." for the folder itself).
Path string `json:"path,omitempty"`
// OldPath is where a renamed item was, in the same form.
OldPath string `json:"oldPath,omitempty"`
}
FileChange is one change of a file or folder of the workspace.
type FileChooser ¶
type FileChooser interface {
// Open shows the dialog and waits for the user: it returns the path of the file chosen, or an empty path and no error when
// the dialog was closed without a choice. It blocks, so it is called from a goroutine of the extension and never from the
// UI thread. It fails with ExtensionFileChooserUnavailable in a scope that has no dialog (a desktop without the file
// chooser portal, a scope that is not on screen), ExtensionDeactivated after the activation ended, and with the error of the
// desktop otherwise. When ctx ends the call returns its error.
Open(ctx context.Context, opts FileChooserOptions) (string, error)
// Save shows the dialog of the desktop that asks where to write a file (SPEC §10.21: the export of a result), with
// opts.Name as the name it starts with. The rules are those of Open: it returns the path chosen, or an empty path and no error
// when the dialog was closed without a choice; it blocks, so it is called from a goroutine of the extension; it fails with
// ExtensionFileChooserUnavailable, ExtensionDeactivated and the error of the desktop. The desktop's dialog asks about
// overwriting a file; the extension writes the file it is given.
Save(ctx context.Context, opts FileChooserOptions) (string, error)
}
FileChooser asks the user for a file with the file dialog of the desktop.
type FileChooserOptions ¶
type FileChooserOptions struct {
// Title is the title of the dialog; the desktop's own when empty.
Title string
// AcceptLabel is the text of the button that accepts the dialog ("Add"); the desktop's own when empty.
AcceptLabel string
// Filters are the kinds of file the dialog offers; the first is chosen when it opens.
Filters []FileFilter
// Folder is the folder the dialog opens in; the desktop's own when empty.
Folder string
// Directory makes the dialog choose a folder instead of a file (a clone's destination); Filters do not apply. Save ignores it.
Directory bool
// Name is, for FileChooser().Save, the file name the dialog starts with ("result.csv"); Open ignores it.
Name string
// Save is set by FileChooser().Save for the host: the dialog asks for a file to write, not to read. An extension leaves it
// alone.
Save bool
}
FileChooserOptions say what the dialog of FileChooser().Open asks for.
type FileCoverage ¶
type FileCoverage struct {
// URI is the file (file:///path).
URI string
// Statement is the statement coverage and Branch and Declaration the others, nil when not measured.
Statement CoverageCount
Branch *CoverageCount
Declaration *CoverageCount
// Data is the value LoadDetailedCoverage gets back, so the extension can keep its own handle on the file's data.
Data any
}
FileCoverage is the coverage of a file (VS Code's FileCoverage): the statements, and optionally the branches and the declarations.
type FileDecoration ¶
type FileDecoration struct {
// Badge is a short text drawn at the end of the row: one or two characters ("M", "U", "↓A"). A longer one makes the decoration
// invalid. Icon wins over it when both are set.
Badge string
// Icon is the name of a Codicon drawn instead of the badge ("lock-small").
Icon string
// Tooltip is the hover of the row; the tooltips of several providers are joined with " • ".
Tooltip string
// Color is the id of the theme color the name and the badge are drawn in ("gitDecoration.modifiedResourceForeground"). A
// color the theme does not know leaves the color of the name as it is.
Color string
// Propagate shows the decoration in the folders above the file too: a folder with such a file is drawn in the color with a small
// dot (VS Code's propagate).
Propagate bool
// Priority orders the decorations several providers give for a file, and the colors that a folder takes from the files below
// it: the higher goes first. 0 is the default. VS Code gives every extension the same weight; Git uses it to put a conflict
// (4) before an ignored file (3), a modified file (2) and the others (1).
Priority int
}
FileDecoration is what an extension says about a file (VS Code's FileDecoration).
func (FileDecoration) IsEmpty ¶
func (d FileDecoration) IsEmpty() bool
IsEmpty says that the decoration says nothing (no color, badge, icon or tooltip); the host drops it, as VS Code does.
type FileDecorationProvider ¶
type FileDecorationProvider interface {
// Decoration is the decoration of the file at uri (file:///path), ok false for none. It is called on the UI thread, for the
// files the views show and for those the extension fired, and its answer is kept until Fire says it may have changed: answer
// from memory, fast. An answer that takes over a millisecond is logged, and a provider that does so too often is not asked for
// new files any more. A panic fails the extension. An invalid decoration (a longer badge, or an empty one) is logged and dropped.
Decoration(uri string) (decoration FileDecoration, ok bool)
}
FileDecorationProvider answers for the files (VS Code's FileDecorationProvider, without the promise: the answer is from memory).
type FileDecorations ¶
type FileDecorations interface {
// Fire says that the decorations of the files may have changed: they are asked again, and the views that show them (and the
// folders above them) are drawn again if the answer is another. With no URI everything the provider said is forgotten. It
// may be called from any goroutine; the questions are asked on the UI thread.
Fire(uris ...string)
// Dispose removes the provider and its decorations. It happens by itself when the activation ends.
Dispose()
}
FileDecorations is a registered provider.
type FileEntry ¶
type FileEntry struct {
// Path is relative to the folder, with forward slashes ("." is the folder itself); Name is its last element.
Path string `json:"path"`
Name string `json:"name"`
// Kind is EntryFile, EntryDir, EntrySymlink or EntryOther. TopicFilesStat follows a link that stays inside the folder
// and reports what it points to, with Symlink true.
Kind string `json:"kind"`
Symlink bool `json:"symlink,omitempty"`
Size int64 `json:"size"`
ModTime time.Time `json:"modTime"`
}
FileEntry is a file, a folder or a link of the folder of the workspace.
type FileFilter ¶
type FileFilter struct {
// Name is what the dialog's menu shows.
Name string
// Patterns are globs such as "*.pub"; the dialog matches them as written, so write both cases for a name that may have
// either.
Patterns []string
}
FileFilter is a kind of file a file dialog shows ("Public keys", "*.pub").
type FileList ¶
type FileList struct {
// Files are the paths relative to the folder, with forward slashes, of the files the quick open lists (the exclusions
// of files.exclude, search.exclude and the ignore files apply).
Files []string
// Complete tells that the walk of the folder has finished; until it has, the list grows and TopicFilesChanged says so
// with FileListed.
Complete bool
}
FileList is the files of the folder of the workspace.
type FileReplacement ¶
type FileReplacement struct {
// Path is the path relative to the folder, with forward slashes.
Path string
// Replacements are the changes of the file; they must not overlap.
Replacements []TextReplacement
}
FileReplacement is the replacements of one file that no editor has open.
type FileViewContent ¶
type FileViewContent struct {
// Build makes the widget of the view, inside a box (see EditorTabContent.Build). It is built again after Refresh.
Build func(bc widgets.BuildContext) widgets.Widget
// Close is called when the editor tab closes, the extension is turned off or the view fails; it releases what the
// view subscribed to.
Close func()
}
FileViewContent is the content of one file view in one editor tab.
type FileViewOpenOptions ¶
type FileViewOpenOptions struct {
// Side opens it in the group on the side of the active group (made when there is none), as "Open to the Side" does;
// otherwise the active group shows it.
Side bool
// Group is the id of the group whose active text editor shows the document when the uri is empty (see GroupOfArgs); 0
// is the active group.
Group int
}
FileViewOpenOptions say how FileViews().Open shows a document.
type FileViewProvider ¶
type FileViewProvider struct {
// Open makes the content of the view for the document of an editor tab, the first time the tab shows the view. A
// returned error makes the tab fall back to the Text view.
Open func(doc DocumentHandle, tab FileViewTab) (FileViewContent, error)
}
FileViewProvider is how an extension makes the view of a document.
type FileViewSpec ¶
type FileViewSpec struct {
// ID identifies the view. It starts with the id of the extension and a dot (emetos.markdown.preview).
ID string
// Name is the label of the micro-tab ("Preview").
Name string
// Icon is the name of the Codicon of the micro-tab; may be empty.
Icon string
// Languages are the ids of the languages of the files the view is for (markdown); Globs are patterns of file names
// (*.csv, docs/**/*.md) matched against the base name and the path relative to the folder. A file is selected by one
// of either. A spec with neither is invalid.
Languages []string
Globs []string
// Order orders the views among those of one file, the lowest first (0 sorts after the ones with an order).
Order int
}
FileViewSpec declares a file view: micro-tabs inside the editor tab of a file (SPEC §10.15 "File view"). The tab of a file the spec selects shows Text first and then the views of the extensions, in the order of Order.
type FileViewTab ¶
type FileViewTab interface {
// Refresh builds the widget of the view again.
Refresh()
}
FileViewTab is the tab a file view is open in.
type FileViews ¶
type FileViews interface {
// Provide sets how the view is made. It fails with ExtensionFileViewNotDeclared, ExtensionFileViewProvided and
// ExtensionFileViewInvalid (Open is nil).
Provide(viewID string, p FileViewProvider) error
// Open shows the open document or the file with the URI in the view (an editor tab of the file is made when there is
// none in the group); an empty uri is the document of the active text editor of opts.Group. It fails when the scope
// cannot show editors or there is no such document; a view that is not available for the file leaves the file in Text.
Open(uri, viewID string, opts FileViewOpenOptions) error
}
FileViews gives the file views the manifest declares their content.
type FilesChanged ¶
type FilesChanged struct {
Changes []FileChange `json:"changes"`
}
FilesChanged is the payload of TopicFilesChanged: what the watcher reported in one go, at most MaxFileChanges of it (a larger batch is one FileRescan of ".").
type FilesListReply ¶
type FilesListReply struct {
Entries []FileEntry `json:"entries"`
More bool `json:"more,omitempty"`
}
FilesListReply is the reply of TopicFilesList.
type FilesListRequest ¶
type FilesListRequest struct {
Path string `json:"path,omitempty"`
Depth int `json:"depth,omitempty"`
Offset int `json:"offset,omitempty"`
Limit int `json:"limit,omitempty"`
}
FilesListRequest is the payload of TopicFilesList. Path is a folder relative to the workspace folder ("" or "." for the folder itself); Depth is how deep to go (1, the default, lists the children; at most MaxFilesListDepth); the entries are in the order of a walk that sorts each folder by name and lists a folder before what is in it. Offset skips that many entries and Limit caps the reply (DefaultFilesListLimit, at most MaxFilesListLimit): the reply says More when the walk has entries left, and the next request asks with Offset + len(Entries).
type FilesPathRequest ¶
type FilesPathRequest struct {
Path string `json:"path"`
MaxBytes int64 `json:"maxBytes,omitempty"`
}
FilesPathRequest is the payload of TopicFilesStat and TopicFilesRead: a path relative to the workspace folder, with forward slashes, no "..", not absolute. MaxBytes, for a read, lowers MaxFilesReadSize.
type FilesReadReply ¶
type FilesReadReply struct {
Path string `json:"path"`
Text string `json:"text"`
Size int64 `json:"size"`
ModTime time.Time `json:"modTime"`
}
FilesReadReply is the reply of TopicFilesRead: the bytes of the file as a string, which must be valid UTF-8 (a byte order mark and the line endings stay as they are).
type FormattingOptions ¶
FormattingOptions are the options of a formatting request.
type FormattingProvider ¶
type FormattingProvider interface {
ProvideFormatting(ctx context.Context, doc TextDocument, opts FormattingOptions) ([]RangeEdit, error)
}
FormattingProvider formats a whole document; a provider that also implements RangeFormattingProvider formats ranges. The formatter is known to editor.defaultFormatter by the id of the extension.
type HeadlessView ¶
type HeadlessView interface {
// Size is the size of the view in pixels.
Size() Size
// OnFrame sets the function that gets the pictures of the view: one when the view is made, and one each time the view
// changed. fn runs on a goroutine of the view, never on the UI thread and never twice at once, so it may encode and
// send; a view whose pictures are not taken fast enough drops the ones in between, the latest is always the next. The
// image belongs to fn. It is called until Close: a call that is running when Close is called finishes (Close waits for it,
// at most a quarter of a second, so that a function that closes the view itself does not wait for itself), and none starts
// after Close has returned.
OnFrame(fn func(frame *image.RGBA))
// Refresh draws the view again, even if nothing changed, and hands the picture over: the client lost its picture.
Refresh()
// Resize gives the view a new size. It fails with ExtensionHeadlessSize for a size that is not allowed.
Resize(size Size) error
// SendKey delivers a key event to the view as the platform would: through the focus and the key handling of Glutter,
// so the editor, the menus and the dialogs of the view take it.
SendKey(event KeyEvent)
// SendPointer delivers a mouse event, and SendScroll a scroll.
SendPointer(event PointerEvent)
SendScroll(event ScrollEvent)
// SetClipboard sets the clipboard of the view, the text a paste in the view takes (the client's clipboard).
SetClipboard(text string)
// OnCopy sets the function that gets the text the user copies or cuts in the view. It runs on the UI thread: hand the
// text to a goroutine and return.
OnCopy(fn func(text string))
// OnNotification sets the function that gets the notifications the workspace raises from now on (the ones that would
// show as a toast: a silent one, made while do not disturb is on, is left out). While a function is set the view draws
// no toast for them, so the client shows them in its own way, and the buttons they carry are pressed with
// RunNotificationAction. fn runs on the UI thread: hand the notification to a goroutine and return. nil takes the
// function away, and the view draws the toasts again.
OnNotification(fn func(n ViewNotification))
// RunNotificationAction presses the button of a notification as its user would in the view: the action runs, in the
// workspace, and the notification closes unless the action keeps it open. It does nothing for a notification that is gone
// or a button that is not there.
RunNotificationAction(id uint64, action int)
// Done is closed when the view ended, whether the extension closed it or Emetos did (the workspace closed, or it opened
// another folder): its widgets are gone and it holds no document. Pictures stop coming before that.
Done() <-chan struct{}
// Close ends the view and frees what it holds: its widgets, its pictures and the editors it opened, which release their
// documents. It does nothing after the first call. The activation ending closes the views it made.
Close()
}
HeadlessView is a second view of the workspace, drawn off screen at a size of its own: a workbench with its own focus, cursors and scroll positions, its own side bar, panel and quick input, over the same documents, so that an edit in one view shows in the other. Emetos draws it with Glutter's software renderer when something in it changes (at most 30 times a second; the UI thread only builds and paints it, the drawing is on a goroutine of the view) and hands the pictures to the extension; the extension hands the input of its user back. Remote Work (SPEC §10.18) is made of it.
A view keeps the commands of the workspace but not the contributions of the extensions to it (their views, menu items and status bar items), and none of the commands that act on Emetos itself: quitting, the window tabs, other workspaces. Its methods may be called from any goroutine.
type HistoryArg ¶
type HistoryArg struct {
// SourceControl is the Handle of the source control.
SourceControl string
// Item is the history item; nil for a command of the title of the view.
Item *HistoryItem
// RefID is the ID of the reference, for the menu of a badge; empty for none.
RefID string
// Range is set when the row opens a range of changes.
Range *HistoryRange
}
HistoryArg is what a menu of the Graph, or the opening of a row, gave a command: VS Code passes (provider, historyItem, refId); Emetos gives one list of objects, [{"sourceControl": "scm1"}, {"historyItem": {...}}, {"historyItemRef": "refs/heads/main"}], which HistoryArgs reads.
func HistoryArgs ¶
func HistoryArgs(args any) (arg HistoryArg, ok bool)
HistoryArgs reads the arguments a menu of the Graph gave a command; ok is false for any other value (the command was run from the palette or by a key).
type HistoryItem ¶
type HistoryItem struct {
// ID identifies the item: a full hash. It is not empty.
ID string
// ParentIDs are the IDs of the parents, the first parent first; none for a root.
ParentIDs []string
// Subject is the first line of the message and Message the whole message.
Subject, Message string
// DisplayID is the short form of the ID ("a1b2c3d").
DisplayID string
// Author and AuthorEmail are the name and the address of the author.
Author, AuthorEmail string
// Timestamp is the time of the item (the author date); the zero time is none.
Timestamp time.Time
// Statistics are the size of the change; nil when the provider did not count it.
Statistics *HistoryStatistics
// References are the references that point at this item.
References []HistoryItemRef
}
HistoryItem is one commit of the history (VS Code's SourceControlHistoryItem).
func (HistoryItem) Ref ¶
func (it HistoryItem) Ref(id string) (HistoryItemRef, bool)
Ref returns the reference of the item with the ID.
type HistoryItemRef ¶
type HistoryItemRef struct {
// ID identifies the reference: "refs/heads/main", "refs/remotes/origin/main", "refs/tags/v1". The menus read it as the context key
// scmHistoryItemRef.
ID string
// Name is what the badge and the pickers show ("main", "origin/main").
Name string
// Revision is the history item the reference points at: a hash.
Revision string
// Category groups the references in the picker of the filter ("branches", "remote branches", "tags").
Category string
// Description is dimmed text after the name in the picker ("a1b2c3d", "Tag at a1b2c3d").
Description string
// Icon is the name of a Codicon drawn in the badge ("git-branch", "cloud", "tag", "target").
Icon string
}
HistoryItemRef is a reference to a history item: a branch, a remote branch or a tag (VS Code's SourceControlHistoryItemRef).
type HistoryOptions ¶
type HistoryOptions struct {
// Skip is how many items to leave out first, and Limit the most items to return (the page).
Skip, Limit int
// RefIDs are what the walk starts from: the Revision of the references of the filter, or their IDs for one with no revision. The
// items are the ones that can be reached from them, newest first with the parents after the children (git's --topo-order).
RefIDs []string
// FilterText is the search of the filter box: the items whose message or author has the text, and the item whose hash starts with
// it. Empty is no filter.
FilterText string
}
HistoryOptions say which history items a provider is asked for (VS Code's SourceControlHistoryOptions).
type HistoryProvider ¶
type HistoryProvider struct {
// Items makes a page of the history. It is required. An empty history is an empty page, not an error.
Items func(ctx context.Context, opts HistoryOptions) ([]HistoryItem, error)
// Refs lists the references: the branches, then the remote branches, then the tags. With ids it lists only the references with these
// IDs (with their latest revision). Required.
Refs func(ctx context.Context, ids []string) ([]HistoryItemRef, error)
// CommonAncestor finds the best common ancestor of the references with these names or IDs, the history item the incoming and the
// outgoing changes are measured from; empty when there is none. Required.
CommonAncestor func(ctx context.Context, refs []string) (string, error)
// OpenCommand is the command the Graph runs when a row is opened (a click, Enter), with the arguments of HistoryArgs: the commit,
// or for the incoming and the outgoing changes the range. Empty: nothing happens.
OpenCommand string
}
HistoryProvider provides the history of a source control (VS Code's SourceControlHistoryProvider). The functions run off the UI thread with a context that is cancelled when the view no longer wants the answer. A panic in one fails the extension (ExtensionHistoryPanicked).
type HistoryRange ¶
type HistoryRange struct {
// Base and Head are the two ends: the changes are from Base to Head.
Base, Head string
// Title is the name of the tab ("Incoming Changes - main ↔ origin/main").
Title string
}
HistoryRange is the range of changes that the incoming-changes and the outgoing-changes row open, and that the first row above the incoming changes opens (VS Code's viewChanges).
type HistoryRefsChange ¶
type HistoryRefsChange struct {
// Added, Removed and Modified are the references.
Added, Removed, Modified []HistoryItemRef
// Silent says that the change happened in the background (an automatic fetch): the Graph refreshes only when it is scrolled to the
// top and shows "Outdated" otherwise.
Silent bool
}
HistoryRefsChange says which references changed (VS Code's SourceControlHistoryItemRefsChangeEvent).
type HistoryRegistration ¶
type HistoryRegistration interface {
// SetCurrentRefs sets the reference of the current branch (VS Code's historyItemRef), the one it tracks (historyItemRemoteRef) and
// the one its merge base is on (historyItemBaseRef); nil for none. The Graph refreshes when the current reference changes and
// draws the incoming and the outgoing changes from the three.
SetCurrentRefs(current, remote, base *HistoryItemRef)
// RefsChanged says that references were added, removed or moved: the Graph refreshes (or shows that it is outdated).
RefsChanged(change HistoryRefsChange)
// Dispose takes the provider away; it happens by itself with the source control and with the activation.
Dispose()
}
HistoryRegistration is a registered history provider of a source control.
type HistoryStatistics ¶
type HistoryStatistics struct {
// Files, Insertions and Deletions are the number of files changed and of lines added and removed.
Files, Insertions, Deletions int
}
HistoryStatistics are the size of the change a history item made (VS Code's SourceControlHistoryItemStatistics).
type Hover ¶
type Hover struct {
// Contents are shown one under the other.
Contents []Markup
// Range is the text the hover is for; the word at the position when nil.
Range *Range
}
Hover is the answer of a hover provider.
type HoverProvider ¶
type HoverProvider interface {
ProvideHover(ctx context.Context, doc TextDocument, pos Position) (*Hover, error)
}
HoverProvider answers hover requests; a nil Hover is no answer.
type InputBox ¶
type InputBox interface {
// Show opens the input box. done is called once, on the UI thread, after the box is hidden: with the text and true when the
// user accepted a valid text, or with an empty text and false when the box was closed without one or another quick input
// took its place. It fails with ExtensionInputBoxUnavailable in a scope that cannot show one (a window tab of an extension
// has none) and with ExtensionDeactivated after the activation ended; done is not called then.
Show(opts InputBoxOptions, done func(value string, ok bool)) error
}
InputBox asks the user for a line of text in the quick input of the window (SPEC §10.3), the way VS Code's showInputBox does.
type InputBoxButton ¶
type InputBoxButton struct {
// Icon is the name of a Codicon ("folder").
Icon string
// Tooltip is the text of the hover of the button.
Tooltip string
}
InputBoxButton is a button inside an input box.
type InputBoxOptions ¶
type InputBoxOptions struct {
// Prompt says what to enter; it is the hint of the input while it is empty (VS Code's prompt and placeHolder in one).
Prompt string
// Value is the text the input starts with; the caret is at its end.
Value string
// Message is a line of text under the input while the text is valid (VS Code's prompt; Prompt is its placeHolder): "Git: https://host"
// over the password that git asks for. A message from Validate takes its place while there is one.
Message string
// IgnoreFocusOut keeps the box open when the user clicks elsewhere or the window loses the focus, as VS Code's ignoreFocusOut does:
// only Enter and Escape end it. A question that a running program waits for (the password git asks) sets it.
IgnoreFocusOut bool
// Password shows a dot for each character typed, as a password box does (VS Code's password option): the text cannot be
// read from the screen or copied. The text still reaches done as typed.
Password bool
// Validate, when set, checks the text on every change and when it is accepted: a message that is not empty is shown under
// the input as an error and the text is not accepted (VS Code's validateInput). It is called on the UI thread.
Validate func(value string) string
// Buttons are buttons inside the box, after the text (VS Code's buttons with the inline location): the one that opens a folder
// chooser beside a path. OnButton is called, on the UI thread, with the index of the button that was pressed, the text in the box and
// a function that replaces the text; a button with no OnButton does nothing.
Buttons []InputBoxButton
OnButton func(index int, value string, setValue func(value string))
// Origin is the screen that shows the box; the zero value is the origin of the command being handled (Origins().Current), which is
// the window of the host for a box that no command asked for. A job that asks later passes the origin it was started from.
Origin Origin
}
InputBoxOptions describe an input box.
type KeyEvent ¶
type KeyEvent struct {
// Kind is whether the key went down, up or repeats.
Kind KeyKind
// Physical is the USB HID usage of the key (Glutter's PhysicalKeyboardKey), which does not depend on the layout.
Physical uint64
// Logical is the ID of the key (Glutter's LogicalKeyboardKey), which does.
Logical uint64
// Text is what the key typed; empty for a release or a key that types nothing.
Text string
}
KeyEvent is a key event of a headless view, with the text it produced, so that the layout and the input method of the keyboard it came from decide what is typed.
type Keybinding ¶
type Keybinding struct {
// Command is the id of the command.
Command string
// Key is the key in the syntax of keybindings.json: ctrl+alt+h, or a chord such as ctrl+k ctrl+h.
Key string
// When is a when-clause over the context keys; empty is always. Use the context keys of the extension itself or
// those of the editor.
When string
// Args are the JSON-compatible arguments the command is run with.
Args any
}
Keybinding binds a key to a command.
type Keybindings ¶
type Keybindings interface {
// Add binds the key.
Add(binding Keybinding) error
}
Keybindings adds the default keybindings of an extension; the user's keybindings.json still wins.
type LanguageServerSpec ¶
type LanguageServerSpec struct {
// ID names the server inside the extension: lowercase letters, digits and hyphens (gopls). Emetos qualifies it with the id
// of the extension: emetos.golang.gopls is the id of the setting emetos.golang.gopls.trace.server.
ID string
// Name is the name shown to the user: the name of the Output channel and of the status bar item.
Name string
// Languages are the ids of the languages the server serves (go). Only documents of these languages are opened on the
// server.
Languages []string
// Program is the program to run, found in PATH unless it has a slash; Args are its arguments.
Program string
Args []string
// Env are extra environment variables ("NAME=value") added to the environment of Emetos.
Env []string
// PathSetting is the key of a setting, written by the user, that holds the path of the program and so overrides Program
// (go.goplsPath). Emetos registers it as a string setting (empty by default) while the extension is enabled in a tab. An
// empty value runs Program.
PathSetting string
// InitializationOptions are sent in initialize as initializationOptions; they must encode to JSON.
InitializationOptions any
// ConfigurationSection is the key of the settings the server reads through workspace/configuration (go.gopls). A request
// for the section of the server's own ID (gopls) or for one below it (gopls.ui) is answered with this key or the one below
// it; any other section is answered with the setting of that name. A change of the section is sent with
// workspace/didChangeConfiguration.
ConfigurationSection string
// WatchedFiles are globs, relative to the folder, of the files whose changes are sent to the server with
// workspace/didChangeWatchedFiles, besides those the server registers itself.
WatchedFiles []string
// OnActivation starts the server when the extension is activated in a tab, without waiting for a document.
OnActivation bool
// OwnUI says that the extension shows the state of the server itself, with LanguageServers().Status and OnChange: Emetos
// makes no status bar item for the server and shows no notification when its program is not found (the line in the
// Output channel and the crash notification stay). The extension then tells the user about a missing program (SPEC
// §10.17 "As built (step 14.1)").
OwnUI bool
// Category is the category of the command <extension id>.restartServer in the command palette ("Go" gives "Go: Restart
// Language Server"); the name of the extension when empty. With several servers the first Category that is not empty
// is used.
Category string
// TraceKey is the key of the setting that traces the communication with the server (see TraceSetting) when the server's
// own VS Code extension has a name for it (rust-analyzer.trace.server); the qualified name of the server plus
// ".trace.server" when empty. Emetos registers it, as it does for the qualified name. The key must be free: the editor and
// the other extensions do not have it.
TraceKey string
}
LanguageServerSpec declares a language server (SPEC §9.12 "Servers and their lifetime"). Emetos starts one server of this kind per window tab, when the first document of its languages opens there (or when the extension is activated, with OnActivation), in the folder of the tab, in a process group of its own, and stops it when the tab closes or the extension is turned off. Its messages go to an Output channel named Name; the language features it offers are merged with those of the providers an extension wrote in Go (Languages().Register...Provider).
type LanguageServers ¶
type LanguageServers interface {
// Status returns the state of the server. A server that is declared but not made yet (the call is made in Activate) is
// idle. It fails with ExtensionServerUnknown for an id the manifest does not declare. Call it on the UI thread.
Status(serverID string) (ServerStatus, error)
// OnChange calls fn, on the UI thread and after the change, whenever the state or the progress of the server changes,
// with the new status, and returns the function that stops the calls. The calls stop with the activation. It fails with
// ExtensionServerUnknown for an id the manifest does not declare. A panic in fn deactivates the extension.
OnChange(serverID string, fn func(ServerStatus)) (cancel func(), err error)
// Restart stops the server, if it runs, and starts it again, forgetting its crashes; an idle server is started and a
// server whose program was not found is looked for again. It is what the command <extension id>.restartServer does. It
// fails with ExtensionServerUnknown, and with ExtensionDeactivated after the activation ended.
Restart(serverID string) error
// ShowOutput shows the Output channel of the server (the channel is named after the server); with preserveFocus the
// keyboard focus stays where it is. It fails with ExtensionServerUnknown.
ShowOutput(serverID string, preserveFocus bool) error
// Commands lists the commands the running server can execute (the commands of executeCommandProvider and those it
// registered); it is empty while the server is not running. It fails with ExtensionServerUnknown. Call it on the UI thread.
Commands(serverID string) ([]string, error)
// ExecuteCommand asks the server to execute one of its commands (workspace/executeCommand) with the arguments, which must
// encode to JSON. The call returns at once; done is called, on the UI thread, with the outcome: nil when the server
// answered, else the error (a server that is not running fails with ExtensionServerNotRunning). The edits the server makes
// meanwhile with workspace/applyEdit are applied like those of any other request. It fails with ExtensionServerUnknown, with
// ExtensionArgumentsInvalid for arguments that do not encode, and with ExtensionDeactivated; done is not called then.
ExecuteCommand(ctx context.Context, serverID, command string, args []any, done func(error)) error
// ApplyCodeAction asks the server for the code actions of the document at the range of req (req.Only lists the kinds wanted,
// such as refactor.rewrite.fillStruct) and applies the first one that is not disabled, the preferred one before the others:
// it is resolved when the server resolves its edit later, its edit is applied (as Documents().Apply does) and its command
// is executed. The call returns at once; done is called, on the UI thread, with the title of the action that was applied
// and nil, with an empty title and nil when the server offers none (or none of the kinds), or with the error. The document
// must be open in the scope. It fails with ExtensionServerUnknown and ExtensionDeactivated; done is not called then.
ApplyCodeAction(ctx context.Context, serverID, uri string, req CodeActionRequest, done func(title string, err error)) error
// SetLauncher gives the server a ServerLauncher, which replaces the fixed Program, Args, PathSetting and InitializationOptions
// of its spec with what the launcher answers at each start (a nil launcher takes it away). Call it in Activate, before the
// first document opens: a server that started already keeps what it runs until it is restarted. It fails with
// ExtensionServerUnknown and with ExtensionDeactivated after the activation ended.
SetLauncher(serverID string, launcher ServerLauncher) error
// Request sends a request of the language server's own protocol (rust-analyzer's rust-analyzer/expandMacro, experimental/parentModule)
// and returns the "result" of the answer as JSON ("null" when the server answers null). params must encode to JSON, and its positions
// are counted as PositionEncoding says. It blocks until the server answers, so call it off the UI thread (a command hands the work to
// a goroutine and comes back with Post; a provider already runs off the UI thread); ctx cancels the wait. It fails with
// ExtensionServerUnknown, ExtensionDeactivated, ExtensionArgumentsInvalid for params that do not encode, ExtensionServerNotRunning
// while the server does not run, and with the error of the server (ServerError) when it answers with one.
Request(ctx context.Context, serverID, method string, params any) (json.RawMessage, error)
// Notify sends a notification of the language server's own protocol (Eclipse JDT LS's java/projectConfigurationUpdate, which it declares
// as a notification: asked as a request it answers "Internal error"). params must encode to JSON, with positions counted as
// PositionEncoding says. It does not wait for the server and returns once the message is queued, so it may be called on the UI thread.
// It fails with ExtensionServerUnknown, ExtensionDeactivated, ExtensionArgumentsInvalid for params that do not encode,
// ExtensionServerNotRunning while the server does not run, and with the error of the connection (NotifyClosed) when it has ended.
Notify(serverID, method string, params any) error
// OnNotification calls fn, on the UI thread, with the params of every notification the server sends with this method
// (experimental/serverStatus), and returns the function that stops the calls. The subscription outlives restarts of the server. The calls
// stop with the activation. It fails with ExtensionServerUnknown. A panic in fn deactivates the extension.
OnNotification(serverID, method string, fn func(params json.RawMessage)) (cancel func(), err error)
// PositionEncoding is the encoding of the positions the running server uses in its messages: "utf-8" (columns count bytes of the
// line, as the positions of this API do), "utf-16" or "utf-32". It is "utf-16", the protocol's default, while the server does not run.
// It fails with ExtensionServerUnknown.
PositionEncoding(serverID string) (string, error)
}
LanguageServers lets an extension follow and control the language servers its manifest declares. The id of a server is the ID of its LanguageServerSpec. The host starts and stops the servers (the activation does not); this is how the extension shows their state and offers their commands.
type Languages ¶
type Languages interface {
// Resolve gives the id of the language called name (an id, an alias or a file extension such as go, golang or py); false
// when none is.
Resolve(name string) (languageID string, ok bool)
// Tokenize splits text into lines and tokens with the grammar of the language; the lines are the lines of text. It fails
// with ExtensionLanguageUnknown for a language that has no grammar. It belongs to the UI thread and costs a
// tokenization of the text, so a caller keeps the answer.
Tokenize(languageID, text string) ([][]Token, error)
// References asks the language servers and the providers for the places that use the symbol at the position of the open
// document with the URI, the declaration included (VS Code's vscode.executeReferenceProvider), and calls done, on the UI
// thread, with the locations or the error. The request runs off the UI thread and ends when ctx does (done then gets
// the error of the context). It fails at once, without calling done, with ExtensionDeactivated, ExtensionDocumentUnavailable
// (the document is not open in the scope, or the scope has no language features) and the tags of document.ParseURI for a
// bad URI; done is called with ExtensionNoProvider when nothing offers the feature for the document, and with the error of
// the provider when every provider that answered failed. The locations are in the order of the providers, without the same
// place twice. Call it on the UI thread.
References(ctx context.Context, uri string, pos Position, done func([]Location, error)) error
// Implementations is References for the implementations of the symbol (vscode.executeImplementationProvider).
Implementations(ctx context.Context, uri string, pos Position, done func([]Location, error)) error
// RegisterCompletionProvider adds a provider of completion items for the documents the selector matches;
// triggerCharacters are the characters that start a request when typed. Each Register method returns the function
// that takes the provider away; it also goes with the activation. They fail with ExtensionDeactivated and
// ExtensionProviderInvalid (a nil provider or a selector that selects nothing).
RegisterCompletionProvider(sel DocumentSelector, p CompletionProvider, triggerCharacters ...string) (dispose func(), err error)
// RegisterHoverProvider adds a hover provider.
RegisterHoverProvider(sel DocumentSelector, p HoverProvider) (dispose func(), err error)
// RegisterSignatureHelpProvider adds a signature help provider; triggerCharacters start a request when typed.
RegisterSignatureHelpProvider(sel DocumentSelector, p SignatureHelpProvider, triggerCharacters ...string) (dispose func(), err error)
// RegisterDefinitionProvider adds a definition provider.
RegisterDefinitionProvider(sel DocumentSelector, p DefinitionProvider) (dispose func(), err error)
// RegisterReferenceProvider adds a references provider.
RegisterReferenceProvider(sel DocumentSelector, p ReferenceProvider) (dispose func(), err error)
// RegisterDocumentSymbolProvider adds a provider of the symbols of a document.
RegisterDocumentSymbolProvider(sel DocumentSelector, p DocumentSymbolProvider) (dispose func(), err error)
// RegisterDocumentHighlightProvider adds a provider of document highlights.
RegisterDocumentHighlightProvider(sel DocumentSelector, p DocumentHighlightProvider) (dispose func(), err error)
// RegisterCodeActionProvider adds a code action provider.
RegisterCodeActionProvider(sel DocumentSelector, p CodeActionProvider) (dispose func(), err error)
// RegisterFormattingProvider adds a formatter; it formats ranges too when it implements RangeFormattingProvider.
RegisterFormattingProvider(sel DocumentSelector, p FormattingProvider) (dispose func(), err error)
// RegisterRenameProvider adds a rename provider.
RegisterRenameProvider(sel DocumentSelector, p RenameProvider) (dispose func(), err error)
// RegisterCodeLensProvider adds a provider of code lenses.
RegisterCodeLensProvider(sel DocumentSelector, p CodeLensProvider) (dispose func(), err error)
// RefreshCodeLenses tells the editors that the code lenses of the providers of this extension (and of the language
// servers, which do the same by themselves) are stale: they ask again. It may be called from any goroutine.
RefreshCodeLenses()
}
Languages gives the extension the grammars of the languages Emetos knows, and takes the language feature providers it writes in Go (SPEC §9.12 "Providers in Go"; the diagnostics of such a provider are set with Problems).
type LaunchRequest ¶
type LaunchRequest struct {
// Folder is the folder of the window tab (empty for a tab with no folder).
Folder string
// Setting reads a setting of the tab: its value as Settings().Get gives it, and false for a key nobody registered. Unlike
// the rest of the settings API it may be called from any goroutine, so that a launcher can read what it needs while it
// runs a program.
Setting func(key string) (any, bool)
}
LaunchRequest is what the host tells a ServerLauncher when it is about to start a server.
type LineAnnotation ¶
type LineAnnotation struct {
// Line is the line, counted from 0 as the positions of the events are. A line the document does not have is not drawn.
Line int
// Text is the text after the line, in the font of the editor, 50 pixels from the end of the text of the line (VS Code's margin). It
// does not move the text, is not selectable and is clipped at the edge of the editor.
Text string
// Color is the id of the theme color the text is drawn in ("git.blame.editorDecorationForeground"); empty, or a color the theme does
// not know, draws it in editorInlayHint.foreground.
Color string
// Hover is a markdown text shown in a hover box when the pointer rests on the annotation; empty for none. A link whose destination is
// command:<id> or command:<id>?<JSON arguments> (an array, or a single value) runs the command, when the command is one of the
// extension itself (declared by its manifest or registered by it); a link to the command of another extension is ignored, and
// so is every other kind of command link (VS Code's isTrusted, narrowed to the extension's own commands).
Hover string
}
LineAnnotation is a text drawn after the end of a line (VS Code's DecorationOptions with an `after` render option).
type LineChange ¶
type LineChange struct {
OriginalStartLineNumber, OriginalEndLineNumber int
ModifiedStartLineNumber, ModifiedEndLineNumber int
}
LineChange is a changed block of lines of a text against its original, VS Code's ILineChange (SPEC §10.30 "The peek"): lines are counted from 1, and an end of 0 says that the side has no lines in the block. An added block has OriginalEndLineNumber 0 and OriginalStartLineNumber the line it follows; a deleted block has ModifiedEndLineNumber 0 and ModifiedStartLineNumber the line the lines were deleted after (0 for the start of the text).
func ReadQuickDiffArgs ¶
func ReadQuickDiffArgs(args any) (uri string, changes []LineChange, index int, ok bool)
ReadQuickDiffArgs reads the arguments QuickDiffArgs made: ok is false for any other value (the command was run from the palette or by a key) and for an index outside the changes.
func (LineChange) Map ¶
func (c LineChange) Map() map[string]any
Map is the change as the argument of a command carries it: an object with the members LineChangeOriginalStart and the others.
type Manifest ¶
type Manifest struct {
// ID is unique and written in lowercase letters, digits and hyphens joined by dots: emetos.markdown, sqltools. The
// settings of the extension are registered under it as prefix (sqltools.connections).
ID string
// Name is the name shown to the user. It is required.
Name string
// Version is the version of the extension, such as 0.1.0.
Version string
// Description says in one sentence what the extension does.
Description string
// ActivationEvents say when the extension is activated in a scope; see OnStartup, OnLanguage, OnFile, OnCommand,
// OnView and OnWindowTab. An extension with none is never activated by itself. The commands in Contributes are
// activation events of their own: running one activates the extension.
ActivationEvents []string
// Contributes are the contributions the extension declares, so that they are there before it is activated.
Contributes Contributes
// Events are the event topics the extension declares (SPEC §10.15 "Events").
Events EventDecl
// Privileges are the privileges the extension asks for (SPEC §10.19 "Privileges"): PrivilegeCommandsExecute.
// The host grants it only to the extensions on its fixed allowlist (emetos.terminal); an extension that declares it and
// is not on it is refused with a problem on the Extensions page (ExtensionPrivilegeRefused) and is not installed.
// CheckManifest refuses a name that is not a privilege (ExtensionPrivilegeUnknown).
Privileges []string
}
Manifest describes an extension (SPEC §10.15).
func (Manifest) HasPrivilege ¶
HasPrivilege tells whether the manifest declares the privilege. Declaring is not being granted: the host refuses an extension that is not on its allowlist and declares one, so an extension that runs has what it declared.
type Marker ¶
type Marker struct {
// Severity is how serious the problem is; an error when zero.
Severity Severity
// Message describes the problem. A marker with no message is dropped.
Message string
// Source is the tool that found the problem ("go vet"); the name of the extension when empty.
Source string
// Code is the code of the problem; may be empty.
Code string
// StartLine, StartColumn, EndLine and EndColumn are the range; a missing end is the start.
StartLine, StartColumn, EndLine, EndColumn int
}
Marker is a problem found in a file, as the Problems panel shows it. Lines and columns count from 1; a column counts UTF-16 units (SPEC §10.13).
type MenuItem ¶
type MenuItem struct {
// Menu is the id of the menu, one of the Menu constants or the ID of a submenu the extension declares
// (Contributes.Submenus).
Menu string
// Command is the id of the command the item runs. An item whose command does not exist is not shown.
Command string
// {"submenu": "git.commit"} entry); its title is the label of the submenu unless Title is set. CheckManifest refuses an item
// that has both, and a submenu that is not declared.
Submenu string
// Title replaces the title of the command in this menu; empty keeps it.
Title string
// Group is the group of the item; the groups of a menu are ordered by name and separated by a line.
Group string
// Order orders the items of a group.
Order float64
// When is a when-clause under which the item is shown; empty is always.
When string
// Args are the JSON-compatible arguments the command is run with.
Args any
}
MenuItem is an item of a menu.
type MergeEditorCompleted ¶
type MergeEditorCompleted struct {
// URI is the result of the merge: the file with the conflict markers that was resolved (file:///path), or the result file of
// "emetos --merge".
URI string `json:"uri"`
}
MergeEditorCompleted is the payload of TopicMergeEditorCompleted.
type MergeLabels ¶
type MergeLabels struct {
// Current is the side of the file as the work tree has it (the part after "<<<<<<<"), Incoming the other one (the part before
// ">>>>>>>"). An empty name keeps the one of the markers.
Current, Incoming string
}
MergeLabels name the two sides of a merge editor.
type MultiDiffProvider ¶
type MultiDiffProvider struct {
// Kind names the provider, unique among the providers of the window tab ("git.changes").
Kind string
// Resources makes the files of the set with the Key, sorted as they are shown. It runs off the UI thread, each time the set is
// opened and each time Changed says it changed, and must stop when ctx does. An error with the tag TagMultiDiffGone closes the
// tab; any other is shown in the tab with its message.
Resources func(ctx context.Context, key string) ([]MultiDiffResource, error)
}
MultiDiffProvider makes the files of the sets of one kind, and is how a multi-file diff editor comes back after a restart (SPEC §10.30): the saved tab remembers only the Kind and the Key, and the window asks the provider for the files when the extension has started and registered it. It is also how the editor follows its set: Changed makes the window ask again.
type MultiDiffRegistration ¶
type MultiDiffRegistration interface {
// Changed tells the window that the files of the sets with these keys may have changed (the group of changes got another file):
// the open editors of them ask the provider again, off the UI thread, and keep the sections of the files that are still there. A
// key that is not open costs nothing.
Changed(keys ...string)
// Dispose takes the provider away; it happens by itself when the activation ends. The tabs of its sets stay open with the files
// they have.
Dispose()
}
MultiDiffRegistration is a registered MultiDiffProvider.
type MultiDiffResource ¶
type MultiDiffResource struct {
// Original and Modified are the two documents of the file: a file (file:///path), an open untitled document, or a provided one
// (ContentURI). An empty one is a file that does not exist on that side (an added file has no original, a deleted file no
// modified); at least one is set. The documents are read when the section of the file comes near the viewport, off the UI thread.
Original, Modified string
// Path is the path of the file as the header shows it, with slashes and relative to the root of the set: the last element is the
// name and the rest the folder.
Path string
// File is the file that Open File shows and that gives the header its icon and its decorations: a file URI; empty for none.
File string
// Letter, Color and Tooltip are the mark of the status of the file at the end of its header: "M" in the theme color with the id
// Color ("gitDecoration.modifiedResourceForeground"), with the tooltip "Modified".
Letter, Color, Tooltip string
// Context holds the context keys the when-clauses of the file's actions are read with (MenuMultiDiffFileToolbar): for Git
// {"scmProvider": "git", "scmResourceGroup": "index"}.
Context map[string]any
// Args is the value the commands of the file's actions are run with, as the command of a menu of the Source Control view is run
// with SCMArgs: for Git the list of one object that names the resource.
Args any
}
MultiDiffResource is one file of a multi-file diff editor (SPEC §10.30 "Diffs of changes"; VS Code's MultiDiffEditorItem with the parts of the Source Control resource that its header shows).
func (MultiDiffResource) FileName ¶
func (r MultiDiffResource) FileName() string
FileName is the name of the file of a resource as its header shows it: the last element of Path.
func (MultiDiffResource) Folder ¶
func (r MultiDiffResource) Folder() string
Folder is the folder of the file of a resource as its header shows it: Path without the last element; empty for a file at the root.
type MultiDiffSpec ¶
type MultiDiffSpec struct {
// Title is the name of the tab ("Git: Changes", "a1b2c3d - Fix the loader"); the tab adds the number of files.
Title string
// Kind and Key name the set: the provider of the Kind makes its files, and the saved tab comes back through them. The same Kind
// and Key is one tab: opening it again shows the open one and asks the provider again. Both are empty for a fixed set.
Kind, Key string
// Resources is a fixed set, used when Kind is empty. A tab of a fixed set is not saved with the window.
Resources []MultiDiffResource
// Reveal, when set, is the Modified document (or the Original of a deleted file) of the file to scroll to.
Reveal string
// Preview opens the editor as a preview tab, which the next preview replaces; false keeps it.
Preview bool
// PreserveFocus keeps the keyboard where it is.
PreserveFocus bool
}
MultiDiffSpec describes a multi-file diff editor to open (Documents().OpenMultiDiff; VS Code's _workbench.openMultiDiffEditor).
func (MultiDiffSpec) Valid ¶
func (s MultiDiffSpec) Valid() bool
Valid reports whether the spec names a provider's set (Kind and Key) or gives a fixed set, and not both or neither.
type NotificationAction ¶
type NotificationAction struct {
// Label is the text of the button.
Label string
// Run is called on the UI thread when the button is pressed. A panic in it deactivates the extension.
Run func()
}
NotificationAction is a button of a notification.
type NotificationProgress ¶
type NotificationProgress interface {
// Report says what the work is doing now and how far it is: percent is 0 to 100 of the whole, or negative when the amount is not
// known (the bar then has no end). An empty message keeps the last one. It does nothing after Done.
Report(message string, percent float64)
// Done ends the work: the notification goes away. Calling it again does nothing.
Done()
}
NotificationProgress is the handle of a notification with a progress bar.
type NotificationSeverity ¶
type NotificationSeverity uint8
NotificationSeverity is how serious a notification of the workspace is.
const ( // NotificationInfo is for news the user may like to know. NotificationInfo NotificationSeverity = iota // NotificationWarning is for something that may not work as the user expects. NotificationWarning // NotificationError is for a failure. NotificationError )
The severities of ViewNotification.
type Notifications ¶
type Notifications interface {
// Info shows an information.
Info(message string, actions ...NotificationAction)
// Warn shows a warning.
Warn(message string, actions ...NotificationAction)
// Error shows an error.
Error(message string, actions ...NotificationAction)
// Progress shows a notification with a progress bar for work that takes a while (a clone, a sync that the user may cancel). It
// stays until the returned handle's Done is called; a host that cannot show notifications (or the end of the activation) gives a
// handle that does nothing, so the work goes on without a bar.
Progress(opts ProgressOptions) NotificationProgress
}
Notifications shows notifications in the window tab of the scope, with the name of the extension as their source.
type OpenSpec ¶
type OpenSpec struct {
// URI is the document: a file, an open untitled document, or a provided one (ContentURI).
URI string
// Title is the name of the tab; the name of the document when empty.
Title string
// Preview opens it as a preview tab.
Preview bool
// Selection is put in the document and revealed, when set.
Selection *Selection
// PreserveFocus keeps the keyboard where it is.
PreserveFocus bool
// MergeEditor opens the file in the merge editor (SPEC §9.11), as "Resolve in Merge Editor" does, instead of a text editor: the file
// must be a file with conflict markers, else the window says that it has none. The file is read like any other document first.
MergeEditor bool
// MergeLabels, with MergeEditor, replaces the names the merge editor gives the two sides, which it reads from the conflict markers
// ("Updated upstream", "Stashed changes"): VS Code's git.openWorktreeMergeEditor titles them "Workspace" and "Worktree". Nil keeps
// the names of the markers.
MergeLabels *MergeLabels
}
OpenSpec describes a document to open with a title of the caller's (Documents().OpenDocument; VS Code's vscode.open with a title).
type Origin ¶
type Origin uint64
Origin names a screen of a workspace: the window of the host, or the view of one client. The zero value is the window of the host, which is also where the questions go that no person started (an automatic fetch).
const HostOrigin Origin = 0
HostOrigin is the window of the host.
func OriginFromContext ¶
OriginFromContext is the origin WithOrigin put in the context, or HostOrigin when it has none.
type Origins ¶
type Origins interface {
// Current is the origin of the command whose handler is running on the UI thread, or of the callback that continues it: the
// function of Show that answers a question the command asked, a button of a notification the command showed, a function that
// WithOrigin calls. It is HostOrigin where no command is running, and on any goroutine but the UI thread's.
Current() Origin
// Run calls f on the calling goroutine with Current returning o until f returns. It is for a callback that the extension keeps
// for later (the end of a job on a goroutine, which a Post hands to the UI thread) so that what f asks goes to the screen the job
// was started from. Call it on the UI thread.
Run(o Origin, f func())
// Remember keeps an origin under a key of the extension's own choice (the typist of a terminal, "terminal:3"), for Recall; the
// key is shared by all the extensions of the scope, so that one extension can tell another where a request came from. The empty
// origin is a valid one: it clears nothing.
Remember(key string, o Origin)
// Recall returns the origin kept under the key, or HostOrigin when there is none.
Recall(key string) Origin
}
Origins tells an extension where a command came from and keeps the origins it needs for work that goes on after the command's handler has returned (a program that asks a question later).
type Output ¶
type Output interface {
// Channel makes the channel with the name, or fails with ExtensionOutputChannelInvalid for an empty name and
// ExtensionOutputChannelDuplicate when the extension has it open. Two window tabs that open the same name share the
// lines, because the Output panel is the window's; the channel goes when the last of them lets go of it.
Channel(name string) (OutputChannel, error)
}
Output gives the extension channels of the Output panel.
type OutputChannel ¶
type OutputChannel interface {
// Name is the name in the list of channels.
Name() string
// AppendLine adds a line; a text with line breaks is several lines. It may be called from any goroutine.
AppendLine(text string)
// Clear empties the channel.
Clear()
// Show selects the channel in the Output panel and shows the panel; with preserveFocus the keyboard focus stays where
// it is.
Show(preserveFocus bool)
// Dispose takes the channel away with its lines. A channel that the activation did not dispose goes when it ends.
Dispose()
}
OutputChannel is a channel of the Output panel that an extension writes to (SPEC §10.13). Its lines are those of the log of the channel: the last 10,000 are kept.
type PanelViewSpec ¶
type PanelViewSpec struct {
// ID identifies the view and its tab. It starts with the id of the extension and a dot.
ID string
// Title is the name on the tab, shown in capitals.
Title string
// Icon is the name of the Codicon of the view in lists; it may be empty.
Icon string
// Order orders the tabs, the lowest first; Problems is 0 and Output 1.
Order int
}
PanelViewSpec declares a view of the panel: a tab beside Problems and Output with one body. It moves and maximizes with the panel (the panel's position is the user's, and so is its size). Emetos adds the command ToggleViewCommand(ID) "Toggle <Title>" and an entry for it in the View menu.
type Parameter ¶
Parameter is a parameter of a signature: the text of the signature that is it (Label), and its documentation.
type PointerEvent ¶
type PointerEvent struct {
// Kind is whether the pointer moved or a button went down or up.
Kind PointerKind
// Buttons are the buttons that are down after the event, as bits of the Button constants.
Buttons uint8
// X and Y are the position of the pointer.
X, Y float64
}
PointerEvent is a mouse event of a headless view, at a position in the pixels of the view.
type PointerKind ¶
type PointerKind uint8
PointerKind is what the pointer did.
const ( // PointerMove is a pointer that moved, with or without buttons down. PointerMove PointerKind = iota // PointerDown is a button that was pressed. PointerDown // PointerUp is a button that was released. PointerUp )
The kinds of a pointer event.
type Position ¶
Position is a place in a text: a zero-based line and a zero-based column counted in bytes of the UTF-8 line (as Emetos's text buffer does, SPEC §6.2).
type PrepareRenameResult ¶
PrepareRenameResult says what a rename would change: the Range of the symbol and the Placeholder to show in the input box (the text of the range when empty).
type Problems ¶
type Problems interface {
// Set replaces the markers the owner has for the file with the URI (file:///path/to/file) with markers; none removes
// them. The owner is a name of the extension's own ("go vet"). It fails with ExtensionProblemsOwnerInvalid for an empty
// owner and ExtensionProblemsURIInvalid for a URI that is not a file. It may be called from any goroutine.
Set(owner, uri string, markers []Marker) error
// Clear removes every marker of the owner.
Clear(owner string)
// Read returns the markers that every owner (language servers, tasks and extensions, this one included) has for the file with the
// URI (file:///path/to/file), most serious first, then by position (VS Code's languages.getDiagnostics). A marker has the Source
// its owner gave it, which is empty for a language server's diagnostic that names none. It fails with ExtensionProblemsURIInvalid
// for a URI that is not a file, ExtensionProblemsUnavailable in a scope with no Problems panel and ExtensionDeactivated after the
// activation ended. It may be called from any goroutine.
Read(uri string) ([]Marker, error)
// Show opens the Problems panel and gives it the keyboard (VS Code's workbench.panel.markers.view.focus). It fails with
// ExtensionProblemsUnavailable in a scope with no Problems panel and ExtensionDeactivated after the activation ended. Call it on
// the UI thread.
Show() error
}
Problems gives the extension markers in the Problems panel. The markers belong to the extension: another extension cannot replace or clear them, and they go when the activation ends.
type ProgressOptions ¶
type ProgressOptions struct {
// Title is the text of the notification; Report adds its message after it ("Cloning: Receiving objects").
Title string
// Cancellable adds a Cancel button. Pressing it calls OnCancel, on the UI thread, and the notification goes away at once; the work
// stops when the extension acts on OnCancel.
Cancellable bool
// OnCancel is called when the Cancel button is pressed; it may be nil.
OnCancel func()
}
ProgressOptions describe a notification with a progress bar.
type ProposedChange ¶
type ProposedChange struct {
// URI is the URI of the file (file:///path/to/file); its name and language come from it. It is required.
URI string
// Original is the current text of the file, shown on the left; empty for a file that does not exist yet.
Original string
// Proposed is the text the change would give, shown on the right.
Proposed string
// Title is the title of the tab; "<file name> (proposed)" when empty.
Title string
// Language is the name or id of the language of both sides when the file name does not say it (a name that
// Languages().Resolve knows); empty takes the language from the name of the file.
Language string
}
ProposedChange is a change to a file that an extension asks the user to review (Editors.OpenProposedChange).
type ProposedResult ¶
type ProposedResult struct {
// Accepted is true when the user pressed Accept, and false for Reject and for closing the tab.
Accepted bool
// Text is the text of the right side at the time of the answer: the proposed text, or what the user made of it. It is
// empty for a rejection.
Text string
// Edited tells that the user changed the proposed text before accepting.
Edited bool
}
ProposedResult is the user's answer to a ProposedChange.
type QuickDiffKind ¶
type QuickDiffKind int
QuickDiffKind tells how a provider's changes are shown (VS Code's QuickDiffProviderKind: primary, secondary).
const ( // QuickDiffPrimary is the provider whose changes are the marks of the file, and whose original the format on save of modifications // compares with (VS Code's SourceControl.quickDiffProvider). QuickDiffPrimary QuickDiffKind = iota // QuickDiffSecondary is a provider whose changes are drawn in the secondary colors, where the primary provider's changes do not // cover them (VS Code's SourceControl.secondaryQuickDiffProvider; Git's staged changes). QuickDiffSecondary )
type QuickDiffProvider ¶
type QuickDiffProvider struct {
// Label names the provider ("Git Local Changes (Working Tree)"); the peek of step 24.12 shows it.
Label string
// Kind says whether the provider is the primary one of its source control or a secondary one.
Kind QuickDiffKind
// Original returns the URI of the document that holds the original text of the file with the URI (file:///path), or "" when the file
// has no original under this provider (an untracked file, a file of another repository). The host reads the document the way it reads
// a provided one, and compares it with the file; it asks again after RefreshQuickDiff and after the provider's content changed
// (ContentRegistration.Changed), not on every edit. It runs off the UI thread and must stop when ctx does; a failure means no
// original for the file, and is logged by the host at debug level. Only files below the root of the source control are asked.
Original func(ctx context.Context, uri string) (string, error)
}
QuickDiffProvider says what the files of a source control are compared with.
type QuickDiffRegistration ¶
type QuickDiffRegistration interface {
// Dispose takes the provider away: the marks it made go. It does nothing the second time, and happens by itself when the activation
// ends.
Dispose()
}
QuickDiffRegistration is a registered QuickDiffProvider.
type QuickPick ¶
type QuickPick interface {
// Show opens the quick pick. done is called once, on the UI thread, after the list is hidden: with the index in
// Options.Items of the chosen item, or -1 when it was closed without a choice or another quick input took its place. The
// command of the item, if it has one, runs before done. It fails with ExtensionQuickPickInvalid when no item that is not a
// separator has a label, with ExtensionQuickPickUnavailable when the scope cannot show a list (a window tab of an extension has none) and
// with ExtensionDeactivated after the activation ended; done is not called then.
Show(opts QuickPickOptions, done func(index int)) error
}
QuickPick shows a list over the editor to choose one item from, as the command palette does (SPEC §10.3).
type QuickPickItem ¶
type QuickPickItem struct {
// Label is the main text; the filter matches it. A codicon may be written $(name).
Label string
// Description is shown after the label in a dimmer color; Detail is shown on a second line below it.
Description, Detail string
// Command, when it is not empty, is the id of a command that is run (with Args) when the item is chosen; the done function
// of Show still gets the index. Use it for a command of the editor, such as workbench.action.openSettings.
Command string
Args any
// Separator makes the item a heading: only its Label is used, it is drawn at the right of the next item that is shown, with a line
// above that item, and it cannot be chosen (VS Code's QuickPickItemKind.Separator). Its index is never given to done.
Separator bool
// AlwaysShow keeps the item in the list when the text typed in the filter does not match it (VS Code's alwaysShow): the entries
// that make something new, such as "Create new branch...".
AlwaysShow bool
}
QuickPickItem is a row of a quick pick.
type QuickPickOptions ¶
type QuickPickOptions struct {
// Title is a line of text centered above the input (VS Code's title); none when empty.
Title string
// Placeholder is the hint of the input.
Placeholder string
// Items are the rows; an item with an empty Label is not shown.
Items []QuickPickItem
// MatchOnDescription lets the filter look at the descriptions too.
MatchOnDescription bool
// IgnoreFocusOut keeps the list open when the user clicks elsewhere or the window loses the focus, as VS Code's ignoreFocusOut does:
// only a choice and Escape end it. A question that a running program waits for (ssh's host key) sets it.
IgnoreFocusOut bool
// OnAccept, when set, is called on the UI thread just before done, when an item was chosen, with the text that was typed in the
// filter at that moment (VS Code's quickPick.value). The checkout picker uses it: the text typed beside "Create new branch..." is
// the name of the branch.
OnAccept func(value string)
// Origin is the screen that shows the list; the zero value is the origin of the command being handled (see InputBoxOptions.Origin).
Origin Origin
}
QuickPickOptions describe a quick pick.
type RangeFormattingProvider ¶
type RangeFormattingProvider interface {
ProvideRangeFormatting(ctx context.Context, doc TextDocument, r Range, opts FormattingOptions) ([]RangeEdit, error)
}
RangeFormattingProvider formats a range of a document.
type ReadOption ¶
type ReadOption func(*ReadOptions)
ReadOption changes a Documents().Read: FromScope.
func FromScope ¶
func FromScope(id string) ReadOption
FromScope reads the document from the window tab with the ID (ScopeInfo.ID) instead of the own one. It needs a link that lets the document events of that tab (TopicDocumentChanged) reach this one, and the tab must not be private; the Manifest must list TopicDocumentChanged among its CrossTab topics. The user is not asked: a read without a link fails with ExtensionReadNotShared.
type ReadOptions ¶
type ReadOptions struct {
// Scope is the ID of the window tab to read from; empty is the own scope.
Scope string
}
ReadOptions are what the ReadOption values set.
type ReferenceProvider ¶
type ReferenceProvider interface {
ProvideReferences(ctx context.Context, doc TextDocument, pos Position, includeDeclaration bool) ([]Location, error)
}
ReferenceProvider answers find all references.
type RenameProvider ¶
type RenameProvider interface {
PrepareRename(ctx context.Context, doc TextDocument, pos Position) (*PrepareRenameResult, error)
ProvideRename(ctx context.Context, doc TextDocument, pos Position, newName string) (*WorkspaceEdit, error)
}
RenameProvider answers rename. PrepareRename may refuse with an error whose message is shown, and may answer nil to use the word at the position.
type ReplaceFailure ¶
type ReplaceFailure struct {
// Path is the path of the file and Message why it failed.
Path, Message string
}
ReplaceFailure is a file that ReplaceInFiles could not change.
type ReplaceReport ¶
type ReplaceReport struct {
// Replaced is the number of replacements made and Skipped the number that were stale (the file had other text there) or
// invalid.
Replaced, Skipped int
// Files are the paths of the files that were written.
Files []string
// Failed are the files that could not be read or written (a binary file, a file that changed while it was replaced, a
// read only file); they are left as they were.
Failed []ReplaceFailure
}
ReplaceReport says what ReplaceInFiles did.
type RequestOption ¶
type RequestOption func(*RequestOptions)
RequestOption changes a Request: ToOtherScopes, ToScopes.
func ToOtherScopes ¶
func ToOtherScopes() RequestOption
ToOtherScopes sends a request to the handler of its topic in another window tab, the first (in the order the tabs were opened) that has one and is linked to this one; the own scope is not looked at.
func ToScopes ¶
func ToScopes(ids ...string) RequestOption
ToScopes sends a request to the handler of its topic in one of the window tabs with these IDs.
type RequestOptions ¶
type RequestOptions struct {
// To are the other scopes whose handler answers; the zero value is the own scope.
To ScopeFilter
}
RequestOptions are what the RequestOption values set.
type ResourceChange ¶
type ResourceChange struct {
// Kind is "edit" (the edits of URI), "create", "rename" (URI to NewURI) or "delete".
Kind string
URI string
NewURI string
// Edits are the edits of an "edit" change; their ranges are in the text as it is now.
Edits []RangeEdit
// Overwrite and IgnoreIfExists are the options of create and rename; Recursive and IgnoreIfNotExists those of delete.
Overwrite, IgnoreIfExists, Recursive, IgnoreIfNotExists bool
}
ResourceChange is one change of a WorkspaceEdit: the edits of a document, or the creation, renaming or deletion of a file.
type ResourceDecorations ¶
type ResourceDecorations struct {
// Icon is the name of a Codicon or the path of an image file.
Icon string
// Tooltip is the hover of the row; it is also what the sort by status compares ("Modified", "Deleted").
Tooltip string
// StrikeThrough draws the name struck through (a deleted file).
StrikeThrough bool
// Faded draws the row dimmed.
Faded bool
// Color is the id of a theme color the icon of the row is drawn in ("gitDecoration.modifiedResourceForeground"). The letter of the row and
// its color come from the file decorations (api.Decorations()), as in VS Code.
Color string
}
ResourceDecorations are the looks of a resource row (VS Code's SourceControlResourceDecorations).
type ResourceGroup ¶
type ResourceGroup interface {
// ID is the id the group was created with.
ID() string
// SetResources replaces the resources of the group in one call. The host draws them lazily: 100,000 are fine.
SetResources(resources []ResourceState)
// SetLabel changes the title of the group.
SetLabel(label string)
// SetHideWhenEmpty says whether the group is hidden while it has no resources.
SetHideWhenEmpty(hide bool)
// Dispose removes the group; it happens by itself with the source control.
Dispose()
}
ResourceGroup is a group of resources of a source control (VS Code's SourceControlResourceGroup).
type ResourceGroupSpec ¶
type ResourceGroupSpec struct {
// ID is the id of the group ("index", "workingTree", "merge"); the menus read it as the context key scmResourceGroup.
ID string
// Label is the title of the group ("Staged Changes").
Label string
// HideWhenEmpty hides the group while it has no resources.
HideWhenEmpty bool
// ContextValue is what the context key scmResourceGroupState holds for the menus of the group.
ContextValue string
}
ResourceGroupSpec describes a group of resources (VS Code's createResourceGroup(id, label)).
type ResourceState ¶
type ResourceState struct {
// URI is the file as file:///path.
URI string
// Command is run on a click on the row (the diff of the change); nil for none.
Command *Command
// ContextValue is what the context key scmResourceState holds for the menus of the resource.
ContextValue string
// Decorations say how the row looks.
Decorations ResourceDecorations
// MultiFileDiffEditorOriginalURI and MultiFileDiffEditorModifiedURI are the two sides of the file in the multi-file diff
// editor (Open All Changes); empty when the file has no such side.
MultiFileDiffEditorOriginalURI, MultiFileDiffEditorModifiedURI string
}
ResourceState is a changed file of a group (VS Code's SourceControlResourceState).
type SCMArg ¶
type SCMArg struct {
// SourceControl is the Handle of the source control the object belongs to.
SourceControl string
// Group is the ID of the group; empty for a source control.
Group string
// URI is the URI of the resource; empty for a source control and a group.
URI string
// ContextValue is the ContextValue of the group or the resource; empty for a source control.
ContextValue string
}
SCMArg is one of the arguments that a command gets from a menu of the Source Control view: a source control, a group or a resource. VS Code passes them as separate arguments (the source control for scm/title, the group, the resource states of the selection); Emetos gives the command one value, a list of objects {"sourceControl": "scm1", "group": "index", "uri": "file:///a.go", "contextValue": "..."} in the order VS Code passes them, which SCMArgs reads.
func SCMArgs ¶
SCMArgs reads the arguments a menu of the Source Control view gave a command: the objects of the list, in order; nothing for any other value (the command was run from the palette or by a key).
func (SCMArg) IsResource ¶
IsResource tells whether the argument is a resource.
func (SCMArg) IsSourceControl ¶
IsSourceControl tells whether the argument is a source control.
type SCMInput ¶
type SCMInput interface {
// Value is the text now in the box.
Value() string
// SetValue replaces the text. OnChange is called, as it is for the user's typing.
SetValue(value string)
// OnChange calls fn, on the UI thread, with the new text each time it changes, and returns the function that stops it. A
// panic in fn deactivates the extension.
OnChange(fn func(value string)) (cancel func())
// SetPlaceholder sets the text shown while the box is empty ("Message (Ctrl+Enter to commit on \"main\")").
SetPlaceholder(placeholder string)
// SetValidation sets the function that checks the text on each change; it returns nil for no message. fn is called on the UI
// thread and must be fast; a panic in it deactivates the extension and shows no message. nil removes the check.
SetValidation(fn func(value string) *Validation)
// SetVisible shows or hides the box (it is shown by default).
SetVisible(visible bool)
// SetEnabled enables or disables the box (it is enabled by default).
SetEnabled(enabled bool)
// Focus gives the box the keyboard focus, in the view.
Focus()
}
SCMInput is the commit message box of a source control (VS Code's SourceControlInputBox).
type ScopeFilter ¶
type ScopeFilter struct {
// Others reaches every other window tab.
Others bool
// IDs reaches the window tabs with these IDs.
IDs []string
}
ScopeFilter says which other window tabs an operation reaches: all of them, or the ones with the listed IDs (ScopeInfo.ID). The zero value reaches none.
func (ScopeFilter) Any ¶
func (f ScopeFilter) Any() bool
Any tells whether the filter reaches any other scope at all.
func (ScopeFilter) Matches ¶
func (f ScopeFilter) Matches(id string) bool
Matches tells whether the filter reaches the scope with the id.
type ScopeInfo ¶
type ScopeInfo struct {
// Kind is what the scope is.
Kind ScopeKind
// Name is the name of the window tab: the base name of the folder, or "No Folder"; the title of the kind for the tab
// of an extension.
Name string
// Folder is the absolute path of the folder of a workspace scope, or empty.
Folder string
// WindowTab is the id of the kind of window tab of a ScopeWindowTab scope; empty for a workspace.
WindowTab string
// ID names the scope in the links between window tabs (SPEC §10.15 "Event sharing"): the cleaned absolute folder of
// a workspace, "<extension id>:<tab id>" for the tab of an extension. It is empty for a scope that cannot be named
// in a link, such as a workspace tab with no folder: it sends nothing to other tabs and receives nothing from them.
ID string
// Instance numbers the scope among the scopes the host has opened: every extension of one scope sees the same number and no
// two open scopes have the same. It is how an extension finds the part of another extension that runs in its own window tab
// (the menu of the Databases view opens query editors of the SQL extension in the tab of the menu). It is 0 where the host
// does not number its scopes (the fake API of the tests).
Instance int
}
ScopeInfo describes the scope an API is bound to.
type ScopeKind ¶
type ScopeKind string
ScopeKind tells what a scope is.
const ( // ScopeWorkspace is a window tab that holds a workspace: a folder, or none. ScopeWorkspace ScopeKind = "workspace" // ScopeWindowTab is a window tab of an extension (a kind of Contributes.WindowTabKinds). Only the extension that owns // the kind is activated in it; it has no folder, no documents and no editor area. ScopeWindowTab ScopeKind = "windowTab" )
The kinds of scope.
type ScrollEvent ¶
type ScrollEvent struct {
// X and Y are the position of the pointer.
X, Y float64
// DX and DY are the distance scrolled, in pixels, positive towards the right and the bottom.
DX, DY float64
}
ScrollEvent is a scroll of the wheel or the trackpad over a headless view.
type Selection ¶
Selection is a selection: the anchor is where it began and the active end is where the cursor is. An empty one is a cursor.
type ServerLaunch ¶
type ServerLaunch struct {
// Program is the path of the program to run; it replaces Program and PathSetting of the spec.
Program string
// Args are its arguments, replacing the spec's Args, and Env extra environment variables ("NAME=value") added to those of
// the spec.
Args, Env []string
// Root is the folder the server works on: the working directory of the program and the root it is initialized with. The
// folder of the tab when empty. A project root above the folder (the folder opened is a subfolder of the crate) is allowed.
Root string
// InitializationOptions are sent in initialize as initializationOptions, replacing the spec's when not nil; they must
// encode to JSON.
InitializationOptions any
// Configuration answers the requests workspace/configuration of the server before the settings do: it is asked for each
// section requested and answers with the value and true, or false to leave the section to the settings (see
// LanguageServerSpec.ConfigurationSection). It may be called from any goroutine. A change of what it answers is told to the
// server by restarting it.
Configuration func(section string) (json.RawMessage, bool)
// Settings, when not nil, are sent to the server with workspace/didChangeConfiguration right after the handshake, before the
// documents open (a server that takes its settings that way, such as typescript-language-server, finds them there). They must encode
// to JSON. A change of what they hold is told to the server by restarting it.
Settings any
// ClientExperimental is what the client tells the server about itself in the "experimental" member of its capabilities (rust-analyzer
// asks for experimental.serverStatusNotification to send experimental/serverStatus, and lists the commands the client runs in
// experimental.commands). The rest of the capabilities Emetos advertises is not changed; nil adds nothing. It must encode to JSON.
ClientExperimental map[string]any
}
ServerLaunch is how to start a server now: the answer of a ServerLauncher.
type ServerLauncher ¶
type ServerLauncher func(ctx context.Context, req LaunchRequest) (ServerLaunch, error)
ServerLauncher decides, each time the host starts a server (the first document, a crash, a restart, a change of the path setting), what to run. It is how an extension finds its server in places the host does not know (the folder's node_modules, the home folder of the installer), checks its version, chooses the root of the project and builds the options the server is initialized with from the current settings. It runs on a goroutine of the host, not on the UI thread, and may run programs and read files; ctx ends when the server is stopped or restarted. It reads settings through req.Setting. An error leaves the server ServerMissing (the host writes it to the Output channel of the server, and shows no notification for a server with OwnUI): the program was not found, or cannot be used. It is not called again until the user restarts the server or the extension asks LanguageServers().Restart (a change of the settings the extension watches).
type ServerState ¶
type ServerState string
ServerState is the state of a language server in the scope of an extension.
const ( // ServerIdle: declared, and waiting for the first document of its languages. ServerIdle ServerState = "idle" // ServerStarting: the program was started and the handshake is not done (a crashed server that is started again too). ServerStarting ServerState = "starting" // ServerRunning: initialized; its documents are open on it. ServerRunning ServerState = "running" // ServerFailed: it crashed five times in three minutes and is not started again until the user restarts it. ServerFailed ServerState = "failed" // ServerMissing: the program was not found; nothing is started again until the path setting changes or the server is // restarted. ServerMissing ServerState = "missing" // ServerStopped: the activation ended. ServerStopped ServerState = "stopped" )
The states of a language server (LanguageServers().Status).
type ServerStatus ¶
type ServerStatus struct {
// State is the state of the server.
State ServerState
// Starts counts the times the program was started in this scope, Crashes the crashes among the last five (a restart by
// the user forgets them).
Starts, Crashes int
// Progress is the work the server reports with $/progress, as the status bar of a language client shows it ("Loading
// packages 40%"): the last work that began and has not ended; empty when there is none.
Progress string
}
ServerStatus is what an extension may know of one of its language servers in its scope.
type SettingSpec ¶
type SettingSpec struct {
// Key is the dotted name. For Settings().Register it starts with the id of the extension and a dot: sqltools.connections.
// A setting declared in Contributes.Settings may have any key the editor and the other extensions do not have (go.gopls).
Key string
// Type is the JSON type of the value: string, number, integer, boolean, array or object.
Type string
// Default is the value when nothing sets it; the zero value of Type when nil.
Default any
// Description says what the setting does; Markdown may be used.
Description string
// Enum lists the only values allowed, when it is not empty.
Enum []any
// Minimum and Maximum bound a number, when not nil.
Minimum, Maximum *float64
// Category is the group of the settings editor; the name of the extension when empty.
Category string
// AlsoTypes are the other JSON types the value may have besides Type, which stays the main one: "null", "string" and the others
// (VS Code's type: ["string", "null", "array"]). Each is a JSON type or "null".
AlsoTypes []string
// EnumDescriptions describe the values of Enum, in the same order.
EnumDescriptions []string
// Scope says where the setting may be set (VS Code's ConfigurationScope): "window" (the default, also for ""), "resource" and
// "language-overridable" (the user's and the workspace's settings), "machine" and "application" (the user's settings only).
Scope string
}
SettingSpec declares a setting of an extension.
type Settings ¶
type Settings interface {
// Register adds a setting. It fails when the key is not under the id of the extension, or is taken by a setting of
// the editor.
Register(spec SettingSpec) error
// Get returns the value of a registered setting in the scope: a string, a float64, a bool, a []any or a
// map[string]any, as the JSON of the settings file reads. Use SettingValue to get a Go type.
Get(key string) (any, error)
// OnChange calls fn, on the UI thread, when a setting changes in the scope, and returns the function that stops it.
// The calls stop when the extension is deactivated.
OnChange(fn func()) (cancel func())
// Update writes the value of a setting of the extension to the user's settings file, keeping the comments and the layout
// of the file, as the Settings editor does; the settings are read again and OnChange is called. The setting is one the
// manifest declares in Contributes.Settings or lists in Contributes.WritesSettings, or the extension registered: it fails with
// ExtensionSettingNotOwned for any other (an extension does not write the settings of the editor or of other extensions
// unless its manifest names them), with ExtensionDeactivated after the activation ended, and returns the settings store's error when the value does not fit the setting or the file cannot
// be written. Call it on the UI thread.
Update(key string, value any) error
}
Settings registers and reads settings. A setting is read for the workspace of the scope, like every setting.
type SharingRevoked ¶
type SharingRevoked struct {
// From is the ID of the scope the events came from, FromName its name.
From string `json:"from"`
FromName string `json:"fromName,omitempty"`
// Topics are the patterns the link carried; empty when it carried every topic.
Topics []string `json:"topics,omitempty"`
// Reason is RevokedLinkRemoved or RevokedPrivate.
Reason string `json:"reason"`
}
SharingRevoked is the payload of TopicSharingRevoked: the events of the scope From no longer reach this tab.
type SignatureHelp ¶
SignatureHelp is the answer of a signature help provider.
type SignatureHelpProvider ¶
type SignatureHelpProvider interface {
ProvideSignatureHelp(ctx context.Context, doc TextDocument, pos Position) (*SignatureHelp, error)
}
SignatureHelpProvider answers signature help requests; a nil answer is none.
type Size ¶
type Size struct {
// Width and Height are the pixels across and down.
Width, Height int
}
Size is a size in pixels.
type SourceControl ¶
type SourceControl interface {
// Handle is the id the host gave the source control, unique in the scope ("scm3"): it is the member "sourceControl" of the
// arguments that the menus of the view give a command (SCMArgs), and tells two source controls of one provider apart.
Handle() string
// SetCount sets the number on the badge of the repository and of the Source Control icon of the activity bar
// (scm.countBadge). A negative count (the default) is VS Code's undefined: the number of resources of all the groups.
SetCount(count int)
// SetStatusBarCommands sets the items that show the state of the repository (the branch and the sync item): in the header of
// the repository and, for the active repository, in the status bar. The first is at the left end.
SetStatusBarCommands(commands []StatusCommand)
// SetActiveRepositoryName sets the name that the title bar and the context key scmActiveRepositoryName show for the source
// control while it is the active one (VS Code's activeRepositoryName: the name of a worktree); empty goes back to the name of
// the root folder.
SetActiveRepositoryName(name string)
// SetBusy shows the progress bar under the header of the repository while a command runs.
SetBusy(busy bool)
// Input is the commit message box of the source control.
Input() SCMInput
// SetAcceptInputCommand sets the command that Ctrl+Enter in the input runs (scm.acceptInput); an empty ID clears it.
SetAcceptInputCommand(command Command)
// SetActionButton sets the button under the input, or removes it with nil.
SetActionButton(button *ActionButton)
// CreateGroup adds a group of resources below the previous ones. It fails with ExtensionSCMGroupInvalid for an empty ID,
// ExtensionSCMGroupDuplicate for an ID the source control has already, ExtensionSCMDisposed for a source control that was
// disposed and ExtensionDeactivated after the activation ended.
CreateGroup(spec ResourceGroupSpec) (ResourceGroup, error)
// Dispose removes the source control and its groups from the view. It happens by itself when the activation ends.
Dispose()
// AddQuickDiffProvider says what the files below the root of the source control are compared with, for the marks of the changes
// in the editors and for the format on save of modifications (SPEC §10.30 "Quick diff"). A source control has one primary and one
// secondary provider at most. It fails with ExtensionQuickDiffInvalid for a provider with no label or no Original, a kind that
// is not known or a source control with no root, ExtensionQuickDiffDuplicate for a kind the source control has a provider of,
// ExtensionQuickDiffUnavailable in a scope that has no editors (a host without a workbench), ExtensionSCMDisposed for a
// source control that was disposed and ExtensionDeactivated after the activation ended. The provider goes with the source control and
// with the activation.
AddQuickDiffProvider(p QuickDiffProvider) (QuickDiffRegistration, error)
// RefreshQuickDiff tells the host that the originals of the files of this source control may have changed (a commit, a stage, a
// checkout): the open files are compared again, off the UI thread, and the providers are asked for their originals again. It
// does nothing when the source control has no provider.
RefreshQuickDiff()
// SetHistoryProvider gives the source control a history for the Graph view (SPEC §10.30 "The Source Control Graph"). A source
// control has one. It fails with ExtensionHistoryInvalid for a provider without Items, Refs or CommonAncestor,
// ExtensionHistoryDuplicate for a source control that has a provider, ExtensionHistoryUnavailable in a scope that has no Graph (a
// host without a workbench), ExtensionSCMDisposed for a source control that was disposed and ExtensionDeactivated after the
// activation ended. The provider goes with the source control and with the activation.
SetHistoryProvider(p HistoryProvider) (HistoryRegistration, error)
}
SourceControl is a source control the extension created.
type SourceControlSpec ¶
type SourceControlSpec struct {
// ID is the id of the provider: "git". The menus read it as the context key scmProvider.
ID string
// Label is the human readable name of the source control ("Git"); it is the name of the repository when RootURI is empty.
Label string
// RootURI is the folder of the repository as file:///path, or empty for a source control that has none. The repository of an
// open file is the one with the deepest root that holds it.
RootURI string
// ContextValue is what the context key scmProviderContext holds for the menus of this source control (VS Code's
// contextValue): "repository", "submodule".
ContextValue string
}
SourceControlSpec describes a source control (VS Code's createSourceControl(id, label, rootUri)).
type SourceControls ¶
type SourceControls interface {
// Create adds a source control to the Source Control view of the scope. spec.ID names the kind of provider ("git") and is
// what the context key scmProvider holds for the menus of the source control; it may be used for several source controls with
// different roots, and a second Create with the same ID and the same RootURI by the extension fails with
// ExtensionSCMDuplicate. It fails with ExtensionSCMInvalid for an empty ID or label, ExtensionSCMUnavailable in a scope that
// has no Source Control model and ExtensionDeactivated after the activation ended. The source control is disposed with the
// activation.
Create(spec SourceControlSpec) (SourceControl, error)
}
SourceControls creates the source controls of an extension: Git has one for each repository it opened.
type State ¶
type State interface {
// Get returns the value kept under the key for the folder of the scope as JSON, and whether there is one. A scope without a
// folder has values of its own, shared by the tabs without one.
Get(key string) (json.RawMessage, bool)
// Set keeps the value under the key; a nil value takes the key away. It fails with ExtensionStateInvalid for an empty key, a value
// that does not encode to JSON or is larger than 64 KiB, with ExtensionStateUnavailable when the scope keeps no state (a scope
// that is not a workspace tab), and with ExtensionDeactivated after the activation ended.
Set(key string, value any) error
}
State keeps small values of the extension in Emetos's state (the state folder, not the user's settings), for the folder of the scope: the Python pack keeps the interpreter the user chose for a folder there (SPEC §10.34 "As built (step 24b.4)"). A value is whatever encodes to JSON, up to 64 KiB; it survives restarts of Emetos and belongs to the extension, the folder and the profile. It is the extension's own memory, not something the user edits: what the user decides to write down is a setting.
The methods may be called from any goroutine (a language server's launcher reads the value off the UI thread).
type StatementCoverage ¶
type StatementCoverage struct {
Executed int
Location Range
Branches []BranchCoverage
}
StatementCoverage is a statement of a file and how many times it ran (VS Code's StatementCoverage).
type StatusAlignment ¶
type StatusAlignment int
StatusAlignment is the side of the status bar an item is on.
const ( // StatusLeft puts the item on the left side. StatusLeft StatusAlignment = iota // StatusRight puts the item on the right side. StatusRight )
The sides of the status bar.
type StatusBar ¶
type StatusBar interface {
// Add puts an item in the bar. It fails when the extension has an item with the same ID.
Add(item StatusItem) (StatusHandle, error)
}
StatusBar adds items to the status bar of the scope.
type StatusCommand ¶
type StatusCommand struct {
// Text is the label; "$(git-branch) main" has the Codicon git-branch before the text.
Text string
// Tooltip is the text of the hover.
Tooltip string
// Command is the id of the command a click runs; empty for an item that only shows.
Command string
// Args are the JSON-compatible arguments of Command.
Args any
}
StatusCommand is an item that shows the state of a repository: the branch item and the sync item of Git.
type StatusHandle ¶
type StatusHandle interface {
// Update replaces what the item shows and does; its ID is kept.
Update(item StatusItem)
// SetVisible shows or hides the item.
SetVisible(visible bool)
// Dispose removes the item.
Dispose()
}
StatusHandle changes or removes an item that was added to the status bar.
type StatusItem ¶
type StatusItem struct {
// ID identifies the item among the items of the extension.
ID string
// Name is the name for the user, in the list of the items one can hide; the name of the extension when empty.
Name string
// Text is the text of the item; a codicon is written $(name). An item with no text is not shown.
Text string
// Tooltip is the text of the hover.
Tooltip string
// Alignment is the side of the bar.
Alignment StatusAlignment
// Kind is the look of the item; StatusStandard when not set.
Kind StatusKind
// Color, when it is "#rrggbb" (or "#rgb"), is the background of the item, with a text color that reads on it (white or black).
// It takes the place of Kind's background. It is how the SQL extension tints the item of a connection with the connection's
// color; any other text is ignored.
Color string
// Priority orders the items of a side: the higher it is, the closer to the left end of the bar.
Priority float64
// Command is the id of the command a click runs, with Args; used when OnClick is nil.
Command string
Args any
// OnClick is called on the UI thread when the item is clicked. A panic in it deactivates the extension.
OnClick func()
}
StatusItem is an item of the status bar.
type StatusKind ¶
type StatusKind int
StatusKind is the look of a status bar item.
const ( // StatusStandard is an item in the colors of the bar. StatusStandard StatusKind = iota // StatusRemote is an item on statusBarItem.remoteBackground, the color VS Code gives its remote indicator: an item that says // the workspace is shared with, or driven from, another computer (the Sharing item, SPEC §10.29). StatusRemote )
The looks of an item.
type SubmenuSpec ¶
type SubmenuSpec struct {
// the id of another extension, nor under emetos. unless it is under the id of the extension itself.
ID string
Label string
}
SubmenuSpec declares a submenu (VS Code's contributes.submenus): a menu that menu items can be put in with their Menu, and that another menu opens with a MenuItem whose Submenu is its ID. Git has Commit, Changes, Pull/Push, Branch, Remote, Stash and Tags.
type SubscribeOption ¶
type SubscribeOption func(*SubscribeOptions)
SubscribeOption changes a Subscribe: FromOtherScopes, FromScopes.
func FromOtherScopes ¶
func FromOtherScopes() SubscribeOption
FromOtherScopes makes a subscription hear the events of every other window tab that is linked to this one (SPEC §10.15 "Event sharing"), besides those of its own.
func FromScopes ¶
func FromScopes(ids ...string) SubscribeOption
FromScopes makes a subscription hear the events of the window tabs with these IDs (ScopeInfo.ID, Event.Scope.ID) that are linked to this one, besides those of its own.
type SubscribeOptions ¶
type SubscribeOptions struct {
// From are the other scopes whose events the subscription hears too.
From ScopeFilter
}
SubscribeOptions are what the SubscribeOption values set.
type TabClose ¶
type TabClose int
TabClose says what CloseTabsAs does with the unsaved changes of the tabs it closes.
const ( // TabCloseAsk closes the tabs the way the close button does: a tab with unsaved changes asks first (CloseTabs). TabCloseAsk TabClose = iota // TabCloseSave saves the documents that have unsaved changes and closes the tabs; a document that cannot be saved (the save fails or // is cancelled) keeps its tab, and the window says why, as it does for any save. TabCloseSave // TabCloseDiscard closes the tabs without asking and without saving: the unsaved changes are dropped, as a revert drops them. TabCloseDiscard )
The ways to close tabs.
type TasksRunReply ¶
type TasksRunReply struct {
// ExitCode is the exit code of the command; -1 when it did not end by itself (a signal).
ExitCode int `json:"exitCode"`
// Cancelled says that the task was stopped (by the user, or because the request was cancelled) and did not end by itself.
Cancelled bool `json:"cancelled,omitempty"`
// Errors is how many problems of the error severity the run put in the Problems panel.
Errors int `json:"errors,omitempty"`
}
TasksRunReply is the answer to TopicTasksRun: how the task ended.
type TasksRunRequest ¶
type TasksRunRequest struct {
// Label is the label of the task.
Label string `json:"label,omitempty"`
// Identifier names the task by an object, as a launch configuration's preLaunchTask may (VS Code's task identifier): its field
// label (else task) is the label. It is used when Label is empty.
Identifier map[string]any `json:"identifier,omitempty"`
}
TasksRunRequest is the payload of TopicTasksRun. A task is named by its label: the command line of an entry of the setting emetos.tasks.commands, or the label of an entry that has one.
type TerminalContribution ¶
type TerminalContribution struct {
// Extension is the id of the extension that contributes, Name its name as the user reads it ("Git").
Extension, Name string
// Description is what the source said its variables enable; empty for none.
Description string
// Variables are the variables, valid ones only (ValidTerminalVariable), by name.
Variables map[string]string
}
TerminalContribution is what one source contributes to a terminal that starts now.
type TerminalEnvironment ¶
type TerminalEnvironment interface {
// Contribute registers a source of variables. dispose takes it away (it is called by itself when the activation ends, which is how
// the variables of an extension that is turned off stop reaching new terminals). It fails with ExtensionTerminalEnvironmentInvalid
// for a nil source and ExtensionDeactivated after the activation ended.
Contribute(source TerminalVariables) (dispose func(), err error)
// Contributions asks every source, in the order they were registered, and returns what they give now, leaving out the sources that
// give no variable. A variable that two sources give is the later one's when a terminal applies them in this order. It is for the
// Terminal extension, and works for any extension.
Contributions() []TerminalContribution
}
TerminalEnvironment adds variables to the environment of terminals.
type TerminalVariables ¶
TerminalVariables is a source of variables for the terminals: it returns the variables to set (nil for none) and the description of what they enable, which the terminal's tab shows ("Enables the following features: git auth provider"). It is called on the UI thread, each time a terminal starts, and replaces a variable of the same name that the environment has. A panic in it fails the extension.
type TestController ¶
type TestController interface {
// ID is the id the controller was made with and Label its name; SetLabel renames it.
ID() string
Label() string
SetLabel(label string)
// Items are the top items of the controller's tree.
Items() *TestItemCollection
// CreateTestItem makes an item for the tree; it is in no tree until it is added.
CreateTestItem(id, label, uri string) *TestItem
// SetResolveHandler sets the function that loads the children of an item when it is expanded (the item has CanResolveChildren), and
// of the whole tree with a nil item when the explorer is shown first.
SetResolveHandler(fn func(ctx context.Context, item *TestItem) error)
// SetRefreshHandler sets the function the Refresh Tests command calls.
SetRefreshHandler(fn func(ctx context.Context) error)
// CreateRunProfile makes a run profile. It fails with ExtensionTestingInvalid for an empty label, an unknown kind or no handler.
CreateRunProfile(label string, kind TestRunKind, handler TestRunHandler, opts TestRunProfileOptions) (TestRunProfile, error)
// CreateTestRun makes a run that reports to the results. A request the host gave a handler joins that request's result; any other
// request starts a result of its own, which is kept in the saved results when persist is true. It fails with
// ExtensionTestingInvalid for no request and ExtensionDeactivated after the activation ended.
CreateTestRun(request *TestRunRequest, name string, persist bool) (TestRun, error)
// InvalidateTestResults marks the results of the items (all, with none given) as outdated; the explorer shows them faded.
InvalidateTestResults(items ...*TestItem)
// Dispose removes the controller, its items and its profiles.
Dispose()
}
TestController is the provider of a group of tests (VS Code's TestController).
type TestItem ¶
type TestItem struct {
// contains filtered or unexported fields
}
TestItem is a test, or a group of tests (a folder, a file, a suite), in a tree (VS Code's TestItem). Its children are in Children(). Making one does not put it anywhere: add it to the Items of a controller or to the children of another item. All methods are safe for concurrent use; an item belongs to one tree for its life, and is added to a tree once at a time.
func NewTestItem ¶
NewTestItem makes an item that is in no tree. The id is unique among the siblings; it must not hold a NUL byte.
func (*TestItem) Children ¶
func (it *TestItem) Children() *TestItemCollection
Children are the children of the item.
func (*TestItem) Data ¶
func (it *TestItem) Data() TestItemData
Data is a copy of the item's properties.
func (*TestItem) Parent ¶
Parent is the item that has this one as a child, or nil for the item of a controller's root or one that is in no tree.
func (*TestItem) Update ¶
func (it *TestItem) Update(fn func(d *TestItemData))
Update changes the item's properties with fn, which receives a copy, and reports the change to the tree the item is in.
type TestItemCollection ¶
type TestItemCollection struct {
// contains filtered or unexported fields
}
TestItemCollection is the children of an item, or the items of a controller (VS Code's TestItemCollection). Its methods are safe for concurrent use.
func NewTestTree ¶
func NewTestTree(observer func(TestTreeChange)) *TestItemCollection
NewTestTree makes the root collection of a tree whose changes observer receives: the items added to it, and to the children of its items, are reported while the tree is locked, in the order of the changes, so the observer must not call the methods of the tree. A host or a fake makes one for each controller.
func (*TestItemCollection) Add ¶
func (c *TestItemCollection) Add(item *TestItem) error
Add puts the item in the collection; an item with the same id that was there is replaced (with its descendants). It fails with ExtensionTestItemInvalid for no item, an empty id or an id with a NUL byte, and with ExtensionTestItemOwned for an item that is in another collection already, or is the owner of this one or an ancestor of it.
func (*TestItemCollection) All ¶
func (c *TestItemCollection) All() []*TestItem
All lists the items, in the order they were added.
func (*TestItemCollection) Delete ¶
func (c *TestItemCollection) Delete(id string) bool
Delete takes the item with the id out, with its descendants, and reports whether there was one. The item is in no tree afterwards and may be added again.
func (*TestItemCollection) Get ¶
func (c *TestItemCollection) Get(id string) *TestItem
Get returns the item with the id, or nil.
func (*TestItemCollection) Replace ¶
func (c *TestItemCollection) Replace(items []*TestItem) error
Replace makes the collection hold exactly the items: the ones with an id that is not among them are deleted, the new ones are added at the end, and an item with the id of one that is there is put in its place when it is another item. It validates all the items before it changes anything and fails like Add.
func (*TestItemCollection) Size ¶
func (c *TestItemCollection) Size() int
Size is the number of items.
type TestItemData ¶
type TestItemData struct {
// URI is the file the item is in (file:///path); empty when it has none.
URI string
// Label is the text of the item, Description more text after it, and SortText what the items are sorted by when the explorer sorts
// by name (the label when empty).
Label, Description, SortText string
// Range is the place of the item in its file; nil when unknown.
Range *Range
// Tags are the tags of the item; a run profile with a tag runs only the items that carry it.
Tags []string
// Error is shown as the item's error row (VS Code's TestItem.error) when the extension could not read the item.
Error string
// Busy says that the extension is working on the item (resolving it).
Busy bool
// CanResolveChildren says that the item's children are loaded when it is expanded (the controller's ResolveHandler).
CanResolveChildren bool
}
TestItemData is what describes a test item (VS Code's TestItem properties).
type TestMessage ¶
type TestMessage struct {
// Message is the text. With Markdown it is Markdown, otherwise plain text.
Message string
Markdown bool
// ExpectedOutput and ActualOutput are shown as a diff when both are not empty.
ExpectedOutput, ActualOutput string
// Location is where the message belongs, usually the line of the failed assertion; nil shows it at the test.
Location *Location
// StackTrace are the frames of the failure, the innermost first.
StackTrace []TestStackFrame
// ContextValue is a value for the menus of the message.
ContextValue string
}
TestMessage is something to tell about a test that failed or errored (VS Code's TestMessage).
type TestRun ¶
type TestRun interface {
// Name is the name the run was made with.
Name() string
// Enqueued, Started and Skipped set the state of the test, and Passed, Failed and Errored its result; the duration is
// TestNoDuration when it is not known. A test that has a result keeps it or takes one that is worse (VS Code's rule).
Enqueued(item *TestItem)
Started(item *TestItem)
Skipped(item *TestItem)
Passed(item *TestItem, duration time.Duration)
Failed(item *TestItem, messages []TestMessage, duration time.Duration)
Errored(item *TestItem, messages []TestMessage, duration time.Duration)
// AppendOutput adds text to the run's output (ANSI sequences are kept). The place and the item are optional: with either, the output
// can be jumped to from the test or the place.
AppendOutput(text string, location *Location, item *TestItem)
// AddCoverage reports the coverage of a file; reporting a file again replaces what was reported.
AddCoverage(file FileCoverage)
// End ends the run. A test still enqueued or started is marked skipped.
End()
}
TestRun reports a run (VS Code's TestRun). It is made by TestController.CreateTestRun. After End its methods do nothing.
type TestRunHandler ¶
type TestRunHandler func(ctx context.Context, request *TestRunRequest) error
TestRunHandler runs the tests of a request with the profile it is the handler of (VS Code's runHandler). It may return when the tests are run, or earlier: the run goes on until every TestRun it made ended. ctx ends when the user cancels the run.
type TestRunKind ¶
type TestRunKind int
TestRunKind says what a run profile does with the tests (VS Code's TestRunProfileKind).
const ( // TestKindRun runs the tests. TestKindRun TestRunKind = iota + 1 // TestKindDebug runs the tests under a debugger. TestKindDebug // TestKindCoverage runs the tests and measures the coverage. TestKindCoverage )
type TestRunProfile ¶
type TestRunProfile interface {
// Label is the name of the profile and Kind says what it does.
Label() string
Kind() TestRunKind
// IsDefault reports whether the group runs the profile without being asked; SetIsDefault changes it. SetLabel renames the profile.
IsDefault() bool
SetIsDefault(bool)
SetLabel(label string)
// Tag and SupportsContinuousRun are those the profile was made with.
Tag() string
SupportsContinuousRun() bool
// Dispose removes the profile.
Dispose()
}
TestRunProfile is a way to run tests: a label, a kind and a handler (VS Code's TestRunProfile).
type TestRunProfileOptions ¶
type TestRunProfileOptions struct {
// IsDefault makes the profile one of those the group runs without being asked which.
IsDefault bool
// Tag limits the profile to the items that carry the tag.
Tag string
// SupportsContinuousRun says that the handler honors TestRunRequest.Continuous.
SupportsContinuousRun bool
// ConfigureHandler is called when the user asks to configure the profile (the gear of the profile picker); nil when it has nothing
// to configure.
ConfigureHandler func()
// LoadDetailedCoverage gives the lines, branches and declarations of a file the run reported coverage for (VS Code's
// loadDetailedCoverage). It is called when the file is opened with coverage on, with a context that ends when the user moves on.
LoadDetailedCoverage func(ctx context.Context, file FileCoverage) (CoverageDetails, error)
// ContinuousTrigger says whether the change of a file starts the continuous run of the item again; nil starts it again when the
// file is the item's URI. uri is file:///path of a changed file.
ContinuousTrigger func(item *TestItem, uri string) bool
}
TestRunProfileOptions are the options of CreateRunProfile.
type TestRunRequest ¶
type TestRunRequest struct {
// Include are the items to run; nil runs all the tests of the controller.
Include []*TestItem
// Exclude are the items not to run; they are children of the included ones.
Exclude []*TestItem
// Profile is the profile that runs them; nil for a run an extension starts on its own.
Profile TestRunProfile
// Continuous says that the tests run again when the files they depend on change (the profile must support it); the handler returns
// when it has started the run, and the context of the handler ends when the continuous run is stopped.
Continuous bool
// PreserveFocus says that the run was not asked for with the Testing view in front.
PreserveFocus bool
}
TestRunRequest says what a run is asked to run (VS Code's TestRunRequest). The handler of a profile receives the request and gives it to CreateTestRun, which joins the run to the request.
type TestStackFrame ¶
type TestStackFrame struct {
// Label is the text (the function), URI the file and Position the place in it; both may be empty.
Label string
URI string
Position *Position
}
TestStackFrame is a line of the stack trace of a failure (VS Code's TestMessageStackFrame).
type TestTreeChange ¶
type TestTreeChange struct {
Kind TestTreeChangeKind
// Item is the item, Parent the item it is a child of (nil at the root) and Path the ids from the root down to the item.
Item *TestItem
Parent *TestItem
Path []string
// Data are the properties of the item when it was added or changed.
Data TestItemData
}
TestTreeChange is a change of a tree made with NewTestTree.
type TestTreeChangeKind ¶
type TestTreeChangeKind int
TestTreeChangeKind says what happened to an item of a tree that has an observer.
const ( // TestItemAdded is an item added to the tree; its descendants are reported after it, each as added. TestItemAdded TestTreeChangeKind = iota + 1 // TestItemRemoved is an item taken out of the tree with its descendants. TestItemRemoved // TestItemChanged is a change of the properties of an item of the tree. TestItemChanged )
type Tests ¶
type Tests interface {
// CreateTestController makes a controller. It fails with ExtensionTestingInvalid for an empty id or label,
// ExtensionTestingControllerTaken when the id is used, ExtensionTestingUnavailable in a scope with no testing service (a host without
// a workbench) and ExtensionDeactivated after the activation ended. The controller is disposed with the activation.
CreateTestController(id, label string) (TestController, error)
}
Tests is the Testing API of an extension in one scope.
type TextChange ¶
type TextChange struct {
// Range is the replaced range, in the text as it was before the change event.
Range Range `json:"range"`
// Text is the text that replaced it.
Text string `json:"text"`
}
TextChange is a replacement of a range with text.
type TextDocument ¶
type TextDocument struct {
// URI is file:///path/to/file or untitled:1.
URI string
// LanguageID is the language of the document.
LanguageID string
// Version is the version of the text; it goes up with every change.
Version int
// Text is the whole text with "\n" line ends.
Text string
}
TextDocument is a document as a provider sees it: an immutable copy of the text at one version.
type TextEdit ¶
TextEdit replaces a range of a document with text. Lines and columns count from 0 and a column counts the bytes of the UTF-8 line, as the core events do (§10.15 "As built (step 11.2)").
type TextReplacement ¶
type TextReplacement struct {
// Range is the replaced range, as the search reported it.
Range Range
// Expected is the text the range has now (TextSearchMatch.Text): when the file has other text there, the file changed
// since the search and the replacement is skipped.
Expected string
// Text is the replacement.
Text string
}
TextReplacement replaces a range of a file with text (ReplaceInFiles).
type TextReplacer ¶
type TextReplacer interface {
// Replace is the replacement for the matched text (TextSearchMatch.Text). It is not safe for concurrent use.
Replace(matchText string) string
}
TextReplacer makes the replacement of a match (see Workspace.NewTextReplacer).
type TextSearchFile ¶
type TextSearchFile struct {
// Path is the path relative to the folder, with forward slashes, and URI the file as file:///path/to/file.
Path, URI string
// Matches are the matches in the order of the text.
Matches []TextSearchMatch
}
TextSearchFile is the matches of one file.
type TextSearchMatch ¶
type TextSearchMatch struct {
// Range is where the match is.
Range Range
// Preview is the text of the line where the match starts (cut around the match when the line is very long).
Preview string
// PreviewStart and PreviewEnd are the match in Preview, in bytes; a match that goes on to the next lines ends at the end
// of Preview.
PreviewStart, PreviewEnd int
// Text is the matched text, with "\n" for each line break.
Text string
}
TextSearchMatch is a match. Lines and columns count from 0, a column counts the bytes of the UTF-8 line (Position).
type TextSearchOptions ¶
type TextSearchOptions struct {
// Include and Exclude are the text of the "files to include" and "files to exclude" boxes of the Search view: globs
// separated by commas, where "./src" is relative to the folder and "src" is a folder or file of that name anywhere.
Include, Exclude string
// DisregardExcludeSettings leaves files.exclude and search.exclude out of the exclusions, and DisregardIgnoreFiles the
// .gitignore and .ignore files (the Search view's "Use Exclude Settings and Ignore Files" toggle turns both).
DisregardExcludeSettings, DisregardIgnoreFiles bool
// OnlyOpenEditors searches the files that editors have open, with their unsaved text, and nothing else.
OnlyOpenEditors bool
// MaxResults is the most matches to report; 20000 (the default of search.maxResults) when not positive.
MaxResults int
}
TextSearchOptions say where to look and what to leave out. The zero value searches the whole folder of the workspace with the settings the user has (files.exclude, search.exclude, the ignore files, symbolic links, files.encoding).
type TextSearchQuery ¶
type TextSearchQuery struct {
// Pattern is the text, or the regular expression (JavaScript's syntax) when IsRegExp is set. It must not be empty.
Pattern string
// IsRegExp says that Pattern is a regular expression.
IsRegExp bool
// IsCaseSensitive matches case; IsWordMatch finds whole words only.
IsCaseSensitive, IsWordMatch bool
// IsSmartCase (search.smartCase) makes the search case sensitive when Pattern has an uppercase letter.
IsSmartCase bool
// IsMultiline lets the search match across lines; it is on anyway for a Pattern with a line break and for a regular
// expression that can match one.
IsMultiline bool
}
TextSearchQuery says what to look for (VS Code's TextSearchQuery).
type TextSearchSummary ¶
type TextSearchSummary struct {
// Files is the number of files with matches and Matches the number of matches.
Files, Matches int
// LimitHit is true when the search stopped at TextSearchOptions.MaxResults.
LimitHit bool
// Searched is the number of files that were read; Binary, TooLarge and Unreadable count the files that were left out
// because they look binary, are too large (over 64 MiB) or could not be read.
Searched, Binary, TooLarge, Unreadable int
}
TextSearchSummary says how a search went.
type Timeline ¶
type Timeline struct {
// Items are the items of the page, in any order.
Items []TimelineItem
// Paging tells whether there is another page.
Paging TimelinePaging
}
Timeline is a page of items (VS Code's Timeline).
type TimelineArg ¶
type TimelineArg struct {
// Source is the ID of the provider and ID that of the item.
Source, ID string
// URI is the file the timeline is for.
URI string
// ContextValue and Label are those of the item.
ContextValue, Label string
// Args is the Args of the item.
Args any
}
TimelineArg is the item that a command of the Timeline view is run for. VS Code passes (item, uri, source, selection); Emetos gives the command one value, a list of objects {"source": "git-history", "id": "abc...", "uri": "file:///a.go", "contextValue": "...", "label": "...", "args": ...}, which TimelineArgs reads: the item first, then the other selected items when the view has several selected (this view selects one row).
func TimelineArgs ¶
func TimelineArgs(args any) []TimelineArg
TimelineArgs reads the arguments a menu of the Timeline view (or the click on an item) gave a command: the objects of the list, in order; nothing for any other value (the command was run from the palette or by a key).
type TimelineItem ¶
type TimelineItem struct {
// ID identifies the item among the items of its provider ("the handle"): a commit hash. The view merges the pages of one provider by
// it, so an item that comes again in a later page replaces the one it has. It is not empty.
ID string
// Label is the text of the row ("Fix the loader").
Label string
// Description is dimmed text after the label ("Ada Example").
Description string
// Detail is the tooltip of the row, as Markdown.
Detail string
// Timestamp is the time of the item; the rows are ordered by it, newest first, and the view writes its age ("3 days") at the end of
// the row.
Timestamp time.Time
// Icon is the name of a Codicon drawn before the label ("git-commit").
Icon string
// ContextValue is the value of the context key timelineItem for the menus of the item (extension.MenuTimelineItemContext):
// "git:file:commit".
ContextValue string
// Command runs when the item is clicked or opened with Enter (VS Code's TimelineItem.command); nil for none.
Command *Command
// Args is the JSON-compatible value the commands of the item's menus get as the member "args" of their argument
// (TimelineArgs). VS Code gives the commands the item object that its provider made, with every member the provider put on it;
// here the provider says what its commands need to know about the item.
Args any
}
TimelineItem is one entry of the history of a file (VS Code's TimelineItem).
type TimelineOptions ¶
type TimelineOptions struct {
// Cursor is the Paging.Cursor the provider gave with the previous page; empty asks for the first page.
Cursor string
// Limit is the most items the page may have; 0 asks for all of them (the view asks for the items it shows again, when the history
// changes). A provider that has more says so with a cursor.
Limit int
}
TimelineOptions say which items a provider is asked for (VS Code's TimelineOptions).
type TimelinePaging ¶
type TimelinePaging struct {
// Cursor is what the provider gets back in TimelineOptions.Cursor for the page after this one; empty when there is none.
Cursor string
}
TimelinePaging says where the next page starts (VS Code's Timeline.paging).
type TimelineProvider ¶
type TimelineProvider struct {
// ID is the source of the items: it names the provider in the view's filter ("git-history") and is unique in the window tab.
ID string
// Label is its name in the filter ("Git History").
Label string
// Schemes are the URI schemes the provider has a history for ("file"); "*" is every scheme. At least one is needed.
Schemes []string
// Provide makes a page of the history of the file at uri (file:///path). It runs off the UI thread, with a context that is
// cancelled when the view no longer wants the answer. A file with no history is an empty page, not an error. A panic fails the
// extension (ExtensionTimelinePanicked).
Provide func(ctx context.Context, uri string, opts TimelineOptions) (Timeline, error)
}
TimelineProvider provides the history of files (VS Code's TimelineProvider).
type TimelineRegistration ¶
type TimelineRegistration interface {
// Changed says that the history of the files may have changed (VS Code's onDidChange): the view loads the items again, as many as it
// shows, when one of them is the file in front. With no URI every file is meant. It may be called from any goroutine.
Changed(uris ...string)
// Dispose removes the provider and its items from the view. It happens by itself when the activation ends.
Dispose()
}
TimelineRegistration is a registered provider.
type Timelines ¶
type Timelines interface {
// RegisterProvider adds a provider. It fails with ExtensionTimelineInvalid for a provider with no ID, no label, no scheme or no
// Provide, ExtTimelineProviderTaken when the window tab has a provider with the ID, ExtensionTimelineUnavailable in a scope that
// has no Timeline view (a host without a workbench) and ExtensionDeactivated after the activation ended.
RegisterProvider(provider TimelineProvider) (TimelineRegistration, error)
}
Timelines registers the timeline providers of an extension.
type Token ¶
Token is a token of a line of highlighted text: the bytes [Start, End) of the line and the TextMate scopes of the token, outermost first. The color is the theme's (package ui resolves it).
type Validation ¶
type Validation struct {
// Message is the text; Markdown is not drawn as such yet.
Message string
// Level is the severity.
Level ValidationLevel
}
Validation is the message shown under the input for the text in it.
type ValidationLevel ¶
type ValidationLevel int
ValidationLevel is the severity of a Validation (VS Code's SourceControlInputBoxValidationType).
const ( // ValidationError is shown in the colors inputValidation.error*. ValidationError ValidationLevel = iota // ValidationWarning is shown in the colors inputValidation.warning*. ValidationWarning // ValidationInfo is shown in the colors inputValidation.info*. ValidationInfo )
The levels of a Validation, in VS Code's order.
type ViewActionSpec ¶
type ViewActionSpec struct {
// View is the id of a view of the extension.
View string
// Command is the id of the command the button runs.
Command string
// Icon is the name of the Codicon of the button.
Icon string
// Tooltip is the text of the hover; the title of the command when empty.
Tooltip string
// When is a when-clause under which the button is shown; empty is always.
When string
// Order orders the buttons of a view, the lowest first.
Order float64
}
ViewActionSpec declares a title action of a view: an icon button at the right end of its header (a side bar view's header, the title strip of the panel for a panel view), shown while the pointer is over the view or the focus is in it for a side bar view and always for the tab that is open in the panel.
type ViewContainerSpec ¶
type ViewContainerSpec struct {
// ID identifies the container among the containers of Emetos. It starts with the id of the extension and a dot
// (acme.build.container).
ID string
// Title is the name in the title of the side bar and the tooltip of the icon.
Title string
// Icon is the name of the Codicon of the activity bar ("checklist", "list-tree").
Icon string
// Order orders the icons of the activity bar, the lowest first; the built-in Explorer is 0. Zero is put after
// everything the editor has.
Order int
}
ViewContainerSpec declares a view container of the side bar: an icon in the activity bar, and the views it holds. The extension's container shows when the user clicks the icon, or runs the command ShowViewCommand(ID).
type ViewContent ¶
type ViewContent struct {
// Build makes the widget of the view. It is called when the view is shown and again after Refresh. The widget is put
// in a box: it gets the constraints of the view, cannot paint outside them, and the text style and colors of the theme
// are those of the side bar or the panel.
Build func(bc widgets.BuildContext) widgets.Widget
// SaveState returns the state the extension wants kept for the view: a value that encodes to JSON, or nil for none.
// It is called when the view goes off screen (another tab of the panel, a container of the side bar, a closed panel)
// and when Emetos saves the state of the workspace, so the state also survives a restart.
SaveState func() (any, error)
// RestoreState gives the view the JSON of the state that SaveState returned, before the first Build after the view
// was provided and whenever the box is made again. It is not called when nothing was saved.
RestoreState func(state json.RawMessage) error
// AllowCommand, when set, is asked while the keyboard focus is in the view and a key press is bound to a command: with
// true the window runs the command as it always does, with false the window leaves the key to the focused widget of the
// view, which is how a terminal gets Ctrl+W or Ctrl+P unless the command is one that skips the shell (SPEC §10.25 "Commands,
// keys and context keys"). A key bound to no command, and a key that starts a chord, are not asked about. It is called on
// the UI thread; a panic in it deactivates the extension.
AllowCommand func(commandID string) bool
}
ViewContent is what an extension puts in a view it declared. All the functions run on the UI thread, and a panic in any of them, in Build or in the widgets that Build makes with the helpers of package ui, deactivates the extension in the scope: the view shows "<Name> failed" with a Show Log button (SPEC §10.15 "Lifetime").
type ViewDocumentChange ¶
type ViewDocumentChange struct {
// Version is the version of the document after the change.
Version int
// Cause is edit, undo, redo, lineEnding or setText, as in emetos.document.changed.
Cause string
}
ViewDocumentChange tells a file view that its document changed.
type ViewHandle ¶
type ViewHandle interface {
// Refresh builds the view again, later, on the UI thread: call it when the data the view shows changed.
Refresh()
// SetBadge puts a count on the tab of a panel view, in the pill the Problems tab has; 0 takes it away. tooltip is
// the hover of the pill. It does nothing for a side bar view.
SetBadge(count int, tooltip string)
// SetTitle sets the title in the header of a side bar view (the name the manifest gave it, until this is called), as VS
// Code's TreeView.title does: the references view says "References" or "Implementations" by what it lists. An empty title
// goes back to the name. It does nothing for a panel view, whose tab has the title of its spec.
SetTitle(title string)
// Reveal shows the view: the container of a side bar view is opened (and the side bar shown), the tab of a panel
// view is selected (and the panel shown). With focus the keyboard focus goes into it.
Reveal(focus bool)
// Hide hides the panel when the view is a panel view and its tab is the one that is open (it does nothing otherwise), and
// gives the keyboard focus to the editor area: the last terminal ending uses it. The view stays declared.
Hide()
// Dispose takes the content away; the view stays declared and shows nothing.
Dispose()
}
ViewHandle controls a view that was provided.
type ViewNotification ¶
type ViewNotification struct {
// ID identifies the notification for RunNotificationAction; it is not the same in another run of Emetos.
ID uint64
// Severity says how serious it is, Source which part of Emetos raised it ("Git") and Message what it says.
Severity NotificationSeverity
Source string
Message string
// Actions are the labels of the buttons, in order; RunNotificationAction takes the place in this list.
Actions []string
}
ViewNotification is a notification of the workspace as a headless view hands it over to its client (OnNotification).
type ViewSpec ¶
type ViewSpec struct {
// ID identifies the view. It starts with the id of the extension and a dot.
ID string
// Name is the title in the header of the view.
Name string
// Container is the id of the container: one the extension declares, or one of Emetos (workbench.view.explorer).
Container string
// When is a when-clause under which the view is shown; empty is always. It reads the context keys of the window and
// the ones the extension sets with Context().
When string
// Order orders the views of a container, the lowest first.
Order int
// Collapsed starts the view with its body folded away.
Collapsed bool
}
ViewSpec declares a view of the side bar: a section with a header and a body in a container.
type ViewWelcomeSpec ¶
type ViewWelcomeSpec struct {
// View is the id of the view the content is for; it need not be one of the extension.
View string
// Contents is the content in Markdown, as a view's welcome content has it: paragraphs of text, **bold** and `code` spans,
// links ([Learn more](https://example.com) opens the address, [Open](command:ext.command) runs a command) and buttons: a
// link that is alone in its paragraph is drawn as a button. A command link may carry arguments after a "?" as JSON
// (command:ext.cmd?%5B1%5D, URL-encoded).
Contents string
// When is a when-clause under which the content is shown; empty is always.
When string
// Group orders the pieces of a view: the pieces of the group "navigation" come first, then the others by group name, then
// those without a group (VS Code's group, written "navigation@1" with the place after the "@").
Group string
// Enablement is a when-clause under which the buttons of the content are enabled; empty is always. A button whose condition
// does not hold is drawn dimmed and does nothing.
Enablement string
}
ViewWelcomeSpec is a piece of welcome content of a view (VS Code's contributes.viewsWelcome entry, SPEC §10.30): what a view that is empty shows in place of its rows. A view shows the pieces whose When holds, one below the other, in the order of the manifests; the Source Control view and the Explorer show theirs when they have nothing else to show. Several extensions may add to one view.
type Views ¶
type Views interface {
// Provide sets the content of a view of the manifest (Contributes.Views or Contributes.PanelViews). It fails with
// ExtensionViewNotDeclared when the manifest does not declare the view, with ExtensionViewProvided when the activation
// provided it already, and with ExtensionViewContentInvalid when Build is nil. The state the view saved last time is
// restored when it is shown.
Provide(viewID string, content ViewContent) (ViewHandle, error)
}
Views gives the views the manifest declares their content.
type WatchSpec ¶
type WatchSpec struct {
// Path is the absolute path of the folder.
Path string
// Recursive watches everything below the folder, as it grows; a link to a folder is not followed.
Recursive bool
// Excludes are paths and globs that are matched against the path relative to Path (files.watcherExclude's syntax: "**/node_modules",
// "objects"); what they match is not watched and gives no changes.
Excludes []string
}
WatchSpec says what Workspace().Watch watches.
type WindowFocus ¶
type WindowFocus struct {
// Focused is true when the window has the focus now.
Focused bool `json:"focused"`
}
WindowFocus is the payload of TopicWindowFocusChanged.
type WindowTab ¶
type WindowTab interface {
// ID is the id of the tab, kept across restarts: the scope of the tab is named "<extension id>:<id>" in the links
// between window tabs (ScopeInfo.ID).
ID() string
// Kind is the id of the kind of the tab.
Kind() string
// SetTitle sets the name on the tab of the strip (the title of the kind when none was set); SetHint the text of its
// tooltip (the title when empty). Both are kept across restarts.
SetTitle(title string)
SetHint(hint string)
// StateChanged says that what SaveState returns changed, so that Emetos writes it soon (a second at most), and not
// only when the tab goes off screen or Emetos quits.
StateChanged()
// Refresh builds the widget of the tab again.
Refresh()
// CaptureKeys says that the content takes the keyboard: while it is true and the content has the keyboard focus, the
// shortcuts of the window tab do not act, except the ones that act on the window itself (switching, opening and closing
// the tabs, quitting, full screen), so every other key reaches the content as a key event. A tab that shows another
// computer's screen sets it; it is false when a tab opens.
CaptureKeys(capture bool)
// Close closes the tab, without asking: an extension keeps its data in the state it saves.
Close()
}
WindowTab is the window tab an extension is shown in: the one tab of the scope it was activated in. Its methods run on the UI thread.
type WindowTabContent ¶
type WindowTabContent struct {
// Build makes the widget of the tab; like the widget of a view it is built inside a box that gives it the whole area
// below the title bar as its constraints, clips what it paints, keeps the keyboard focus and catches a panic.
Build func(bc widgets.BuildContext) widgets.Widget
// SaveState returns the state of the tab that is kept in the state of the window (a value that encodes to JSON, nil
// for none). It is called when the tab goes off screen, when the extension is deactivated and when the window state is
// written. The state is given to the kind's Create when the tab comes back.
SaveState func() (any, error)
// OnClose is called when the tab is closed for good (not when the extension is deactivated or Emetos quits); the
// state of the tab is dropped after it.
OnClose func()
}
WindowTabContent is what an extension puts in its window tab. All the functions run on the UI thread, and a panic in any of them, or in a widget Build makes, deactivates the extension in the scope: the tab shows "<Name> failed" with a Show Log button (SPEC §10.15 "Lifetime").
type WindowTabKind ¶
type WindowTabKind struct {
// Create makes the content of the tab, with the state SaveState returned in the session before (nil for a tab that was
// just opened). The title and the hint may be set on tab at once. It is called once for each activation, on the UI
// thread.
Create func(tab WindowTab, state json.RawMessage) (WindowTabContent, error)
}
WindowTabKind is how an extension makes the content of its window tab.
type WindowTabKindSpec ¶
type WindowTabKindSpec struct {
// ID identifies the kind. It starts with the id of the extension and a dot (emetos.remotework.tab).
ID string
// Title is the title of a tab that has not set one, and the name the Extensions page and the log call the tab.
Title string
// Icon is the name of the Codicon in the tab of the strip ("note", "remote"); may be empty (the icon "window").
Icon string
// PlusMenuLabel is the text of the entry of the "+" menu; the title when empty. By the convention of the menu the
// label ends with "..." when choosing it asks for more before the work is done.
PlusMenuLabel string
}
WindowTabKindSpec declares a kind of window tab: a tab in the strip of the window beside the workspaces, with a widget of the extension in place of a workbench (SPEC §10.15 "Window tab", §10.14). Emetos lists every kind in the menu of the "+" button, opens a tab of it when the entry is chosen, and brings it back when Emetos restarts, with the state the extension saved. The extension gives the kind its content with WindowTabs().Provide, in the scope of the tab.
type WindowTabs ¶
type WindowTabs interface {
// Provide sets how the tab of a kind the manifest declares is made, and makes the content of the tab of this scope
// (the window tab the extension was activated for, with its saved state). It fails with
// ExtensionWindowTabKindNotDeclared when the manifest does not declare the kind, ExtensionWindowTabKindInvalid when
// Create is nil, ExtensionWindowTabKindProvided when the activation provided it already and
// ExtensionWindowTabUnavailable in a scope that is not a window tab of this kind.
Provide(kindID string, kind WindowTabKind) error
}
WindowTabs gives the extension the content of the window tabs of the kinds its manifest declares.
type Workspace ¶
type Workspace interface {
// Files lists the files of the folder. It fails with ExtensionNoFolder in a scope with no folder.
Files() (FileList, error)
// ReadFile reads a file of the folder from disk, by its path relative to the folder, as UTF-8 text. It sees no unsaved
// changes (Documents().Read does). It fails with ExtensionNoFolder, ExtensionFilePathInvalid for a path that leaves
// the folder (a .. or a link that points out of it), ExtensionFileTooLarge above MaxReadFileSize and
// ExtensionFileNotText for a file that is not valid UTF-8; the error of the file system is wrapped otherwise. Unlike
// Documents().Read it may be called from any goroutine.
ReadFile(ctx context.Context, path string) (string, error)
// OpenURI opens a URI with the desktop (the OpenURI portal): a web address in the browser, a mail address in the mail
// program. It fails with ExtensionOpenURIUnavailable when the scope cannot, and returns the portal's error otherwise.
OpenURI(ctx context.Context, uri string) error
// RevealFile shows the file with the URI (file:///path) in the Explorer view (VS Code's revealInExplorer), or with inOS the folder
// that holds it in the file manager of the desktop (revealFileInOS, "Open Containing Folder"). It fails with
// ExtensionFilePathInvalid for a URI that is not a file, ExtensionRevealUnavailable when the scope cannot, and ExtensionDeactivated
// after the activation ended. Call it on the UI thread.
RevealFile(uri string, inOS bool) error
// TrashFiles moves the files and folders with the URIs (file:///path) to the trash of the user (SPEC §6.3, the trash the Explorer's
// Delete uses), as one operation of the file operations history, and returns the function that takes exactly this operation back
// (the files are restored where they were, whatever the user did after it). The function fails with the tags of the file
// operations when something is at an old path now or when the operation is gone from the history (it was undone from the Explorer
// already); it may be called from any goroutine, once. Open editors of the files follow as they do for a deletion in the Explorer.
// It blocks while the files are moved, so call it from a goroutine of the extension. It fails with ExtensionFilePathInvalid for a
// URI that is not a clean absolute file, ExtensionTrashUnavailable when the scope has no trash (a window tab of an extension, a
// headless host), ExtensionDeactivated after the activation ended, and with the tags of the trash (TrashCrossDevice for a file on
// another file system than the trash: the caller may offer to delete it for good, TrashSourceMissing, TrashFailed); the files
// moved before a failure stay in the trash and the returned function is nil.
TrashFiles(ctx context.Context, uris []string) (undo func(ctx context.Context) error, err error)
// OpenWindowTab opens the window tab of a kind of window tab (the id of a kind in a manifest's WindowTabKinds, this
// extension's or another one's) and makes it the active one; when a tab of the kind is open already it is shown instead of a
// second one (SPEC §10.29: the open command of Remote Work). It fails with ExtensionOpenWindowTabUnavailable when the scope cannot, and
// returns the window's error for a kind that is unknown or turned off. Call it on the UI thread.
OpenWindowTab(kindID string) error
// OpenFolder opens the folder (an absolute path) as the folder of the workspace: with newTab false it replaces the folder of the
// window tab of the scope, after the questions about unsaved changes of the editors it closes (VS Code's vscode.openFolder with
// forceReuseWindow); with newTab true it opens a new workspace tab (SPEC §10.14), or shows the tab that has the folder already
// (forceNewWindow). It returns before the folder is open, and the scope is made again when the tab's folder changes, so nothing is
// asked of the result: the Git extension opens a clone this way. It fails with ExtensionFilePathInvalid for a path that is not
// absolute, ExtensionOpenFolderUnavailable when the scope cannot (a window tab of an extension, a headless host) and
// ExtensionDeactivated after the activation ended. Call it on the UI thread.
OpenFolder(path string, newTab bool) error
// NewHeadlessView makes a second, off-screen view of the workspace, size pixels large (HeadlessView). The view starts
// with the editors the workspace has open in front of the user. It fails with ExtensionHeadlessSize for a size that is
// not allowed (positive, at most MaxHeadlessSide a side and MaxHeadlessPixels in all), ExtensionHeadlessUnavailable in
// a scope that has no workspace to show (a window tab of an extension, a workspace that is not on screen yet) and
// ExtensionDeactivated after the activation ended. Call it on the UI thread.
NewHeadlessView(size Size) (HeadlessView, error)
// FindTextInFiles searches the files of the folder for the query and calls onFile with the matches of each file that has
// some, as the search goes on (SPEC §10.27). The goroutine rules:
// - It blocks until the search is over, so it is called from a goroutine of the extension and never from the UI
// thread (it asks the UI thread for the text of the editors that have unsaved changes and would wait for itself).
// - onFile is called on goroutines of the search, not on the UI thread, and never at the same time as itself; it must
// not touch widgets, and hands what it gets to the UI thread with API.Post (once a frame at most, for a long list).
// It must not block for long. A panic in it is not caught.
// - When ctx ends the search stops and the call returns the error of the context (the tag SearchCancelled); onFile is
// not called after the call returned. The matches are in the order of the text in each file, and the files in no
// fixed order.
// It fails with ExtensionNoFolder in a scope with no folder, ExtensionDeactivated after the activation ended,
// SearchPatternEmpty for an empty pattern, and the error of the regular expression (RegexUnbalancedParen, RegexUnterminatedClass, ...)
// for one that does not compile.
FindTextInFiles(ctx context.Context, query TextSearchQuery, opts TextSearchOptions, onFile func(TextSearchFile)) (TextSearchSummary, error)
// NewTextReplacer makes the replacer of a search: the replacement for a match, as VS Code's search makes it. For a regular
// expression the replacement may have $1 and $&, \n and \t and the case operations \u \U \l \L; for a plain text it is
// used as it is; preserveCase makes it follow the case of the text it replaces. It may be called from any goroutine. It
// fails as FindTextInFiles does for the query.
NewTextReplacer(query TextSearchQuery, replacement string, preserveCase bool) (TextReplacer, error)
// ReplaceInFiles makes replacements in files of the folder that no editor has open (those of an open editor are made
// with Documents().Apply, which is one undo step of the document). Each file is read as the editor reads it, changed,
// and written again with the same encoding, byte order mark and line ending, atomically; a replacement whose range no
// longer has the expected text is skipped. A file that cannot be changed is listed in the report and left as it was; the
// others are still done. It fails with ExtensionNoFolder, ExtensionDeactivated and ExtensionFilePathInvalid (a path that
// leaves the folder), and with the error of ctx. It may be called from any goroutine.
ReplaceInFiles(ctx context.Context, files []FileReplacement) (ReplaceReport, error)
// Watch watches a folder, any absolute folder the user may read (the git directory of a parent repository is outside the
// folder of the workspace), and calls fn with the changes below it. The changes are those of the watcher of the window
// (inotify, or a scan every few seconds where inotify cannot be used, SPEC §10.5), gathered by its debounce and then
// batched: fn gets at most one batch for each turn of the UI thread, on the UI thread, with the paths absolute. The
// events of WatchSpec.Excludes are not reported and their folders are not watched. cancel stops it; it also ends with the
// activation. It blocks while the watches are placed (it reads the folder), so call it from a goroutine of the extension,
// not from the UI thread. It fails with ExtensionWatchUnavailable in a scope with no watcher, ExtensionWatchPathInvalid for
// a path that is not absolute, ExtensionDeactivated after the activation ended, and with the tags of the watcher
// (WatcherPathNotFound, WatcherStatFailed, WatcherAddFailed) for a folder that cannot be watched.
Watch(ctx context.Context, spec WatchSpec, fn func([]FileChange)) (cancel func(), err error)
}
Workspace gives the extension the folder of the workspace, read only.
type WorkspaceEdit ¶
type WorkspaceEdit struct {
Changes []ResourceChange
}
WorkspaceEdit changes several documents and files; Emetos applies it with one undo step per document.
type WorkspaceInfo ¶
type WorkspaceInfo struct {
Kind ScopeKind `json:"kind"`
Name string `json:"name"`
Folder string `json:"folder,omitempty"`
// WindowTab is the id of the kind of an extension's window tab, empty for a workspace.
WindowTab string `json:"windowTab,omitempty"`
// ID names the scope in the links between window tabs (ScopeInfo.ID); empty for a tab that has no folder.
ID string `json:"id,omitempty"`
// Instance is ScopeInfo.Instance; it is not part of the payload (the conversion from a ScopeInfo needs the same fields).
Instance int `json:"-"`
}
WorkspaceInfo is the payload of the workspace events and of TopicWindowTabActivated.
Source Files
¶
- api.go
- banners.go
- builtin.go
- content.go
- core.go
- debug.go
- decorations.go
- dialogs.go
- doc.go
- editordecorations.go
- editors.go
- events.go
- extension.go
- headless.go
- history.go
- inputbox.go
- languageservers.go
- manifest.go
- multidiff.go
- origin.go
- providers.go
- quickdiff.go
- quickpick.go
- resources.go
- scm.go
- search.go
- state.go
- tasks.go
- terminalenv.go
- testing.go
- timeline.go
- views.go
- windowtabs.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package contenttest is the conformance suite of the provided documents of the extension contract (Documents().ProvideContent, OpenDiff, OpenDocument, Tabs, CloseTabs, Dirty and SaveAll, and ProvideMultiDiff and OpenMultiDiff of the multi-file diff editor): the host runs it over a window tab, and the fake of the tests of the extensions runs it too, so that an extension that passes its tests against the fake meets the same rules in the window.
|
Package contenttest is the conformance suite of the provided documents of the extension contract (Documents().ProvideContent, OpenDiff, OpenDocument, Tabs, CloseTabs, Dirty and SaveAll, and ProvideMultiDiff and OpenMultiDiff of the multi-file diff editor): the host runs it over a window tab, and the fake of the tests of the extensions runs it too, so that an extension that passes its tests against the fake meets the same rules in the window. |
|
Package decorationstest is the conformance suite of the File Decorations API (extension.Decorations, SPEC §10.30, step 24.6): one set of tests that both implementations of the API pass, the host (internal/gui/exthost, over the service of internal/core/decorations) and the fake of the tests of the extensions (extensions/internal/fakeapi).
|
Package decorationstest is the conformance suite of the File Decorations API (extension.Decorations, SPEC §10.30, step 24.6): one set of tests that both implementations of the API pass, the host (internal/gui/exthost, over the service of internal/core/decorations) and the fake of the tests of the extensions (extensions/internal/fakeapi). |
|
Package editordecorationstest is the conformance suite of the Editor Decorations API (extension.EditorDecorations, SPEC §10.30, step 24.22): one set of tests that both implementations of the API pass, the host (internal/gui/exthost, over the store of internal/core/annotations) and the fake of the tests of the extensions (extensions/internal/fakeapi).
|
Package editordecorationstest is the conformance suite of the Editor Decorations API (extension.EditorDecorations, SPEC §10.30, step 24.22): one set of tests that both implementations of the API pass, the host (internal/gui/exthost, over the store of internal/core/annotations) and the fake of the tests of the extensions (extensions/internal/fakeapi). |
|
Package historytest is the conformance suite of the history API of a source control (extension.SourceControl.SetHistoryProvider, SPEC §10.30 "The Source Control Graph", step 24.20): one set of tests that the host (internal/gui/exthost) and the fake (extensions/internal/fakeapi) both pass, so that the tests of an extension that run on the fake mean what they say.
|
Package historytest is the conformance suite of the history API of a source control (extension.SourceControl.SetHistoryProvider, SPEC §10.30 "The Source Control Graph", step 24.20): one set of tests that the host (internal/gui/exthost) and the fake (extensions/internal/fakeapi) both pass, so that the tests of an extension that run on the fake mean what they say. |
|
Package jsonc parses JSON with comments and edits it while keeping the comments (SPEC §11.1).
|
Package jsonc parses JSON with comments and edits it while keeping the comments (SPEC §11.1). |
|
Package scmtest is the conformance suite of the Source Control API (extension.SourceControls, SPEC §10.30, step 24.2): one set of tests that both implementations of the API pass, the host (internal/gui/exthost, over the model of internal/core/scm) and the fake of the tests of the extensions (extensions/internal/fakeapi).
|
Package scmtest is the conformance suite of the Source Control API (extension.SourceControls, SPEC §10.30, step 24.2): one set of tests that both implementations of the API pass, the host (internal/gui/exthost, over the model of internal/core/scm) and the fake of the tests of the extensions (extensions/internal/fakeapi). |
|
Package terminalenvtest is the conformance suite of the Terminal Environment API (extension.TerminalEnvironment, SPEC §10.30, step 24.23): one set of tests that both implementations of the API pass, the host (internal/gui/exthost) and the fake of the tests of the extensions (extensions/internal/fakeapi).
|
Package terminalenvtest is the conformance suite of the Terminal Environment API (extension.TerminalEnvironment, SPEC §10.30, step 24.23): one set of tests that both implementations of the API pass, the host (internal/gui/exthost) and the fake of the tests of the extensions (extensions/internal/fakeapi). |
|
Package timelinetest is the conformance suite of the Timeline API (extension.Timelines, SPEC §10.30, step 24.21): one set of tests that both implementations of the API pass, the host (internal/gui/exthost, over the service of internal/core/timeline) and the fake of the tests of the extensions (extensions/internal/fakeapi).
|
Package timelinetest is the conformance suite of the Timeline API (extension.Timelines, SPEC §10.30, step 24.21): one set of tests that both implementations of the API pass, the host (internal/gui/exthost, over the service of internal/core/timeline) and the fake of the tests of the extensions (extensions/internal/fakeapi). |
|
Package ui is what an extension builds the widgets of its views with (SPEC §10.15 "As built (step 11.5)").
|
Package ui is what an extension builds the widgets of its views with (SPEC §10.15 "As built (step 11.5)"). |
|
markdown
Package markdown renders Markdown for the extensions of Emetos (SPEC §10.15 "As built (step 11.6)"): a parser that turns a text into a tree of blocks (headings, paragraphs, lists, block quotes, code blocks, tables, rules) and inlines (emphasis, code, links, images), and a widget that draws the tree with the theme of the window.
|
Package markdown renders Markdown for the extensions of Emetos (SPEC §10.15 "As built (step 11.6)"): a parser that turns a text into a tree of blocks (headings, paragraphs, lists, block quotes, code blocks, tables, rules) and inlines (emphasis, code, links, images), and a widget that draws the tree with the theme of the window. |
|
uitest
Package uitest is the test harness for the widgets of an extension's views: it shows a widget in a window with the theme of Dark Modern or Light Modern and the test fonts, so a widget test or a golden test of an extension does not depend on the machine's fonts.
|
Package uitest is the test harness for the widgets of an extension's views: it shows a widget in a window with the theme of Dark Modern or Light Modern and the test fonts, so a widget test or a golden test of an extension does not depend on the machine's fonts. |
|
uitest/mdfixture
Package mdfixture makes the big Markdown document that the tests and the benchmark of the preview use (SPEC §14 "Markdown preview", step 17b.2): a document of about 700 KB with 150 images, the size of docs/IMPLEMENTED.md in October 2026, made from small generated PNG files, so that no test depends on a document that changes with every step of the plan.
|
Package mdfixture makes the big Markdown document that the tests and the benchmark of the preview use (SPEC §14 "Markdown preview", step 17b.2): a document of about 700 KB with 150 images, the size of docs/IMPLEMENTED.md in October 2026, made from small generated PNG files, so that no test depends on a document that changes with every step of the plan. |