workspace.nvim
Type of pattern used by workspace folder.
All 80 public APIs exported from the workspace module, with declarations, documentation, and source-backed examples.
Generated from typings/index.d.ts @ 555f5ceon
Type of pattern used by workspace folder.
Current buffer number, could be wrong since vim could not send autocmd as expected.
workspace.bufnr: numberReturns a Promise that resolves to the active buffer/document instance in Vim/Neovim.
workspace.document: Promise<Document>import { workspace, ExtensionContext } from 'coc.nvim';
export async function activate(context: ExtensionContext) {
// workspace.document returns a Promise, use await to get the active Document
const doc = await workspace.document;
if (doc) {
console.log('Active document URI:', doc.uri);
console.log('Language ID:', doc.filetype);
console.log('Line count:', doc.lineCount);
}
}Environments or current (neo)vim.
Float window or popup can work.
workspace.floatSupported: booleanCurrent working directory of vim.
workspace.cwd: stringCurrent workspace root.
workspace.root: stringworkspace.rootPath: stringNot neovim when true.
workspace.isVim: booleanIs neovim when true.
workspace.isNvim: booleanAll filetypes of loaded documents.
workspace.filetypes: ReadonlySet<string>All languageIds of loaded documents.
workspace.languageIds: ReadonlySet<string>Root directory of coc.nvim
workspace.pluginRoot: stringExists channel names.
workspace.channelNames: ReadonlyArray<string>Loaded documents that attached.
Current document array.
workspace.textDocuments: ReadonlyArray<LinesTextDocument>Current workspace folders.
workspace.workspaceFolders: ReadonlyArray<WorkspaceFolder>Directory paths of workspaceFolders.
workspace.folderPaths: ReadonlyArray<string>Current workspace folder, could be null when vim started from user's home.
workspace.workspaceFolder: WorkspaceFolder | nullField/Property workspace.onDidCreateFiles exported by workspace.
workspace.onDidCreateFiles: Event<FileCreateEvent>Field/Property workspace.onDidRenameFiles exported by workspace.
workspace.onDidRenameFiles: Event<FileRenameEvent>Field/Property workspace.onDidDeleteFiles exported by workspace.
workspace.onDidDeleteFiles: Event<FileDeleteEvent>Field/Property workspace.onWillCreateFiles exported by workspace.
workspace.onWillCreateFiles: Event<FileWillCreateEvent>Field/Property workspace.onWillRenameFiles exported by workspace.
workspace.onWillRenameFiles: Event<FileWillRenameEvent>Field/Property workspace.onWillDeleteFiles exported by workspace.
workspace.onWillDeleteFiles: Event<FileWillDeleteEvent>Event fired on workspace folder change.
workspace.onDidChangeWorkspaceFolders: Event<WorkspaceFoldersChangeEvent>Event fired after document create.
workspace.onDidOpenTextDocument: Event<LinesTextDocument & { bufnr: number }>Event fired after document unload.
workspace.onDidCloseTextDocument: Event<LinesTextDocument & { bufnr: number }>Event fired on document change.
workspace.onDidChangeTextDocument: Event<DidChangeTextDocumentParams>Event fired before document save.
workspace.onWillSaveTextDocument: Event<WillSaveEvent>Event fired after document save.
workspace.onDidSaveTextDocument: Event<LinesTextDocument>Event fired on configuration change. Configuration change could by many reasons, including:
coc-settings.json.workspace.onDidChangeConfiguration: Event<ConfigurationChangeEvent>Fired when vim's runtimepath change detected.
Returns a path that is relative to the workspace folder or folders.
When there are no workspace folders or when the path is not contained in them, the input is returned.
workspace.asRelativePath(pathOrUri: string | Uri, includeWorkspaceFolder?: boolean): string| Parameter | Type | Description |
|---|---|---|
| pathOrUri | string | Uri | A path or uri. When a uri is given its fsPath is used. |
| includeWorkspaceFolder? | boolean | When |
A path relative to the root or the input.
Returns converted unix path when the vim is built with win32unix enabled. Original fullpath is returned when the convert is not necessary. Only needed when the fullpath is passed vim directly.
workspace.fixWin32unixFilepath(fullpath: string): string| Parameter | Type | Description |
|---|---|---|
| fullpath | string | The filepath to fix, only windows absolute filepath is fixed. |
Opens a document. Will return early if this document is already open. Otherwise the document is loaded and the didOpen-event fires.
The document is denoted by an Uri. Depending on the scheme the following rules apply:
file-scheme: Open a file on disk (openTextDocument(Uri.file(path))). Will be rejected if the file
does not exist or cannot be loaded.untitled-scheme: Open a blank untitled file with associated path (openTextDocument(Uri.file(path).with({ scheme: 'untitled' }))).
The language will be derived from the file name.TextDocumentContentProvider text document content providers and
file system providers are consulted.Note that the lifecycle of the returned document is owned by the editor and not by the extension. That means an
onDidClose-event can occur at any time after opening it.
Get display cell count of text on vim. Control character below 0x80 are considered as 1.
workspace.getDisplayWidth(text: string, cache?: boolean): number| Parameter | Type | Description |
|---|---|---|
| text | string | Text to display. |
| cache? | boolean |
The cells count.
Like vim's has(), but for version check only. Check patch on neovim and check nvim on vim would return false.
For example:
workspace.has(feature: string): boolean| Parameter | Type |
|---|---|
| feature | string |
Register autocmd on vim.
Note: avoid request autocmd when possible since vim could be blocked forever when request triggered during request.
workspace.registerAutocmd(autocmd: Autocmd, disposables?: Disposable[]): Disposable| Parameter | Type |
|---|---|
| autocmd | Autocmd |
| disposables? | Disposable[] |
Watch for vim's global option change.
workspace.watchOption(key: string, callback: (oldValue: any, newValue: any) => Thenable<void> | void, disposables?: Disposable[]): void| Parameter | Type |
|---|---|
| key | string |
| callback | (oldValue: any, newValue: any) => Thenable<void> | void |
| disposables? | Disposable[] |
Watch for vim's global variable change, works on neovim only.
workspace.watchGlobal(key: string, callback?: (oldValue: any, newValue: any) => Thenable<void> | void, disposables?: Disposable[]): void| Parameter | Type |
|---|---|
| key | string |
| callback? | (oldValue: any, newValue: any) => Thenable<void> | void |
| disposables? | Disposable[] |
Check if selector match document.
workspace.match(selector: DocumentSelector, document: TextDocumentMatch): number| Parameter | Type |
|---|---|
| selector | DocumentSelector |
| document | TextDocumentMatch |
Findup from filename or filenames from current filepath or root.
workspace.findUp(filename: string | string[]): Promise<string | null>| Parameter | Type |
|---|---|
| filename | string | string[] |
fullpath of file or null when not found.
Get possible watchman binary path.
workspace.getWatchmanPath(): string | nullRetrieve scoped user or workspace settings from coc-settings.json.
workspace.getConfiguration(section?: string, scope?: ConfigurationScope): WorkspaceConfigurationimport { workspace } from 'coc.nvim';
export function activate() {
const config = workspace.getConfiguration('myextension');
const isEnabled = config.get<boolean>('enable', true);
console.log('Feature enabled:', isEnabled);
}| Parameter | Type |
|---|---|
| section? | string |
| scope? | ConfigurationScope |
Resolve internal json schema, uri should starts with vscode://
workspace.resolveJSONSchema(uri: string): any| Parameter | Type |
|---|---|
| uri | string |
Get created document by uri or bufnr.
Applies workspace file edits across open and unopened files using coc.nvim buffer handling.
workspace.applyEdit(edit: WorkspaceEdit, metadata?: WorkspaceEditMetadata): Promise<boolean>import { workspace, WorkspaceEdit } from 'coc.nvim';
export async function activate() {
const edit: WorkspaceEdit = {
changes: {
'file:///path/to/file.ts': [
{
range: { start: { line: 0, character: 0 }, end: { line: 0, character: 5 } },
newText: 'const'
}
]
}
};
await workspace.applyEdit(edit);
}| Parameter | Type |
|---|---|
| edit | WorkspaceEdit |
| metadata? | WorkspaceEditMetadata |
Convert location to quickfix item.
workspace.getQuickfixItem(loc: Location | LocationLink, text?: string, type?: string, module?: string): Promise<QuickfixItem>| Parameter | Type |
|---|---|
| loc | Location | LocationLink |
| text? | string |
| type? | string |
| module? | string |
Convert locations to quickfix list.
workspace.getQuickfixList(locations: Location[]): Promise<ReadonlyArray<QuickfixItem>>| Parameter | Type |
|---|---|
| locations | Location[] |
Populate locations to UI.
Get content of line by uri and line.
workspace.getLine(uri: string, line: number): Promise<string>| Parameter | Type |
|---|---|
| uri | string |
| line | number |
Get WorkspaceFolder of uri
workspace.getWorkspaceFolder(uri: string | Uri): WorkspaceFolder | undefined| Parameter | Type |
|---|---|
| uri | string | Uri |
Get content from buffer or file by uri.
workspace.readFile(uri: string): Promise<string>| Parameter | Type |
|---|---|
| uri | string |
Get current document and position.
workspace.getCurrentState(): Promise<EditerState>Get format options of uri or current buffer.
workspace.getFormatOptions(uri?: string): Promise<FormattingOptions>| Parameter | Type |
|---|---|
| uri? | string |
Jump to location.
Create a file in vim and disk
workspace.createFile(filepath: string, opts?: CreateFileOptions): Promise<void>| Parameter | Type |
|---|---|
| filepath | string |
| opts? | CreateFileOptions |
Load uri as document, buffer would be invisible if not loaded.
Load the files that not loaded
Rename file in vim and disk
workspace.renameFile(oldPath: string, newPath: string, opts?: RenameFileOptions): Promise<void>| Parameter | Type |
|---|---|
| oldPath | string |
| newPath | string |
| opts? | RenameFileOptions |
Delete file from vim and disk.
workspace.deleteFile(filepath: string, opts?: DeleteFileOptions): Promise<void>| Parameter | Type |
|---|---|
| filepath | string |
| opts? | DeleteFileOptions |
Open resource by uri
workspace.openResource(uri: string): Promise<void>| Parameter | Type |
|---|---|
| uri | string |
Resolve full path of module from yarn or npm global directory.
workspace.resolveModule(name: string): Promise<string>| Parameter | Type |
|---|---|
| name | string |
Run nodejs command
workspace.runCommand(cmd: string, cwd?: string, timeout?: number): Promise<string>| Parameter | Type |
|---|---|
| cmd | string |
| cwd? | string |
| timeout? | number |
Expand filepath with ~ and/or environment placeholders
workspace.expand(filepath: string): string| Parameter | Type |
|---|---|
| filepath | string |
Call a function by use notifications, useful for functions like |input| that could block vim.
workspace.callAsync<T>(method: string, args: any[]): Promise<T>| Parameter | Type |
|---|---|
| method | string |
| args | any[] |
Register TextDocumentContentProvider for custom scheme
workspace.registerTextDocumentContentProvider(scheme: string, provider: TextDocumentContentProvider): Disposable| Parameter | Type |
|---|---|
| scheme | string |
| provider | TextDocumentContentProvider |
Register unique global key-mapping with <Plug>(coc-{key}) as lhs.
'noremap' is always used, Throw error when {key} already exists.
workspace.registerKeymap(modes: MapMode[], key: string, fn: () => ProviderResult<any>, opts?: KeymapOption): Disposable| Parameter | Type | Description |
|---|---|---|
| modes | MapMode[] | Array of map mode short-name. |
| key | string | Unique name, should only use alphabetical characters and '-'. |
| fn | () => ProviderResult<any> | Callback function. |
| opts? | KeymapOption | Optional option. |
Register expr mapping global or local to buffer.
Unlike :map, space in {lhs} is accepted as part of the {lhs}, keycodes are replaced are usual. 'noremap' and map arguments <silent>, <nowait> are always used.
workspace.registerExprKeymap(mode: MapMode, rhs: string, fn: () => ProviderResult<string>, buffer?: number | boolean, cancel?: boolean): Disposable| Parameter | Type | Description |
|---|---|---|
| mode | MapMode | Mode short-name. |
| rhs | string | rhs of key-mapping. |
| fn | () => ProviderResult<string> | callback function. |
| buffer? | number | boolean | Buffer number or current buffer by use |
| cancel? | boolean | Cancel pupop menu before invoke callback, insert mode only, define to true. |
Register a dynamic insert-mode mapping.
The callback runs at the mapping's execution point and returns literal
text and special keys to execute in order. Use option.arglist to pass
current editor state without making nested editor requests. The callback
must not change text, switch windows, or run :normal while the
expression mapping is being evaluated.
Vim cannot guarantee ordering for channel-backed expression results
during batched :normal or macro input.
workspace.registerInsertKeymap(key: string, fn: (...args: any[]) => ProviderResult<InsertKeymapResult>, option?: InsertKeymapOption): Disposable| Parameter | Type | Description |
|---|---|---|
| key | string | lhs of the insert-mode mapping. |
| fn | (...args: any[]) => ProviderResult<InsertKeymapResult> | callback receiving evaluated |
| option? | InsertKeymapOption | Mapping options. |
Register local keymap with callback.
Unlike :map, space in {lhs} is accepted as part of the {lhs}, keycodes are replaced are usual. 'noremap' and map arguments <nowait> are always used.
workspace.registerLocalKeymap(bufnr: number, mode: 'n' | 'i' | 'v' | 's' | 'x', lhs: string, fn: () => ProviderResult<any>, opts?: KeymapOption | boolean): Disposable| Parameter | Type | Description |
|---|---|---|
| bufnr | number | buffer number, use 0 for current buffer. |
| mode | 'n' | 'i' | 'v' | 's' | 'x' | mode short-name. |
| lhs | string | lhs of key-mapping. |
| fn | () => ProviderResult<any> | callback function. |
| opts? | KeymapOption | boolean | Optional option, when it's boolean value, indicate use notification or not. |
Register for buffer sync objects, created sync object should be disposable and provide optional event handlers:
onChange called on onDidChangeTextDocument event.onTextChange called on line change event from vim.onVisible called on WindowVisible event.The document is always attached and not command line buffer.
workspace.registerBufferSync<T extends BufferSyncItem>(create: (doc: Document) => T | undefined): BufferSync<T>| Parameter | Type | Description |
|---|---|---|
| create | (doc: Document) => T | undefined | Called for each attached document and on document create. |
Disposable
Create a FuzzyMatch instance using wasm module.
The FuzzyMatch does the same match algorithm as vim's :h matchfuzzypos()
workspace.createFuzzyMatch(): FuzzyMatchCompute word ranges of opened document in specified range.
workspace.computeWordRanges(uri: string | number, range: Range, token?: CancellationToken): Promise<{ [word: string]: Range[] } | null>| Parameter | Type | Description |
|---|---|---|
| uri | string | number | Uri of resource |
| range | Range | Range of resource |
| token? | CancellationToken |
| null>}
Create a FileSystemWatcher instance, when watchman doesn't exist, the returned FileSystemWatcher can still be used, but not work at all.
workspace.createFileSystemWatcher(globPattern: GlobPattern, ignoreCreate?: boolean, ignoreChange?: boolean, ignoreDelete?: boolean): FileSystemWatcher| Parameter | Type |
|---|---|
| globPattern | GlobPattern |
| ignoreCreate? | boolean |
| ignoreChange? | boolean |
| ignoreDelete? | boolean |
workspace.findFiles(include: GlobPattern, exclude?: GlobPattern | null, maxResults?: number, token?: CancellationToken): Thenable<Uri[]>findFiles('**/*.js', '**/node_modules/**', 10)| Parameter | Type | Description |
|---|---|---|
| include | GlobPattern | A glob pattern that defines the files to search for. The glob pattern will be matched against the file paths of resulting matches relative to their workspace. Use a relative pattern to restrict the search results to a workspace folder. |
| exclude? | GlobPattern | null | A glob pattern that defines files and folders to exclude. The glob pattern
will be matched against the file paths of resulting matches relative to their workspace. When |
| maxResults? | number | An upper-bound for the result. |
| token? | CancellationToken | A token that can be used to signal cancellation to the underlying search engine. |
A thenable that resolves to an array of resource identifiers. Will return no results if no workspace folders are opened.
Create persistence Mru instance.
Create Task instance that runs in (neo)vim, no shell.
Create DB instance at extension root.