Public API
Environmentsrc/environment.js:95
Lumine global for dealing with packages, themes, menus, and the window.
An instance of this class is always available as the lumine global.
Properties33
deserializeTimings:Object
hooks:Object
Shared overlay scrollbar presentation and local geometry.
tools:Object
Public API
ApplicationServicesrc/application-service.js:12
Main-process application services exposed as serializable values.
Application Information8
Return an Electron application path captured during bootstrap.
| Argument | Type | Description |
|---|---|---|
name | String | A supported Electron application-path name. |
Returns
String — The cached path synchronously.
Return the application locale captured during bootstrap.
Returns
String — The cached locale synchronously.
Return the editor resource directory captured during bootstrap.
Returns
String — The absolute resource path synchronously.
Return the full name of this Lumine application.
Returns
String — The application name synchronously.
Return the Lumine application version.
Returns
String — The version synchronously.
Determine whether the current application version satisfies a semantic-version range.
| Argument | Type | Description |
|---|---|---|
range | String | A semantic-version range. |
Returns
Boolean — Whether the current version satisfies the range.
Return the current release channel.
Returns
String — The release channel.
Determine whether this build came from the release pipeline.
Returns
Boolean — Whether this is a released build.
Application Lifecycle2
Open paths in a new or reusable Lumine window.
The call returns immediately after sending the request to the main process.
| Argument | Type | Description |
|---|---|---|
params | Object | Paths and window options to open. |
Restart Lumine with the current launch options.
Returns
Promise<void> — that resolves when restart is scheduled.
System Integration4
Create an owned reporter for work shown in the operating system’s taskbar or Dock. Each reporter contributes independently to this workspace’s main and detached windows; the application badge counts work across workspaces on platforms that support native badges.
Call update({count, progress}) with a non-negative task count and an
optional progress fraction between zero and one. Omit progress, or use
null, for indeterminate work. A zero count clears this reporter. When
several reporters have known progress, the window displays their average
weighted by task count; any indeterminate work makes it indeterminate.
Both update() and dispose() return promises. Dispose the reporter when
its owner unloads. A renderer reload or crash also clears its reports.
After disposal, updates reject; a failed disposal can be retried.
Returns
Object — An owned reporter with update(status) and dispose() methods.
Read an operating-system user default.
| Argument | Type | Description |
|---|---|---|
key | String | The operating-system preference key. |
type | String | One of string, boolean, integer, float, double, url, array, or dictionary. |
Returns
Promise<*> — resolving to a serializable preference value.
Read the operating system’s accent color.
Returns
Promise<String|null> — resolving to a #rrggbb string, or null where the platform has no accent color to report.
Load an operating-system file icon as a data URL.
| Argument | Type | Description |
|---|---|---|
filePath | String | The filesystem path whose native icon is requested. |
optionsoptional, default: {} | Object | Native icon options. |
sizeoptional | String | One of small, normal, or large. |
Returns
Promise<String|null> — resolving to a data-URL String, or null.
Printing1
Render a complete HTML document to a PDF file.
The document is loaded into an offscreen window of its own, so the result holds only what was passed here — never the surrounding editor chrome — and its scripts are not run.
| Argument | Type | Description |
|---|---|---|
html | String | A complete HTML document. Reference assets by data URI: nothing relative to the calling document resolves. |
outputPath | String | Where to write the PDF. |
optionsoptional, default: {} | Object | Electron printToPDF options. printBackground defaults to true. |
Returns
Promise<Object> — resolving to {outcome: 'success', result: outputPath}, or {outcome: 'failure', error} when the document could not be printed.
Protocol Handling2
Determine whether Lumine is the default handler for a protocol.
| Argument | Type | Description |
|---|---|---|
protocol | String | The protocol name without its trailing colon. |
pathoptional | String | The executable path used for protocol registration. |
argsoptional | Array<String> | Arguments supplied to the protocol executable. |
Returns
Promise<Boolean> — resolving to a Boolean.
Register Lumine as the default handler for a protocol.
| Argument | Type | Description |
|---|---|---|
protocol | String | The protocol name without its trailing colon. |
pathoptional | String | The executable path used for protocol registration. |
argsoptional | Array<String> | Arguments supplied to the protocol executable. |
Returns
Promise<Boolean> — resolving to a Boolean.
Extended API
BufferedNodeProcesssrc/buffered-node-process.js:19
Extends BufferedProcess
Like BufferedProcess, but accepts a Node script as the command to run.
Full description
This is necessary on Windows since it doesn’t support shebang #! lines.
Examples#
const {BufferedNodeProcess} = require('lumine')
Methods1
Get a fresh array of runtime arguments for a Node script launched with the
editor’s executable. Place these before the script path, or pass them as
execArgv to child_process.fork. Use these with the editor’s
process.execPath. The array is empty outside Windows Electron, and
requesting it never changes the process environment.
Returns
Array<String> — Runtime arguments for the current editor process.
Construction1
Runs the given Node script by spawning a new child process.
| Argument | Type | Description |
|---|---|---|
options | Object | Process options. |
command | String | Path to the JavaScript script. |
argsoptional | Array<String> | Arguments passed to the script. |
optionsoptional | Object | Options passed to Node’s ChildProcess.spawn. |
stdoutoptional | Function | Receives buffered, complete lines of standard output and any remaining data when the stream closes. |
data | String | Standard-output data. |
stderroptional | Function | Receives buffered, complete lines of standard error and any remaining data when the stream closes. |
data | String | Standard-error data. |
exitoptional | Function | Receives the process exit status. |
code | Number | The exit status. |
Extended API
BufferedProcesssrc/buffered-process.js:25
A wrapper which provides standard error/output line buffering for Node’s ChildProcess.
Full description
Examples#
const {BufferedProcess} = require('lumine')
const command = 'ps'
const args = ['-ef']
const stdout = (output) => console.log(output)
const exit = (code) => console.log(`ps -ef exited with ${code}`)
const process = new BufferedProcess({command, args, stdout, exit})
Construction1
Runs the given command by spawning a new child process.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Process options. |
command | String | The command to execute. |
argsoptional | Array<String> | Arguments passed to the command. |
optionsoptional | Object | Options passed to Node’s ChildProcess.spawn. |
stdoutoptional | Function | Receives buffered, complete lines of standard output and any remaining data when the stream closes. |
data | String | Standard-output data. |
stderroptional | Function | Receives buffered, complete lines of standard error and any remaining data when the stream closes. |
data | String | Standard-error data. |
exitoptional | Function | Receives the process exit status. |
code | Number | The exit status. |
autoStartoptional, default: true | Boolean | Whether to start immediately. |
Event Subscription1
Invoke the given callback when the process raises an error.
Usually this is due to the command not being available or not on the PATH.
You can call handle() on the object passed to your callback to indicate
that you have handled this error.
| Argument | Type | Description |
|---|---|---|
callback | Function | callback |
errorObject | Object | |
error | Object | the error object |
handle | Function | call this to indicate you have handled the error. The error will not be thrown if this function is called. |
Returns
Process Control1
Terminate the process.
Extended API
Clipboardsrc/clipboard.js:39
Represents the clipboard used for copying and pasting in Lumine.
Full description
An instance of this class is always available as the lumine.clipboard global.
This class owns what the clipboard holds, not what a paste does with it. To
intercept a paste before the editor inserts it as text — to handle an image,
say — register a provider with PasteProviderRegistry through
lumine.pasteProviders.
It is also the only supported route to the native clipboard from a package:
Electron exposes its Promise-based clipboard only in the main process, so
every programmatic read and write here crosses the process boundary (see
src/clipboard-bridge.js). Native ClipboardEvents use a synchronous
DataTransfer-backed adapter for the duration of the event.
Examples#
await lumine.clipboard.write('hello')
console.log(await lumine.clipboard.read()) // 'hello'
Reading and Writing Text3
Write the given text to the clipboard.
The metadata associated with the text is available by calling #readWithMetadata.
| Argument | Type | Description |
|---|---|---|
text | String | The String to store. |
metadataoptional | * | The additional info to associate with the text. |
Returns
Promise<void> — that resolves after the system clipboard has been updated.
Read the text from the clipboard.
Returns
Promise<String> — that resolves to the clipboard text as a String.
Read the text from the clipboard and return both the text and the associated metadata.
Metadata copied in another window only flows through paste
ClipboardEvents (see createDataTransferClipboard): Chromium stores
DataTransfer custom formats in a private bundle that Electron’s clipboard
API cannot read back, so there is no native-format fallback here.
textTheStringclipboard text.metadataThe metadata stored by an earlier call to #write.
Returns
Promise<Object> — that resolves to an Object with the following keys:
Native Data2
Write text plus a JSON payload for a custom format to the system clipboard through the async Clipboard API.
Chromium registers web -prefixed custom formats with the operating
system, so any window can read the payload back with #readNativeData.
Custom formats written through a DataTransfer during a copy event are only
readable inside paste ClipboardEvents, and renderer-initiated
execCommand("paste") never fires one, so this is the only way to
round-trip a custom format without a native paste keystroke.
| Argument | Type | Description |
|---|---|---|
text | String | The plain-text String to store alongside the payload. |
format | String | The MIME-style format String, without the web prefix. |
data | Object | The JSON-serializable payload. |
Returns
Promise<Boolean> — that resolves to true when the payload was written, or false when only the plain text could be written.
Read a JSON payload written by #writeNativeData in this or any other window.
| Argument | Type | Description |
|---|---|---|
format | String | The MIME-style format String, without the web prefix. |
Returns
Promise<Object|null> — that resolves to the parsed payload Object, or null when the clipboard holds no valid payload for the format.
Find Pasteboard2
Write the given text to the macOS find pasteboard.
| Argument | Type | Description |
|---|---|---|
text | String | The text to store. |
Returns
Promise<void> — that resolves after the find pasteboard has been updated.
Read the text from the macOS find pasteboard.
Returns
Promise<String> — that resolves to the find pasteboard text as a String.
Images2
Read the image on the clipboard.
The image crosses the process boundary as PNG bytes, so its scale factor does not survive the trip.
Returns
Promise<NativeImage> — that resolves to a NativeImage, empty when the clipboard holds no image.
Write an image to the clipboard, replacing whatever it held.
| Argument | Type | Description |
|---|---|---|
image | NativeImage|Buffer|Uint8Array | A NativeImage, or the PNG bytes of one as a Buffer. |
Returns
Promise<void> — that resolves after the image has been written.
Primary Selection2
Read the text from the Linux primary selection.
Returns
Promise<String> — that resolves to a String, always empty on platforms without a primary selection.
Write the given text to the Linux primary selection.
| Argument | Type | Description |
|---|---|---|
text | String | The String to store. |
Returns
Promise<void> — that resolves after the primary selection has been updated.
Essential API
Colorsrc/color.js:11
A simple color class returned from Config#get when the value at the key path is of type ‘color’.
Methods3
Return the color as a hexadecimal RGB string.
Returns
String — in the form '#abcdef'.
Return the color as an RGBA CSS string.
Returns
String — in the form 'rgba(25, 50, 75, .9)'.
Public API
CommandRegistrysrc/command-registry.js:54
Associates listener functions with commands in a
context-sensitive way using CSS selectors. You can access a global instance of
this class via lumine.commands, and commands registered there will be
presented in the command palette.
Full description
The global command registry facilitates a style of event handling known as
event delegation that was popularized by jQuery. Lumine commands are expressed
as custom DOM events that can be invoked on the currently focused element via
a key binding or manually via the command palette. Rather than binding
listeners for command events directly to DOM nodes, you instead register
command event listeners globally on lumine.commands and constrain them to
specific kinds of elements with CSS selectors.
Command names must follow the namespace:action pattern, where namespace
will typically be the name of your package, and action describes the
behavior of your command. If either part consists of multiple words, these
must be separated by hyphens. E.g. awesome-package:turn-it-up-to-eleven.
All words should be lowercased.
As the event bubbles upward through the DOM, all registered event listeners
with matching selectors are invoked in order of specificity. In the event of a
specificity tie, the most recently registered listener is invoked first. This
mirrors the “cascade” semantics of CSS. Event listeners are invoked in the
context of the current DOM node, meaning this always points at
event.currentTarget. As is normally the case with DOM events,
stopPropagation and stopImmediatePropagation can be used to terminate the
bubbling process and prevent invocation of additional listeners.
Example#
Here is a command that inserts the current date in an editor:
lumine.commands.add('lumine-text-editor', {
'user:insert-date'(event) {
const editor = this.getModel()
editor.insertText(new Date().toLocaleString())
}
})
Registering Commands1
Add one or more command listeners associated with a selector.
Registering one command
The function (listener itself if it is a function, or the didDispatch
method if listener is an object) will be called with this referencing
the matching DOM node and the following argument:
Additionally, listener may have additional properties which are returned
to those who query using lumine.commands.findCommands, as well as several
meaningful metadata properties:
Registering multiple commands
Pass an object mapping command names such as user:insert-date to listener
functions as commandName.
| Argument | Type | Description |
|---|---|---|
target | String|Element | A CSS selector or DOM element. Selectors associate the command with all matching elements; the , combinator is not supported. |
commandName | String|Object | A command name such as user:insert-date, or a map of command names to listeners. |
listeneroptional | Function|Object | A function, or an object whose didDispatch property handles the command. |
throwOnInvalidSelectoroptional, default: true | Boolean | Throw when target is an invalid selector. |
event | Event | The dispatched DOM event. Call stopPropagation() or stopImmediatePropagation() to stop bubbling. |
displayNameoptional | String | Overrides the generated display name. |
descriptionoptional | String | Detailed command information. |
hiddenInCommandPaletteoptional | Boolean | Hide the command from the bundled command palette by default. |
modaloptional | Boolean|String | Declares that the command opens a modal, optionally naming its breadcrumb label. |
isAvailableoptional | Function | A synchronous, side-effect-free predicate returning a Boolean. It receives {target, currentTarget, detail, context} with this set to the matching node. It runs only after the registration scope matches, for availability queries and immediately before invoking this handler. Omit it when the scope alone is sufficient. |
checkedoptional | Function|Boolean|String | Persistent choice state, or a synchronous, side-effect-free function receiving the same context as isAvailable. Return a Boolean, or mixed for a checkbox. Menus and command presentations share this state. |
typeoptional, default: checkbox | String | Use radio for an exclusive choice or checkbox for an independent choice when checked is supplied. |
Returns
Disposable — on which .dispose() can be called to remove the added command handler(s).
Accessing Commands5
Determine whether an enabled handler matches a target or its ancestors.
Registration scope is checked before its optional isAvailable predicate.
Handlers are never invoked. This follows the same route as command dispatch,
including detached targets and the target’s own window.
| Argument | Type | Description |
|---|---|---|
target | Node|Window | The target from which the command would be dispatched. |
commandName | String | The command to look up. |
detailoptional | * | The arguments that would be supplied to dispatch. |
Returns
Boolean — Whether dispatch can reach an enabled handler.
Find all registered commands matching a query.
nameThe name of the command. For example,user:insert-date.displayNameThe display name of the command. For example,User: Insert Date. Additional metadata may also be present in the returned descriptor:descriptionaStringdescribing the function of the command in more detail than the titletagsanArrayofStringsthat describe keywords related to the command Any additional nonstandard metadata provided when the command wasadded may also be present in the returned descriptor.
| Argument | Type | Description |
|---|---|---|
params | Object | Query parameters. |
target | Element | The hypothetical command target. |
Returns
Array<Object> — Command descriptors containing the documented keys.
Read persistent choice state from the nearest scoped command registration. This never dispatches the command or loads its implementation. A matching handler without state shadows an ancestor’s state as it does its label.
| Argument | Type | Description |
|---|---|---|
commandName | String | Command whose state should be read. |
optionsoptional, default: {} | Object | |
target | Node|Window | Dispatch target. |
detailoptional | * | Arguments that would be passed to the command. |
Returns
Object|null — Frozen {type, checked} or null for an ordinary command.
Return the display metadata and effective keybindings for one command at a target. This is the shared presentation used by command pickers and modal action lists.
| Argument | Type | Description |
|---|---|---|
commandName | String | Command to describe. |
options | Object | |
targetoptional | Element | Element from which the command would be dispatched. |
bindingTargetoptional, default: options.target | Element | Element where displayed keybindings resolve. |
detailoptional | * | Arguments used to evaluate the command’s availability. |
Returns
Object|null — The scoped command descriptor with keystrokes and Boolean enabled, or null when no registration matches the scope.
Return presentation metadata for every effective command at a target. Metadata and keybindings are each scanned once; availability uses the indexed registrations of each command. Disabled commands remain visible.
| Argument | Type | Description |
|---|---|---|
options | Object | |
targetoptional | Element | Element from which commands would be dispatched. |
bindingTargetoptional, default: options.target | Element | Element where displayed keybindings resolve. |
Returns
Array<Object> — One frozen descriptor per scoped command, each with Boolean enabled and frozen keystrokes.
Dispatching Commands1
Simulate the dispatch of a command on a DOM node.
This is useful for passing arguments to a command, as keymaps currently do not support arguments; for example, add a new command with no arguments that dispatches another command with arguments, and map the new command to a key binding.
This can be useful for testing when you want to simulate the invocation of a command on a detached DOM node. Otherwise, the DOM node in question needs to be attached to the document so the event bubbles up to the root node to be processed.
| Argument | Type | Description |
|---|---|---|
target | Node | The DOM node at which to start bubbling the command event. |
commandName | String | indicating the name of the command to dispatch. |
detailoptional | * | Any value that will be assigned to the event’s .detail property. Pass an object with multiple properties if you need multiple command arguments. |
Returns
Promise<Array<*>>|null — Resolves to the listener results after all enabled matching handlers finish, or null when none is available. Rejected handler promises reject the returned promise; synchronous handler errors are thrown.
Event Subscription4
Invoke the given callback before dispatching a command event.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called before dispatching each command |
event | CustomEvent | The Event that will be dispatched |
Returns
Disposable — Removes the event subscription.
Invoke the given callback after dispatching a command event.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called after dispatching each command |
event | CustomEvent | The Event that was dispatched |
Returns
Disposable — Removes the event subscription.
Invoke the callback when command registrations are added, removed, cleared
or restored, or their availability is invalidated. Unlike dispatch subscriptions, this subscription survives
clear() and is disposed when the registry is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called after registrations change. |
changeoptional | Object | A local availability change; absent for a global change. |
targetoptional | Node | Only command targets within this subtree are affected. |
Returns
Disposable — Removes the event subscription.
Notify command surfaces that state used by isAvailable or checked changed.
Predicates are evaluated afresh on every query; this asks live presentations
such as the native application menu to refresh without a focus change.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Optional scope of a local state change. |
targetoptional | Node | The changed command subtree. Omit for domain-wide changes. |
Returns
void
Essential API
CompositeDisposablelib/composite-disposable.js:31
An object that aggregates multiple Disposable instances into a single disposable, so they can all be disposed as a group.
Full description
These are very useful when subscribing to multiple events.
Examples#
const { CompositeDisposable } = require("lumine");
class Something {
constructor() {
this.disposables = new CompositeDisposable();
const editor = lumine.workspace.getActiveTextEditor();
this.disposables.add(editor.onDidChange(() => {}));
this.disposables.add(editor.onDidChangePath(() => {}));
}
destroy() {
this.disposables.dispose();
}
}
Construction and Destruction2
Construct an instance, optionally with one or more disposables.
| Argument | Type | Description |
|---|---|---|
...disposables | ...Disposable | Disposables to add to the instance. |
Dispose all disposables added to this composite disposable.
Every disposable is attempted before errors are reported. A single failure
is rethrown unchanged; multiple failures produce an AggregateError whose
errors follow disposal order and whose cause is the first failure.
If this object has already been disposed, this method has no effect.
Managing Disposables4
Add disposables to be disposed when the composite is disposed.
If this object has already been disposed, this method has no effect.
| Argument | Type | Description |
|---|---|---|
...disposables | ...Disposable | Disposable instances or any objects with .dispose() methods. |
Remove a previously added disposable.
| Argument | Type | Description |
|---|---|---|
disposable | Disposable | A Disposable instance or any object with a .dispose() method. |
Alias for CompositeDisposable#remove.
| Argument | Type | Description |
|---|---|---|
disposable | Disposable | A Disposable instance or any object with a .dispose() method. |
Clear all disposables. They will not be disposed by the next call to CompositeDisposable#dispose.
Essential API
Configsrc/config.js:435
Used to access all of Lumine’s configuration details.
Full description
An instance of this class is always available as the lumine.config global.
Getting and setting config settings.#
// Note that with no value set, ::get returns the setting's default value.
lumine.config.get('my-package.myKey') // -> 'defaultValue'
lumine.config.set('my-package.myKey', 'value')
lumine.config.get('my-package.myKey') // -> 'value'
// Change only this window until it reloads, without saving to config.json.
lumine.config.set('my-package.myKey', 'temporary', { local: true })
lumine.config.unset('my-package.myKey', { local: true })
You may want to watch for changes. Use #observe to catch changes to the setting.
lumine.config.set('my-package.myKey', 'value')
lumine.config.observe('my-package.myKey', (newValue) => {
// `observe` calls immediately and every time the value is changed
console.log('My configuration changed:', newValue)
})
If you want a notification only when the value changes, use #onDidChange.
lumine.config.onDidChange('my-package.myKey', ({ newValue, oldValue }) => {
console.log('My configuration changed:', newValue, oldValue)
})
Value Coercion#
Config settings each have a type specified by way of a
schema. For example we might want an integer setting that only
allows integers greater than 0:
// When no value has been set, `::get` returns the setting's default value
lumine.config.get('my-package.anInt') // -> 12
// The string will be coerced to the integer 123
lumine.config.set('my-package.anInt', '123')
lumine.config.get('my-package.anInt') // -> 123
// The string will be coerced to an integer, but it must be greater than 0, so is set to 1
lumine.config.set('my-package.anInt', '-20')
lumine.config.get('my-package.anInt') // -> 1
Defining settings for your package#
Declare a configSchema in your package’s package.json:
{
"name": "my-package",
"configSchema": {
"someInt": {
"title": "Some Int",
"description": "How many of the thing to do.",
"type": "integer",
"minimum": 1,
"default": 23
}
}
}
The schema is read before the package activates, so its settings appear in
the settings view and its defaults apply whether or not the package has been
loaded yet. Export a config object from the package’s main module only when
the schema cannot be written down ahead of time and has to be built at
runtime.
See the package tutorial for more info.
Config Schemas#
We use json schema which allows you to define your value’s
default, the type it should be, etc. Every example below is the value of the
configSchema key. A simple one, providing an enableThing and a
thingVolume:
{
"enableThing": {
"type": "boolean",
"default": false
},
"thingVolume": {
"type": "integer",
"minimum": 1,
"maximum": 11,
"default": 5
}
}
The type keyword allows for type coercion and validation. If a thingVolume is
set to a string '10', it will be coerced into an integer.
lumine.config.set('my-package.thingVolume', '10')
lumine.config.get('my-package.thingVolume') // -> 10
// It respects the min / max
lumine.config.set('my-package.thingVolume', '400')
lumine.config.get('my-package.thingVolume') // -> 11
// If it cannot be coerced, the value will not be set
lumine.config.set('my-package.thingVolume', 'cats')
lumine.config.get('my-package.thingVolume') // -> 11
Supported Types#
The type keyword can be a string with any one of the following. You can also
chain them by specifying multiple in an array. For example
{
"someSetting": {
"type": ["boolean", "integer"],
"default": 5
}
}
lumine.config.set('my-package.someSetting', 'true')
lumine.config.get('my-package.someSetting') // -> true
lumine.config.set('my-package.someSetting', '12')
lumine.config.get('my-package.someSetting') // -> 12
string#
Values must be a string.
{
"someSetting": {
"type": "string",
"default": "hello"
}
}
integer#
Values will be coerced into integer. Supports the (optional) minimum and
maximum keys.
{
"someSetting": {
"type": "integer",
"minimum": 1,
"maximum": 11,
"default": 5
}
}
number#
Values will be coerced into a number, including real numbers. Supports the
(optional) minimum and maximum keys.
{
"someSetting": {
"type": "number",
"minimum": 1.5,
"maximum": 11.5,
"default": 5.3
}
}
boolean#
Values will be coerced into a Boolean. 'true' and 'false' will be coerced into
a boolean. Numbers, arrays, objects, and anything else will not be coerced.
{
"someSetting": {
"type": "boolean",
"default": false
}
}
array#
Value must be an Array. The types of the values can be specified by a
subschema in the items key. An item that does not conform to that subschema
is dropped rather than rejecting the whole array. Supports the (optional)
minItems and maxItems keys, which bound the length of the array that
survives; a value outside those bounds is rejected and the setting keeps its
previous value.
{
"someSetting": {
"type": "array",
"items": {
"type": "integer",
"minimum": 1.5,
"maximum": 11.5
},
"minItems": 1,
"maxItems": 3,
"default": [1, 2, 3]
}
}
color#
Values will be coerced into a Color with red, green, blue, and alpha
properties that all have numeric values. red, green, blue will be in
the range 0 to 255 and value will be in the range 0 to 1. Values can be any
valid CSS color format such as #abc, #abcdef, white,
rgb(50, 100, 150), and rgba(25, 75, 125, .75).
{
"someSetting": {
"type": "color",
"default": "white"
}
}
object / Grouping other types#
A config setting with the type object allows grouping a set of config
settings. The group will be visually separated and has its own group headline.
The sub options must be listed under a properties key.
{
"someSetting": {
"type": "object",
"properties": {
"myChildIntOption": {
"type": "integer",
"minimum": 1.5,
"maximum": 11.5
}
}
}
}
Other Supported Keys#
enum#
All types support an enum key, which lets you specify all the values the
setting can take. enum may be an array of allowed values (of the specified
type), or an array of objects with value and description properties, where
the value is an allowed value, and the description is a descriptive string
used in the settings view.
In this example, the setting must be one of the 4 integers:
{
"someSetting": {
"type": "integer",
"enum": [2, 4, 6, 8],
"default": 4
}
}
In this example, the setting must be either ‘foo’ or ‘bar’, which are presented using the provided descriptions in the settings pane:
{
"someSetting": {
"type": "string",
"enum": [
{ "value": "foo", "description": "Foo mode. You want this." },
{ "value": "bar", "description": "Bar mode. Nobody wants that!" }
],
"default": "foo"
}
}
If you only have a few elements, you can display your enum as a list of
radio buttons in the settings view rather than a select list. To do so,
specify radio: true as a sibling property to the enum array.
{
"someSetting": {
"type": "string",
"enum": [
{ "value": "foo", "description": "Foo mode. You want this." },
{ "value": "bar", "description": "Bar mode. Nobody wants that!" }
],
"radio": true,
"default": "foo"
}
}
Usage:
lumine.config.set('my-package.someSetting', '2')
lumine.config.get('my-package.someSetting') // -> 2
// a value outside the enum is rejected, and the setting keeps what it had
lumine.config.set('my-package.someSetting', '3')
lumine.config.get('my-package.someSetting') // -> 2
// a value inside it is coerced to the declared type and set
lumine.config.set('my-package.someSetting', '4')
lumine.config.get('my-package.someSetting') // -> 4
title and description#
The settings view will use the title and description keys to display your
config setting in a readable way. By default the settings view humanizes your
config key, so someSetting becomes Some Setting. In some cases, this is
confusing for users, and a more descriptive title is useful.
Descriptions will be displayed below the title in the settings view.
For a group of config settings the humanized key or the title and the description are used for the group headline.
{
"someSetting": {
"title": "Setting Magnitude",
"description": "This will affect the blah and the other blah",
"type": "integer",
"default": 4
}
}
Note: You should strive to be so clear in your naming of the setting that you do not need to specify a title or description!
Descriptions allow a subset of Markdown formatting. Specifically, you may use the following in configuration setting descriptions:
- bold -
**bold** - italics -
*italics* - links -
[links](https://lumine-code.github.io) code spans-`code spans`- line breaks -
line breaks<br/> strikethrough-~~strikethrough~~
order#
The settings view displays your settings in the order the schema declares them, so arranging the schema is all this normally takes.
An explicit order key still takes precedence where one is present, but
prefer not to use it: a setting without order sorts after every setting
that has one, so adding order to part of a schema reorders the rest of it
too.
Manipulating values outside your configuration schema#
It is possible to manipulate(get, set, observe etc) values that do not
appear in your configuration schema. For example, if the config schema of the
package ‘some-package’ is
{
"someSetting": {
"type": "boolean",
"default": false
}
}
You can still do the following
const otherSetting = lumine.config.get('some-package.otherSetting')
lumine.config.set('some-package.stillAnotherSetting', otherSetting * 5)
In other words, if a function asks for a key-path, that path doesn’t have to
be described in the config schema for the package or any package. However, as
highlighted in the best practices section, you are advised against doing the
above.
Best practices#
- Don’t depend on (or write to) configuration keys outside of your keypath.
Config Subscription2
Add a listener for changes to a given key path. This is different than #onDidChange in that it will immediately call your callback with the current value of the config entry.
Examples
You might want to be notified when the theme mode changes. We’ll watch
theme.mode for changes
lumine.config.observe('theme.mode', (value) => {
// do stuff with value
})
| Argument | Type | Description |
|---|---|---|
keyPath | String | The configuration key to observe. |
optionsoptional | Object | Observation options. |
scopeoptional | ScopeDescriptor | A path from the root of the syntax tree to a token. Get one by calling editor.getLastCursor().getScopeDescriptor(). See #get and the scopes docs for examples. |
callback | Function | Called when the value changes. |
value | * | The new value. |
Returns
Disposable — A disposable on which .dispose() can be called to unsubscribe.
Add a listener for changes to a given key path. If keyPath is
not specified, your callback will be called on changes to any key.
| Argument | Type | Description |
|---|---|---|
keyPathoptional | String | The key to observe. Required when options.scope is specified. |
optionsoptional | Object | Observation options. |
scopeoptional | ScopeDescriptor | A path from the root of the syntax tree to a token. Get one by calling editor.getLastCursor().getScopeDescriptor(). See #get and the scopes docs for examples. |
callback | Function | Called when the value changes. |
event | Object | The change event. |
newValue | * | The new value. |
oldValue | * | The previous value. |
Returns
Disposable — A disposable on which .dispose() can be called to unsubscribe.
Managing Settings8
Retrieves the setting for the given key.
Examples
You might want to know what theme mode is enabled, so check theme.mode
lumine.config.get('theme.mode')
With scope descriptors you can get settings within a specific editor
scope. For example, you might want to know editor.tabLength for ruby
files.
lumine.config.get('editor.tabLength', { scope: ['source.ruby'] }) // => 2
This setting in ruby files might be different than the global tabLength setting
lumine.config.get('editor.tabLength') // => 4
lumine.config.get('editor.tabLength', { scope: ['source.ruby'] }) // => 2
You can get the language scope descriptor via TextEditor#getRootScopeDescriptor. This will get the setting specifically for the editor’s language.
lumine.config.get('editor.tabLength', { scope: editor.getRootScopeDescriptor() }) // => 2
Additionally, you can get the setting at the specific cursor position.
const scopeDescriptor = editor.getLastCursor().getScopeDescriptor()
lumine.config.get('editor.tabLength', { scope: scopeDescriptor }) // => 2
| Argument | Type | Description |
|---|---|---|
keyPath | String | The key to retrieve. |
optionsoptional | Object | Lookup options. |
sourcesoptional | Array<String> | If provided, use only values associated with these sources during #set. |
excludeSourcesoptional | Array<String> | If provided, exclude values associated with these sources during #set. |
scopeoptional | ScopeDescriptor | A path from the root of the syntax tree to a token. Get one by calling editor.getLastCursor().getScopeDescriptor(). See the scopes docs for more information. |
Returns
* — The resolved value, including this window’s local user overrides, in the type specified by the configuration schema.
Get all of the values for the given key-path, along with their associated scope selector.
| Argument | Type | Description |
|---|---|---|
keyPath | String | The String name of the key to retrieve |
optionsoptional | Object | see the options argument to #get |
scopeoptional | ScopeDescriptor|Array<String> | The scope with which the values are associated. |
Returns
Array<Object> — of objects containing a scopeSelector string and its corresponding value, ordered from the most specific matching selector to the global * value.
Sets the value for a configuration setting.
This value is stored in Lumine’s configuration file unless local is true.
Local values replace user values in this renderer until it reloads. Project
and scope precedence remains unchanged, and synchronized file changes do
not remove local values. An ordinary write removes the local override at
the same selector and key path before updating the user value.
Examples
You might want to change the themes programmatically:
lumine.config.set('theme.dark', ['one-night-ui', 'one-night-syntax'])
You can also set scoped settings. For example, you might want change the
editor.tabLength only for ruby files.
lumine.config.get('editor.tabLength') // => 4
lumine.config.get('editor.tabLength', { scope: ['source.ruby'] }) // => 4
lumine.config.get('editor.tabLength', { scope: ['source.js'] }) // => 4
// Set ruby to 2
lumine.config.set('editor.tabLength', 2, { scopeSelector: '.source.ruby' }) // => true
// Notice it's only set to 2 in the case of ruby
lumine.config.get('editor.tabLength') // => 4
lumine.config.get('editor.tabLength', { scope: ['source.ruby'] }) // => 2
lumine.config.get('editor.tabLength', { scope: ['source.js'] }) // => 4
| Argument | Type | Description |
|---|---|---|
keyPath | String | The configuration key. |
value | * | The setting value. Passing undefined reverts it to the default value, or removes the override when local is true. |
optionsoptional | Object | Write options. |
localoptional, default: false | Boolean | Keep the value in this window only. |
scopeSelectoroptional | String | A scope such as .source.ruby. See the scopes docs for more information. |
sourceoptional | String | The associated source file. Defaults to the user’s configuration file. |
Returns
Boolean — true if the value was set; false if it could not be coerced to the type specified by the setting’s schema or the schema declares allowLocal: false for a requested local write.
Restore the setting at keyPath to its default value. With local: true,
remove only the selected local override and inherit the current user value.
Get an Array of all of the source Strings with which
settings have been added via #set.
Returns
Array<String>
Inspect the stored layers for a key at an exact selector. Complex selectors describe several possible scope chains, so only their exact entries are reported; simple chains also receive inherited/effective values.
The selected target is the user file by default, or this window when
local is true. overrideValue and hasOverride describe that target’s
exact declaration. inheritedValue removes that declaration while retaining
normal project precedence. editableValue and editableInheritedValue
exclude project values, and exclude all local values for the user-file
target. localValue and hasLocalOverride describe the exact local
declaration independently of the selected target. effectiveValue always
describes actual runtime resolution, including projects and locals; it is
undefined for a complex selector whose match cannot be inferred.
| Argument | Type | Description |
|---|---|---|
keyPath | String | The configuration key to inspect. |
optionsoptional, default: {} | Object | Storage target options. |
localoptional, default: false | Boolean | Inspect this window’s declaration. |
scopeSelectoroptional | String | An exact selector; omitted or * selects the base declaration. |
sourceoptional | String | The stored source, defaulting to the user file. Local inspection only accepts the user source. |
Returns
Object — Stored and resolved values: overrideValue, hasOverride, inheritedValue, editableValue, editableInheritedValue, localValue, hasLocalOverride, effectiveValue, baseValue, valuesBySource, projectValue, variableByMatch, keyPath, scopeSelector, and schema. allowLocal is false when the key or a parent schema forbids local writes.
Retrieve the schema for a specific key path. The schema will tell you what type the keyPath expects, and other metadata about the config option.
| Argument | Type | Description |
|---|---|---|
keyPath | String | The String name of the key. |
Returns
Object|null — A schema such as {type: 'integer', default: 23, minimum: 1}, or null when the key path has no accessible schema.
Suppress calls to handler functions registered with #onDidChange
and #observe for the duration of callback. After callback executes,
handlers will be called once if the value for their key-path has changed.
| Argument | Type | Description |
|---|---|---|
callback | Function | to execute while suppressing calls to handlers. |
Returns
* — The value returned by callback.
Extended API
Cursorsrc/cursor.js:16
The Cursor class represents the little blinking line identifying
where text can be inserted.
Cursors belong to TextEditors and have some metadata attached in the form of a DisplayMarker.
Event Subscription2
Calls your callback when the cursor has been moved.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
oldBufferPosition | Point | |
oldScreenPosition | Point | |
newBufferPosition | Point | |
newScreenPosition | Point | |
textChanged | Boolean | |
origin | String | edit, undo, redo, reload, or mixed; identifies history replay and buffer reloads independently of textChanged. |
cursor | Cursor | that triggered the event |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when the cursor is destroyed
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Managing Cursor Position11
Moves a cursor to a given screen position.
| Argument | Type | Description |
|---|---|---|
screenPosition | Point|Array<Number>|Object | of two numbers: the screen row, and the screen column. |
optionsoptional, default: {} | Object | with the following keys: |
autoscrolloptional | Boolean | A Boolean which, if true, scrolls the TextEditor to wherever the cursor moves to. |
modeoptional | String|Number|Array<Number> | The scroll mode when autoscrolling. See TextEditor#scrollToScreenRange. |
Moves a cursor to a given buffer position.
| Argument | Type | Description |
|---|---|---|
bufferPosition | Point|Array<Number>|Object | of two numbers: the buffer row, and the buffer column. |
optionsoptional, default: {} | Object | with the following keys: |
autoscrolloptional | Boolean | indicating whether to autoscroll to the new position. Defaults to true if this is the most recently added cursor, false otherwise. |
modeoptional | String|Number|Array<Number> | The scroll mode when autoscrolling. See TextEditor#scrollToScreenRange. |
Get the cursor position in buffer coordinates.
Returns
Point — The current buffer position.
Get the cursor’s zero-indexed screen row.
Returns
Number — cursor’s current screen row.
Get the cursor’s zero-indexed screen column.
Returns
Number — cursor’s current screen column.
Retrieves the cursor’s current buffer row.
Returns
Number — The zero-indexed buffer row.
Get the cursor’s zero-indexed buffer column.
Returns
Number — cursor’s current buffer column.
Get the text of the cursor’s buffer row, excluding its line ending.
Returns
String — The text of the cursor’s current buffer row, excluding its line ending.
Determine whether the cursor is at the beginning of its buffer row.
Returns
Boolean — whether the cursor is at the start of a line.
Determine whether the cursor is at the end of its buffer row.
Returns
Boolean — whether the cursor is on the line return character.
Cursor Position Details9
Get the display marker tracking this cursor.
Returns
DisplayMarker — underlying DisplayMarker for the cursor. Useful with overlay Decorations.
Identifies if the cursor is surrounded by whitespace.
Check the characters directly before and after the cursor, clipped to the current line. At line boundaries, only existing characters are checked.
Returns
Boolean
Determine whether the cursor separates a word character from a non-word character.
This method returns false if the character before or after the cursor is whitespace.
Returns
Boolean — Whether the cursor is between a word and non-word character. Non-word characters come from the editor.nonWordCharacters setting.
Determine whether the configured word pattern matches at the cursor.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | |
wordRegexoptional | RegExp | A RegExp indicating what constitutes a “word” (default: #wordRegExp). |
Returns
Boolean — whether this cursor is between a word’s start and end.
Get the indentation level corresponding to the cursor’s current column.
Returns
Number — The cursor column divided by tab length for soft tabs, or its buffer column for hard tabs.
Retrieves the scope descriptor for the cursor’s current position.
Returns
Retrieves the syntax tree scope descriptor for the cursor’s current position. Worker syntax resolves asynchronously.
Returns
ScopeDescriptor|Promise<ScopeDescriptor>
Determine whether non-whitespace characters precede the cursor on its buffer row.
Returns
Boolean — true if this cursor has non-whitespace characters before its current position.
Identifies if this cursor is the last in the TextEditor.
“Last” is defined as the most recently added cursor.
Returns
Boolean
Moving the Cursor21
Moves the cursor up one screen row.
| Argument | Type | Description |
|---|---|---|
rowCountoptional, default: 1 | Number | number of rows to move (default: 1) |
optionsoptional, default: {} | Object | Movement options. |
moveToEndOfSelectionoptional | Boolean | Move to the start of an existing selection. |
Moves the cursor down one screen row.
| Argument | Type | Description |
|---|---|---|
rowCountoptional, default: 1 | Number | number of rows to move (default: 1) |
optionsoptional, default: {} | Object | Movement options. |
moveToEndOfSelectionoptional | Boolean | Move to the end of an existing selection. |
Moves the cursor left one screen column.
| Argument | Type | Description |
|---|---|---|
columnCountoptional, default: 1 | Number | number of columns to move (default: 1) |
optionsoptional, default: {} | Object | Movement options. |
moveToEndOfSelectionoptional | Boolean | Move to the start of an existing selection. |
Moves the cursor right one screen column.
| Argument | Type | Description |
|---|---|---|
columnCountoptional, default: 1 | Number | number of columns to move (default: 1) |
optionsoptional, default: {} | Object | Movement options. |
moveToEndOfSelectionoptional | Boolean | Move to the end of an existing selection. |
Moves the cursor to the top of the buffer.
Moves the cursor to the bottom of the buffer.
Moves the cursor to the beginning of the line.
Moves the cursor to the beginning of the buffer line.
Moves the cursor to the beginning of the first character in the line.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | Cursor position options, including autoscroll and mode. |
Moves the cursor to the end of the line.
Moves the cursor to the end of the buffer line.
Moves the cursor to the beginning of the word.
Moves the cursor to the end of the word.
Moves the cursor to the beginning of the next word.
Moves the cursor to the previous word boundary.
Moves the cursor to the next word boundary.
Moves the cursor to the previous subword boundary.
Moves the cursor to the next subword boundary.
Moves the cursor to the beginning of the buffer line, skipping all whitespace.
Moves the cursor to the beginning of the next paragraph
Moves the cursor to the beginning of the previous paragraph
Local Positions and Ranges9
Get the preceding word boundary in buffer coordinates.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | with the following keys: |
wordRegexoptional | RegExp | A RegExp indicating what constitutes a “word” (default: #wordRegExp) |
Returns
Point — buffer position of previous word boundary. It might be on the current word, or the previous word.
Get the next word boundary in buffer coordinates.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | with the following keys: |
wordRegexoptional | RegExp | A RegExp indicating what constitutes a “word” (default: #wordRegExp) |
Returns
Point — buffer position of the next word boundary. It may belong to the current word or a following word.
Retrieves the buffer position of where the current word starts.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | An Object with the following keys: |
wordRegexoptional | RegExp | A RegExp indicating what constitutes a “word” (default: #wordRegExp). |
includeNonWordCharactersoptional | Boolean | A Boolean indicating whether to include non-word characters in the default word regex. Has no effect if wordRegex is set. |
allowPreviousoptional | Boolean | A Boolean indicating whether the beginning of the previous word can be returned. |
Returns
Retrieves the buffer position of where the current word ends.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | with the following keys: |
wordRegexoptional | RegExp | A RegExp indicating what constitutes a “word” (default: #wordRegExp) |
includeNonWordCharactersoptional | Boolean | A Boolean indicating whether to include non-word characters in the default word regex. Has no effect if wordRegex is set. |
allowNextoptional, default: true | Boolean | Allow searching following rows when the cursor is not inside a word. |
Returns
Retrieves the buffer position of where the next word starts.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
wordRegexoptional | RegExp | A RegExp indicating what constitutes a “word” (default: #wordRegExp). |
Returns
Get the buffer range occupied by the word under the cursor.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
wordRegexoptional | RegExp | A RegExp indicating what constitutes a “word” (default: #wordRegExp). |
Returns
Range — buffer Range occupied by the word located under the cursor.
Get the buffer range occupied by the cursor’s current line.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | |
includeNewlineoptional | Boolean | A Boolean which controls whether the Range should include the newline. |
Returns
Range — buffer Range for the current line.
Retrieves the range for the current paragraph.
A paragraph is defined as a block of text surrounded by empty lines or comments.
Returns
Array<Number>|undefined|Promise<Array<Number>|undefined> — Inclusive paragraph row bounds, or undefined on a blank row. Worker syntax resolves asynchronously.
Get the part of the current word preceding the cursor.
Returns
String — characters preceding the cursor in the current word.
Comparison1
Compare this cursor’s buffer position to another cursor’s buffer position.
See Point#compare for more details.
| Argument | Type | Description |
|---|---|---|
otherCursor | Cursor | to compare against |
Returns
Number — -1, 0, or 1 according to the ordering of the buffer positions.
Selections1
Deselects the current selection.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | Options for this operation. |
autoscrolloptional | Boolean | Scroll by default only for the most recently added selection. |
modeoptional | String|Number|Array<Number> | Scroll mode; see TextEditor#scrollToScreenRange. |
Word Matching2
Get the RegExp used by the cursor to determine what a “word” is.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | with the following keys: |
includeNonWordCharactersoptional | Boolean | A Boolean indicating whether to include non-word characters in the regex. (default: true) |
Returns
RegExp
Get the RegExp used by the cursor to determine what a “subword” is.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | with the following keys: |
backwardsoptional | Boolean | A Boolean indicating whether to look forwards or backwards for the next subword. (default: false) |
Returns
RegExp
Essential API
Decorationsrc/decoration.js:47
Represents a decoration that follows a DisplayMarker. A decoration is basically a visual representation of a marker. It allows you to add CSS classes to line numbers in the gutter, lines, and add selection-line regions around marked ranges of text.
Full description
Decoration objects are not meant to be created directly, but created with TextEditor#decorateMarker. eg.
const range = editor.getSelectedBufferRange() // any range you like
const marker = editor.markBufferRange(range)
const decoration = editor.decorateMarker(marker, { type: 'line', class: 'my-line-class' })
Best practice for destroying the decoration is by destroying the DisplayMarker.
marker.destroy()
You should only use Decoration#destroy when you still need or do not own the marker.
Lifecycle1
Destroy this marker decoration.
You can also destroy the marker if you own it, which will destroy this decoration.
Returns
void
Event Subscription2
Invoke a callback when this decoration’s properties are replaced.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
oldProperties | Object | the decoration’s previous properties |
newProperties | Object | the decoration’s new properties |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the Decoration is destroyed
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Decoration Details3
An id unique across all Decoration objects
Returns
Number — The id unique among decorations.
Get the display marker tracked by this decoration.
Returns
DisplayMarker — marker associated with this Decoration
Check if this decoration is of type type
| Argument | Type | Description |
|---|---|---|
type | String|Array<String> | type like 'line-number', 'line', etc. When given an array, returns true if the decoration matches any listed type. |
Returns
Boolean
Properties2
Get the properties used to render this decoration.
Returns
Object — The decoration’s properties.
Replace this decoration’s properties, including its CSS class.
Examples
decoration.setProperties({ type: 'line-number', class: 'my-new-class' })
| Argument | Type | Description |
|---|---|---|
newProperties | Object | eg. {type: 'line-number', class: 'my-new-class'} |
Returns
void
Public API
DefaultDirectoryProvidersrc/default-directory-provider.js:37
Turns a project URI into a Directory, for local paths.
This is the provider Project falls back to when no package claims a URI. A
package supplies its own by providing the project.directory-provider
service; the methods below are the shape that contract expects.
Resolving Directories2
Create a Directory that corresponds to the specified URI.
| Argument | Type | Description |
|---|---|---|
uri | String | The path to the directory to add. This is guaranteed not to be contained by a Directory in lumine.project. |
Returns
Directory — A directory wrapper for the URI, or its existing parent when the URI is not an existing directory.
Create a Directory that corresponds to the specified URI.
| Argument | Type | Description |
|---|---|---|
uri | String | The path to the directory to add. This is guaranteed not to be contained by a Directory in lumine.project. |
Returns
Promise<Directory> — The same directory wrapper as directoryForURISync.
Path Normalization1
Normalize platform separators and the drive letter of a local path.
| Argument | Type | Description |
|---|---|---|
uri | String | The path that should be normalized. |
Returns
String — with normalized path.
Extended API
DeserializerManagersrc/deserializer-manager.js:36
Manages the deserializers used for serialized state
Full description
An instance of this class is always available as the lumine.deserializers
global.
Examples#
class MyPackageView {
static deserialize(state) {
return new MyPackageView(state)
}
constructor(state) {
this.state = state
}
serialize() {
return { deserializer: 'MyPackageView', ...this.state }
}
}
lumine.deserializers.add(MyPackageView)
Serialized state has to carry the deserializer key: it is the name
#deserialize looks the class up by, and state without it is dropped with a
warning rather than restored.
Methods2
Register the given class(es) as deserializers.
| Argument | Type | Description |
|---|---|---|
...deserializers | ...(Object|Function) | One or more deserializers to register. A deserializer can be any object with a .name property and a .deserialize() method. A common approach is to register a constructor as the deserializer for its instances by adding a .deserialize() class method. When your method is called, it will be passed serialized state as the first argument and the Environment object as the second argument, which is useful if you wish to avoid referencing the lumine global. |
Returns
Disposable — Removes these registrations and restores any previous deserializer with the same name.
Deserialize serialized state with its registered deserializer.
| Argument | Type | Description |
|---|---|---|
state | Object | The state Object to deserialize. |
Returns
* — The deserializer result, or undefined when state is absent, unknown, or has an incompatible version.
Essential API
DisplayMarkersrc/display-marker.js:51
Represents a buffer annotation that remains logically stationary even as the buffer changes. This is used to represent cursors, folds, snippet targets, misspelled words, and anything else that needs to track a logical location in the buffer over time.
Full description
DisplayMarker Creation#
Use DisplayMarkerLayer#markBufferRange or DisplayMarkerLayer#markScreenRange rather than creating Markers directly.
Head and Tail#
Markers always have a head and sometimes have a tail. If you think of a marker as an editor selection, the tail is the part that’s stationary and the head is the part that moves when the mouse is moved. A marker without a tail always reports an empty range at the head position. A marker with a head position greater than the tail is in a “normal” orientation. If the head precedes the tail the marker is in a “reversed” orientation.
Validity#
Markers are considered valid when they are first created. Depending on the invalidation strategy you choose, certain changes to the buffer can cause a marker to become invalid, for example if the text surrounding the marker is deleted. The strategies, in order of descending fragility:
- never: The marker is never marked as invalid. This is a good choice for markers representing selections in an editor.
- surround: The marker is invalidated by changes that completely surround it.
- overlap: The marker is invalidated by changes that surround the start or end of the marker. This is the default.
- inside: The marker is invalidated by changes that extend into the inside of the marker. Changes that end at the marker’s start or start at the marker’s end do not invalidate the marker.
- touch: The marker is invalidated by a change that touches the marked region in any way, including changes that end at the marker’s start or start at the marker’s end. This is the most fragile strategy.
See TextBuffer#markRange for usage.
Lifecycle2
Destroy the marker and notify #onDidDestroy subscribers. Once destroyed, a marker cannot be restored by undo/redo operations.
Creates and returns a new DisplayMarker with the same properties as this marker.
Selection markers (markers with a custom property type: "selection")
should be copied with a different type value, for example with
marker.copy({type: null}). Otherwise, the new marker’s selection will
be merged with this marker’s selection, and an undefined value will be
returned.
| Argument | Type | Description |
|---|---|---|
paramsoptional | Object | properties to associate with the new marker. The new marker’s properties are computed by extending this marker’s properties with params. |
Returns
DisplayMarker|undefined — The copied marker, or undefined when it was merged into a selection.
Event Subscription2
Invoke the given callback when the state of the marker changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the marker changes. |
event | Object | with the following keys: |
oldHeadBufferPosition | Point | representing the former head buffer position |
newHeadBufferPosition | Point | representing the new head buffer position |
oldTailBufferPosition | Point | representing the former tail buffer position |
newTailBufferPosition | Point | representing the new tail buffer position |
oldHeadScreenPosition | Point | representing the former head screen position |
newHeadScreenPosition | Point | representing the new head screen position |
oldTailScreenPosition | Point | representing the former tail screen position |
newTailScreenPosition | Point | representing the new tail screen position |
wasValid | Boolean | indicating whether the marker was valid before the change |
isValid | Boolean | indicating whether the marker is now valid |
hadTail | Boolean | indicating whether the marker had a tail before the change |
hasTail | Boolean | indicating whether the marker now has a tail |
oldProperties | Object | containing the marker’s custom properties before the change. |
newProperties | Object | containing the marker’s custom properties after the change. |
textChanged | Boolean | indicating whether this change was caused by a textual change to the buffer or whether the marker was manipulated directly via its public API. |
origin | String | edit, undo, redo, reload, or mixed; identifies history replay and buffer reloads independently of textChanged. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the marker is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the marker is destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Marker Details6
Determine whether this marker is valid.
Returns
Boolean — indicating whether the marker is valid. Markers can be invalidated when a region surrounding them in the buffer is changed.
Determine whether this marker has been destroyed.
Returns
Boolean — indicating whether the marker has been destroyed. A marker can be invalid without being destroyed, in which case undoing the invalidating operation would restore the marker. Once a marker is destroyed by calling DisplayMarker#destroy, no undo/redo operation can ever bring it back.
Determine whether the head precedes the tail.
Returns
Boolean — indicating whether the head precedes the tail.
Determine whether insertions at the endpoints stay outside this marker.
Returns
Boolean — Whether insertions at either endpoint remain outside the marked range.
Get the invalidation strategy for this marker.
Valid values include: never, surround, overlap, inside, and touch.
Returns
String
Determine whether this marker has a tail.
Returns
Boolean — indicating whether the marker has a tail.
Properties2
Get the custom properties associated with this marker.
Returns
Object — containing any custom properties associated with the marker.
Merges an Object containing new properties into the marker’s
existing properties.
| Argument | Type | Description |
|---|---|---|
properties | Object |
Returns
Boolean|undefined — Whether the marker changed, or undefined when no update is attempted.
Range Queries1
Determine whether this marker matches a marker-layer query.
| Argument | Type | Description |
|---|---|---|
attributes | Object |
Returns
Boolean — whether this marker matches the given parameters. The parameters are the same as DisplayMarkerLayer#findMarkers.
Comparison2
Compares this marker to another based on their ranges.
| Argument | Type | Description |
|---|---|---|
otherMarker | DisplayMarker | The marker to compare. |
Returns
Number — The ordering of this marker relative to otherMarker.
Determine whether this marker has the same range and options as another.
| Argument | Type | Description |
|---|---|---|
other | DisplayMarker | other marker |
Returns
Boolean — indicating whether this marker is equivalent to another marker, meaning they have the same range and options.
Marker Ranges18
Gets the buffer range of this marker.
Returns
Gets the screen range of this marker.
Returns
Modifies the buffer range of this marker.
| Argument | Type | Description |
|---|---|---|
bufferRange | Range|Array<Point|Array<Number>>|Object | The new Range to use |
propertiesoptional | Object | Range options; custom properties are not updated by this method. |
reversedoptional | Boolean | If true, place the head at the earlier endpoint; omission preserves the current orientation. |
exclusiveoptional | Boolean | Override endpoint insertion affinity when supplied. |
Returns
Boolean|undefined — Whether the marker changed, or undefined when no update is attempted.
Modifies the screen range of this marker.
| Argument | Type | Description |
|---|---|---|
screenRange | Range|Array<Point|Array<Number>>|Object | The new Range to use |
optionsoptional | Object | An Object with the following keys: |
reversedoptional | Boolean | If true, place the head at the earlier endpoint; omission preserves the current orientation. |
clipDirectionoptional, default: 'closest' | String | If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest' and applies to both ends of the range. |
exclusiveoptional | Boolean | Override endpoint insertion affinity when supplied. |
Returns
Boolean|undefined — Whether the marker changed, or undefined when no update is attempted.
Retrieves the buffer position of the marker’s head.
Returns
Retrieves the screen position of the marker’s head.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | An Object with the following keys: |
clipDirectionoptional, default: 'closest' | String | If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'. |
Returns
Point — The marker’s head screen position.
Sets the screen position of the marker’s head.
| Argument | Type | Description |
|---|---|---|
screenPosition | Point|Array<Number>|Object | The new Point to use |
optionsoptional | Object | An Object with the following keys: |
clipDirectionoptional, default: 'closest' | String | If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'. |
Returns
Boolean|undefined — Whether the marker changed, or undefined when no update is attempted.
Retrieves the buffer position of the marker’s tail.
Returns
Retrieves the screen position of the marker’s tail.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | An Object with the following keys: |
clipDirectionoptional, default: 'closest' | String | If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'. |
Returns
Point — The marker’s tail screen position.
Sets the screen position of the marker’s tail.
| Argument | Type | Description |
|---|---|---|
screenPosition | Point|Array<Number>|Object | The new Point to use |
optionsoptional | Object | An Object with the following keys: |
clipDirectionoptional, default: 'closest' | String | If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'. |
Returns
Boolean|undefined — Whether the marker changed, or undefined when no update is attempted.
Retrieves the buffer position of the marker’s start. This will always be less than or equal to the result of DisplayMarker#getEndBufferPosition.
Returns
Retrieves the screen position of the marker’s start. This will always be less than or equal to the result of DisplayMarker#getEndScreenPosition.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | An Object with the following keys: |
clipDirectionoptional, default: 'closest' | String | If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'. |
Returns
Point — The marker’s start screen position.
Retrieves the buffer position of the marker’s end. This will always be greater than or equal to the result of DisplayMarker#getStartBufferPosition.
Returns
Retrieves the screen position of the marker’s end. This will always be greater than or equal to the result of DisplayMarker#getStartScreenPosition.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | An Object with the following keys: |
clipDirectionoptional, default: 'closest' | String | If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'. |
Returns
Point — The marker’s end screen position.
Plants the marker’s tail at the current head position. After calling the marker’s tail position will be its head position at the time of the call, regardless of where the marker’s head is moved.
Returns
Boolean|undefined — Whether the marker changed, or undefined when no update is attempted.
Removes the marker’s tail. After calling the marker’s head position will be reported as its current tail position until the tail is planted again.
Returns
Boolean|undefined — Whether the marker changed, or undefined when no update is attempted.
Experimental API
DisplayMarkerLayersrc/display-marker-layer.js:13
A container for a related set of markers at the DisplayLayer level. Wraps
an underlying MarkerLayer on the TextBuffer.
Lifecycle3
Destroy this layer.
Returns
void
Destroy all markers in this layer.
Returns
void
Determine whether this layer has been destroyed.
Returns
Boolean
Range Tracking2
Set this layer’s custom range tracker in buffer coordinates. See MarkerLayer#setRangeTracker for the callback contract.
| Argument | Type | Description |
|---|---|---|
callbackoptional | Function|null | A range tracker, or null to disable it. |
Get the custom tracker used for buffer-coordinate ranges.
Returns
Function|null — The custom range tracker, or null when native tracking is used.
Event Subscription3
Subscribe to be notified synchronously when this layer is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — Dispose to unsubscribe.
Subscribe to be notified whenever markers are created, updated, or destroyed on this layer. Prefer this method for optimal performance when interacting with layers that could contain large numbers of markers.
Changes made within a TextBuffer#transact block are batched: subscribers are notified once, at the end of the transaction. Changes made outside a transaction notify subscribers synchronously per change. You should re-query the layer to determine the state of markers in which you’re interested in. It may be counter-intuitive, but this is much more efficient than subscribing to events on individual markers, which are expensive to deliver.
| Argument | Type | Description |
|---|---|---|
callback | Function | A Function that will be called with no arguments when changes occur on this layer. |
Returns
Disposable — Dispose to unsubscribe.
Subscribe to be notified synchronously whenever markers are created on this layer. Avoid this method for optimal performance when interacting with layers that could contain large numbers of markers.
You should prefer #onDidUpdate when synchronous notifications aren’t absolutely necessary.
| Argument | Type | Description |
|---|---|---|
callback | Function | A Function that will be called with a DisplayMarker whenever a new marker is created. |
marker | DisplayMarker | The newly created marker. |
Returns
Disposable — Dispose to unsubscribe.
Marker Creation4
Create a marker with the given screen range.
| Argument | Type | Description |
|---|---|---|
screenRange | Range|Array<Point|Array<Number>>|Object | The range to mark; compatible arrays and coordinate objects are accepted. |
optionsoptional | Object | Marker options and custom properties. |
reversedoptional, default: false | Boolean | Place the head at the earlier endpoint. |
invalidateoptional, default: 'overlap' | String | Invalidation strategy: never, surround, overlap, inside, or touch. See DisplayMarker for the strategy definitions. |
exclusiveoptional | Boolean | Keep endpoint insertions outside the marker. Defaults to false, or true with the inside invalidation strategy. |
clipDirectionoptional, default: 'closest' | String | Clip invalid screen positions backward, forward, or to the closest valid position. |
Returns
DisplayMarker — The new marker.
Create a marker with its head at the given screen position and no tail.
| Argument | Type | Description |
|---|---|---|
screenPosition | Point|Array<Number>|Object | The position to mark; compatible arrays and coordinate objects are accepted. |
optionsoptional | Object | Marker options and custom properties. |
invalidateoptional, default: 'overlap' | String | Invalidation strategy: never, surround, overlap, inside, or touch. See DisplayMarker for the strategy definitions. |
exclusiveoptional | Boolean | Keep endpoint insertions outside the marker. Defaults to true for markers without a tail. |
clipDirectionoptional, default: 'closest' | String | Clip invalid screen positions backward, forward, or to the closest valid position. |
Returns
DisplayMarker — The new marker.
Create a marker with the given buffer range.
| Argument | Type | Description |
|---|---|---|
bufferRange | Range|Array<Point|Array<Number>>|Object | The range to mark; compatible arrays and coordinate objects are accepted. |
optionsoptional | Object | Marker options and custom properties. |
reversedoptional, default: false | Boolean | Place the head at the earlier endpoint. |
invalidateoptional, default: 'overlap' | String | Invalidation strategy: never, surround, overlap, inside, or touch. See DisplayMarker for the strategy definitions. |
exclusiveoptional | Boolean | Keep endpoint insertions outside the marker. Defaults to false, or true with the inside invalidation strategy. |
Returns
DisplayMarker — The new marker.
Create a marker with its head at the given buffer position and no tail.
| Argument | Type | Description |
|---|---|---|
bufferPosition | Point|Array<Number>|Object | The position to mark; compatible arrays and coordinate objects are accepted. |
optionsoptional | Object | Marker options and custom properties. |
invalidateoptional, default: 'overlap' | String | Invalidation strategy: never, surround, overlap, inside, or touch. See DisplayMarker for the strategy definitions. |
exclusiveoptional | Boolean | Keep endpoint insertions outside the marker. Defaults to true for markers without a tail. |
Returns
DisplayMarker — The new marker.
Essential API
Disposablelib/disposable.js:8
A handle to a resource that can be disposed. For example, Emitter#on returns disposables representing subscriptions.
Methods1
Ensure that object correctly implements the Disposable contract.
| Argument | Type | Description |
|---|---|---|
object | Object | The object to check. |
Returns
Boolean — Whether object is a valid Disposable.
Construction and Destruction2
Construct a Disposable.
| Argument | Type | Description |
|---|---|---|
disposalActionoptional | Function | A function to call when Disposable#dispose is called for the first time. |
Perform the disposal action, indicating that the resource associated with this disposable is no longer needed.
You can call this method more than once, but the disposal action will only be performed the first time.
Extended API
Docksrc/dock.js:25
A container at the edges of the editor window capable of holding items. You should not create a Dock directly. Instead, access one of the three docks of the workspace via Workspace#getLeftDock, Workspace#getRightDock, and Workspace#getBottomDock or add an item to a dock via Workspace#open.
Activation1
Show the dock and focus its active Pane.
Visibility4
Show the dock without focusing it.
Hide the dock and activate the WorkspaceCenter if the dock was was previously focused.
Toggle the dock’s visibility without changing the Workspace’s active pane container.
Check if the dock is visible.
Returns
Boolean
Event Subscription16
Invoke the given callback when the visibility of the dock changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the visibility changes. |
visible | Boolean | Is the dock now visible? |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with the current and all future visibilities of the dock.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the visibility changes. |
visible | Boolean | Is the dock now visible? |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with all current and future panes items in the dock.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with current and future pane items. |
item | * | An item that is present in #getPaneItems at the time of subscription or that is added at some later time. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the active pane item changes.
Because observers are invoked synchronously, it’s important not to perform any expensive operations via this method. Consider #onDidStopChangingActivePaneItem to delay operations until after changes stop occurring.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active pane item changes. |
item | * | The active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the active pane item stops changing.
Observers are called asynchronously 100ms after the last active pane item change. Handling changes here rather than in the synchronous #onDidChangeActivePaneItem prevents unneeded work if the user is quickly changing or closing tabs and ensures critical UI feedback, like changing the highlighted tab, gets priority over work that can be done asynchronously.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active pane item stops changing. |
item | * | The active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with the current active pane item and with all future active pane items in the dock.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active pane item changes. |
item | * | The current active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a pane is added to the dock.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when panes are added. |
event | Object | with the following keys: |
pane | Pane | The added pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback before a pane is destroyed in the dock.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called before panes are destroyed. |
event | Object | with the following keys: |
pane | Pane | The pane to be destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a pane is destroyed in the dock.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when panes are destroyed. |
event | Object | with the following keys: |
pane | Pane | The destroyed pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with all current and future panes in the dock.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with current and future panes. |
pane | Pane |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the active pane changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active pane changes. |
pane | Pane | A Pane that is the current return value of #getActivePane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with the current active pane and when the active pane changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with the current and future active panes. |
pane | Pane | A Pane that is the current return value of #getActivePane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a pane item is added to the dock.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when pane items are added. |
event | Object | with the following keys: |
item | * | The added pane item. |
pane | Pane | containing the added item. |
index | Number | indicating the index of the added item in its pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a pane item is about to be destroyed, before the user is prompted to save it.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called before pane items are destroyed. |
event | Object | with the following keys: |
item | * | The item to be destroyed. |
pane | Pane | containing the item to be destroyed. |
index | Number | indicating the index of the item to be destroyed in its pane. |
Returns
Disposable — on which .dispose can be called to unsubscribe.
Invoke the given callback when a pane item is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when pane items are destroyed. |
event | Object | with the following keys: |
item | * | The destroyed item. |
pane | Pane | containing the destroyed item. |
index | Number | indicating the index of the destroyed item in its pane. |
Returns
Disposable — on which .dispose can be called to unsubscribe.
Invoke the given callback when the hovered state of the dock changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the hovered state changes. |
hovered | Boolean | Is the dock now hovered? |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Pane Items2
Get all pane items in the dock.
Returns
Array — of items.
Get the active Pane’s active item.
Returns
Object|undefined — pane item Object.
Panes4
Public API
EditorWindowsrc/editor-window.js:13
A presentation window belonging to one workspace. Documents and packages belong to the workspace; this object owns the window’s presentation lifetime.
Window Information5
Get the native identity of this window.
Returns
Number — The native window ID.
Determine whether this is the workspace’s main window.
Returns
Boolean — Whether this is the main presentation.
Get the shared workspace owning this window.
Returns
Workspace — The shared workspace.
Get this window’s local document pane container.
Returns
PaneContainer — The window-local document container.
Read the native window’s state.
Returns
Promise<Object> — The native window state snapshot.
DOM Access3
Get the DOM document used by this presentation.
Returns
Document|null — The presentation document, or null before attachment and after destruction.
Get the DOM window used by this presentation.
Returns
Window|null — The physical DOM window, or null before attachment and after destruction.
Get this window’s workspace command root.
Returns
HTMLElement|null — The workspace command root, or null before attachment and after destruction.
Frame Messaging1
Send a message to an embedded frame from its physical parent window.
| Argument | Type | Description |
|---|---|---|
frame | HTMLIFrameElement | A frame belonging to this window’s document. |
message | * | Structured-cloneable message data. |
originoptional, default: "*" | String | The expected target origin, or “*” for an opaque sandbox. |
portsoptional, default: [ | Array<MessagePort> | ] - Transferable ports owned by the caller. |
Panels4
Add a panel to this window’s title bar region.
| Argument | Type | Description |
|---|---|---|
options | Object | Panel item, visibility and priority. |
Returns
Panel — The window-local panel.
Add a modal panel to this presentation’s own document.
| Argument | Type | Description |
|---|---|---|
options | Object | Panel content, visibility and modal options. |
dismissOnBluroptional, default: false | Boolean|Function | Hide after an outside click or same-document focus departure. A synchronous predicate must return true to permit dismissal. Window blur preserves the panel. Supplying this option enables autoFocus unless explicitly disabled. |
Returns
Panel — The local modal panel.
Observe this window’s existing and newly added modal panels.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives each Panel once; observe its visibility and destruction separately. |
Returns
Disposable — Stops observing new panels.
Lifecycle1
Determine whether this presentation has been destroyed.
Returns
Boolean
Event Subscription8
Subscribe before the window’s presentation is released.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives this EditorWindow before its presentation is released. |
window | EditorWindow | The window being destroyed. |
Returns
Disposable — Dispose to remove the callback.
Subscribe after the window’s presentation is released.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives this EditorWindow after its presentation is released. |
window | EditorWindow | The destroyed window. |
Returns
Disposable — Dispose to remove the callback.
Subscribe when the native window gains focus.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called when the documented window lifecycle event occurs. |
Returns
Disposable — Dispose to remove the callback.
Subscribe when the native window loses focus.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called when the documented window lifecycle event occurs. |
Returns
Disposable — Dispose to remove the callback.
Subscribe when this native window is maximized.
| Argument | Type | Description |
|---|---|---|
callback | Function | The observer. |
Returns
Disposable — Dispose to unsubscribe.
Subscribe when this native window leaves maximization.
| Argument | Type | Description |
|---|---|---|
callback | Function | The observer. |
Returns
Disposable — Dispose to unsubscribe.
Subscribe when this native window enters fullscreen.
| Argument | Type | Description |
|---|---|---|
callback | Function | The observer. |
Returns
Disposable — Dispose to unsubscribe.
Subscribe when this native window leaves fullscreen.
| Argument | Type | Description |
|---|---|---|
callback | Function | The observer. |
Returns
Disposable — Dispose to unsubscribe.
Window Geometry1
Set the native bounds of this presentation.
| Argument | Type | Description |
|---|---|---|
bounds | Object | x, y, width and height. |
x | Number | The integer horizontal screen position. |
y | Number | The integer vertical screen position. |
width | Number | The positive integer window width. |
height | Number | The positive integer window height. |
Returns
Promise — Completes when the bounds have been applied.
Native Presentation2
Set the document path represented by this native window.
| Argument | Type | Description |
|---|---|---|
filename | String | The current path, or an empty string. |
Returns
Promise — Completes after the native property is set.
Set the attachment offset of native sheets in this window.
| Argument | Type | Description |
|---|---|---|
offset | Number | The title bar height in pixels. |
Returns
Promise|undefined — Completes when supported by the platform.
Dialogs3
Choose resources in a native dialog attached to this window.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Electron open dialog options. |
Returns
Promise<Object> — The selected filePaths or a cancelled result.
Choose a save path in a native dialog attached to this window.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Electron save dialog options. |
Returns
Promise<Object> — The selected filePath or a cancelled result.
Ask for a decision in a native dialog attached to this window.
| Argument | Type | Description |
|---|---|---|
options | Object | The message, detail and button labels. |
Returns
Promise<Number> — The selected button index.
Window Management6
Show this native window without changing its document or pane layout.
Returns
Promise<void> — Resolves when the native window has been shown.
Focus this window.
Returns
Promise<void>
Minimize this window.
Returns
Promise<void>
Maximize this window.
Returns
Promise<void>
Restore this window from maximization.
Returns
Promise<void>
Request a coordinated close of this window.
Returns
Promise<Boolean|void> — The workspace close decision, or completion of the native close request when no workspace coordinator is installed.
Essential API
Emitterlib/emitter.js:36
Utility class to be used when implementing event-based APIs that allows handlers registered via Emitter#on to be invoked with calls to Emitter#emit. Instances of this class are intended to be used internally by classes that expose an event-based API.
Full description
For example:
class User {
constructor() {
this.emitter = new Emitter();
}
onDidChangeName(callback) {
return this.emitter.on("did-change-name", callback);
}
setName(name) {
if (name !== this.name) {
this.name = name;
this.emitter.emit("did-change-name", name);
}
return this.name;
}
}
Construction and Destruction3
Construct an emitter.
this.emitter = new Emitter();
Clear out any existing subscribers.
Unsubscribe all handlers.
Event Subscription3
Register the given handler function to be invoked whenever events by the given name are emitted via Emitter#emit.
| Argument | Type | Description |
|---|---|---|
eventName | String | The name of the event that invokes the handler. |
handler | Function | The function to invoke when Emitter#emit is called with the given event name. |
unshiftoptional, default: false | Boolean | Whether to add the handler before the existing handlers. |
Returns
Disposable — A subscription on which Disposable#dispose can be called to unsubscribe.
Register the given handler function to be invoked the next time an event with the given name is emitted via Emitter#emit.
| Argument | Type | Description |
|---|---|---|
eventName | String | The name of the event that invokes the handler. |
handler | Function | The function to invoke when Emitter#emit is called with the given event name. |
unshiftoptional, default: false | Boolean | Whether to add the handler before the existing handlers. |
Returns
Disposable — A subscription on which Disposable#dispose can be called to unsubscribe.
Register the given handler function to be invoked before all other handlers existing at the time of subscription whenever events by the given name are emitted via Emitter#emit.
Use this method when you need to be the first to handle a given event. This could be required when a data structure in a parent object needs to be updated before third-party event handlers registered on a child object via a public API are invoked. Your handler could itself be preempted via subsequent calls to this method, but this can be controlled by keeping methods based on Emitter#preempt private.
| Argument | Type | Description |
|---|---|---|
eventName | String | The name of the event that invokes the handler. |
handler | Function | The function to invoke when Emitter#emit is called with the given event name. |
Returns
Disposable — A subscription on which Disposable#dispose can be called to unsubscribe.
Event Emission1
Invoke handlers registered via Emitter#on for the given event name.
| Argument | Type | Description |
|---|---|---|
eventName | String | The name of the event to emit. Handlers registered with Emitter#on for the same name will be invoked. |
value | * | The value passed to each handler. |
Public API
FileWatchHandlesrc/file-watch-client.js:14
A disposable observation of a fixed filesystem path. External renames do not change its path. Register callbacks immediately, then await ready.
Observation State3
Get the fixed absolute path requested by the subscriber.
Returns
String — The absolute path in the subscriber’s spelling.
Wait for the underlying observation to be armed.
Returns
Promise<void> — Resolves when observation is armed; rejects on failure or cancellation.
Wait for disposal to release ownership and native resources.
Returns
Promise<void> — Resolves after this handle’s ownership and resources are released.
Event Subscription3
Subscribe to batches of created, updated and deleted paths.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called with an array of {action, path} changes. |
Returns
Disposable — Removes the callback when disposed.
Subscribe to restored observation after changes may have been lost.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called with {path, reason, generation} after recovery. |
Returns
Disposable — Removes the callback when disposed.
Subscribe to structured observation errors.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called with an Error retaining code, path and backend. |
Returns
Disposable — Removes the callback when disposed.
Lifecycle1
Suppress further callbacks immediately and release this observation. Await closed to confirm release. Cancelling before ready rejects ready with an AbortError. Repeated disposal has no effect.
Returns
void
Extended API
GitRepositorysrc/git-repository.js:162
Represents the underlying git operations performed by Lumine.
Full description
This class shouldn’t be instantiated directly but instead by accessing the
lumine.repositories and calling getRepositories() or getForPath(). It is
independent from project roots and may represent containing or nested repos.
Examples#
Logging the URL of the origin remote#
const git = lumine.repositories.getRepositories()[0]
console.log(git.getOriginURL())
Requiring in packages#
const { GitRepository } = require('lumine')
Construction and Destruction3
Creates a new GitRepository instance.
| Argument | Type | Description |
|---|---|---|
path | String | The String path to the Git repository to open. |
optionsoptional, default: {} | Object | Optional repository construction settings. |
Returns
Promise<GitRepository|null> — resolving to an instance or null if the repository could not be opened.
Destroy this GitRepository object.
This destroys any tasks and subscriptions. Repository operations run in the git-host process and hold no Git process or repository state in the renderer. This method is idempotent.
Check whether this repository has been destroyed.
Returns
Boolean — indicating if this repository has been destroyed.
Operations1
Get the repository write facade supplied by operation providers.
Returns
Object|null — stable write facade assigned by lumine.repositories. Its methods are enabled by repositories.operations-provider services.
Event Subscription4
Invoke the given callback when this GitRepository’s destroy() method is invoked.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the detailed repository status snapshot changes.
Subscribing declares interest: the repository lazily loads the first snapshot and keeps it fresh with debounced background refreshes while at least one subscriber exists. Consumers never call #refreshStatusSnapshot themselves.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with an immutable status snapshot. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the repository refs snapshot changes. Subscribing declares interest exactly like #onDidChangeStatusSnapshot: the first subscriber triggers a lazy load and refs stay fresh with debounced background refreshes.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with an immutable refs snapshot. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Observe accepted changes to the cached status, refs or effective HEAD. Unlike the snapshot subscriptions, this declares no interest, schedules no refresh and performs no Git or filesystem work. It does not replay the current state. Combined refreshes publish both caches before notifying.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with a frozen {repository, kind, snapshot} object, where kind is status or refs and snapshot is the accepted immutable cache. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Repository Details8
A String indicating the type of version control system used by
this repository.
Returns
"git"
Get the absolute path of the repository Git directory.
Returns
String — path of the repository.
Get the repository working directory.
Returns
String|null — The working directory path, or null for a bare repository.
Get the Git directory shared by linked worktrees.
Returns
String — directory shared by linked worktrees for refs and configuration.
Makes a path relative to the repository’s working directory.
| Argument | Type | Description |
|---|---|---|
path | String | An absolute or repository-relative path. |
Returns
String — A relative path inside the working directory, or the input path when it lies outside.
Is the given path a submodule in the repository?
| Argument | Type | Description |
|---|---|---|
filePath | String | The String path to check. |
Returns
Boolean
The index mode of a path (git ls-files --stage).
| Argument | Type | Description |
|---|---|---|
filePath | String | A String path, absolute or repository-relative. |
Returns
Promise<String|null> — resolving to the String mode (e.g. "100644"), or null when the path is not tracked.
The repository-relative paths declared in .gitmodules.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Read options. |
signaloptional | AbortSignal | Cancellation signal. |
Returns
Promise<Array<String>> — resolving to an Array of path Strings.
References13
Check whether a branch exists in the cached refs snapshot.
| Argument | Type | Description |
|---|---|---|
branch | String | The local branch name. |
Returns
Boolean — true if the given branch exists.
Retrieves a shortened version of the HEAD reference value.
This removes the leading segments of refs/heads, refs/tags, or
refs/remotes. It also shortens the object id of a detached HEAD to 7
characters, independent of the repository’s object format.
Returns
String — The shortened HEAD reference.
Get cached ahead and behind counts for a branch reference.
| Argument | Type | Description |
|---|---|---|
referenceoptional | String | The branch reference name; omit it for the current HEAD branch. |
Returns
Object — The ahead and behind commit counts.
Get the cached ahead/behind commit counts for the current branch’s upstream branch.
aheadTheNumberof commits ahead.behindTheNumberof commits behind.
Returns
Object — with the following keys:
Get the fetch URL of the origin remote from the refs snapshot.
Returns
String|null — origin url of the repository, read from the refs snapshot’s remotes. Returns null until the snapshot has loaded or when the repository has no origin remote.
Get the current branch upstream reference from the refs snapshot.
Returns
String|null — The upstream branch, such as refs/remotes/origin/master, or null when HEAD has no upstream.
Gets all the local and remote references.
headsAnArrayof head reference names.remotesAnArrayof remote reference names.tagsAnArrayof tag reference names.
Returns
Object — with the following keys:
Get the object ID of a reference from the refs snapshot.
| Argument | Type | Description |
|---|---|---|
reference | String | The String reference to get the target of. |
Returns
String|null — The current SHA for the reference, or null when it is unavailable.
Get the latest immutable repository refs snapshot.
Returns
Object — latest immutable refs snapshot. It contains head, local branches with upstream tracking, remoteBranches, tags, remotes with fetch and push URLs, worktrees, and a monotonic generation. Branch and tag entries include lastCommit metadata for their target commit. The initial snapshot has initialized: false; subscribe with #onDidChangeRefsSnapshot or call #ensureRefsSnapshot to load it.
Resolve with an initialized refs snapshot, loading it on first call. Concurrent callers share one in-flight refresh.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Snapshot read options. |
signaloptional | AbortSignal | Cancellation signal. |
Returns
Promise<Object> — that resolves to the snapshot.
Refresh the refs snapshot with Git. Concurrent calls coalesce into at most one in-flight and one trailing worker request.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Snapshot read options. |
signaloptional | AbortSignal | Cancellation signal. |
debounceoptional, default: false | Boolean | Coalesce filesystem triggers through the background debounce window while awaiting a fresh snapshot. |
Returns
Promise<Object> — The refreshed immutable refs snapshot.
Describe HEAD as a ref name (git describe --contains --all --always). Returns a Promise resolving to the String description, or
"" when the branch is unborn.
Returns
Promise<String> — The ref description of HEAD, or an empty string for an unborn branch.
The fully-qualified refnames of branches that contain a commit
(git branch --contains).
| Argument | Type | Description |
|---|---|---|
commit | String | A String commit id or revision. |
optionsoptional, default: {} | Object | Branch filtering options. |
showLocaloptional, default: false | Boolean | Include local branches. |
showRemoteoptional, default: false | Boolean | Include remote branches. |
patternoptional | String | Limit branch names by pattern. |
Returns
Promise<Array<String>> — resolving to an Array of refname Strings.
Git Configuration2
Asynchronously read a git configuration value via the git-host worker.
Resolves to the value or null when unset.
| Argument | Type | Description |
|---|---|---|
key | String | The configuration key to look up. |
optionsoptional, default: {} | Object | Read options. |
signaloptional | AbortSignal | Cancellation signal. |
Returns
Promise<String|null> — The configured value.
Read several effective Git configuration values in one repository pass.
Every requested key is present on the resolved plain object and maps
to a String value or null when unset.
| Argument | Type | Description |
|---|---|---|
keys | Array<String> | Configuration keys to read. |
optionsoptional, default: {} | Object | Read options. |
signaloptional | AbortSignal | Cancellation signal. |
Returns
Promise<Object> — Values keyed by the requested names.
Reading Status10
Check whether a cached status entry marks a path as modified.
| Argument | Type | Description |
|---|---|---|
path | String | The String path to check. |
Returns
Boolean — Whether the path is modified in the detailed status snapshot. Returns false until the snapshot loads.
Check whether a cached status entry marks a path as newly added.
| Argument | Type | Description |
|---|---|---|
path | String | The String path to check. |
Returns
Boolean — Whether the path is new in the detailed status snapshot. Returns false until the snapshot loads.
Is the given path ignored? Resolved from the detailed status snapshot’s ignored entries; returns false until the snapshot has loaded.
| Argument | Type | Description |
|---|---|---|
path | String | The String path to check. |
Returns
Boolean — that’s true if the path is ignored.
Whether the given path is ignored, resolved synchronously from the Git status snapshot’s ignored entries. Returns false until the first snapshot loads.
| Argument | Type | Description |
|---|---|---|
filePath | String | The String path to check. |
Returns
Boolean — that’s true if the filePath is ignored.
Get the latest immutable repository status snapshot.
Returns
Object — latest immutable detailed status snapshot. It contains head, upstream, submodulePaths, per-file staged/unstaged/conflict state, aggregate counts, and a monotonic generation. The initial snapshot has initialized: false; subscribe with #onDidChangeStatusSnapshot or call #ensureStatusSnapshot to load it.
Resolve with an initialized status snapshot, loading it on first call. Concurrent callers share one in-flight refresh.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Snapshot read options. |
signaloptional | AbortSignal | Cancellation signal. |
includeIgnoredoptional, default: true | Boolean | Include ignored paths in the status snapshot. |
Returns
Promise<Object> — that resolves to the snapshot.
Get the detailed cached status entry for a repository path.
| Argument | Type | Description |
|---|---|---|
filePath | String | An absolute or repository-relative path. |
Returns
Object|null — detailed cached status for a repository path, or null.
Refresh the detailed branch and file status snapshot with Git. Concurrent calls coalesce into at most one in-flight and one trailing worker request.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Snapshot read options. |
signaloptional | AbortSignal | Cancellation signal. |
includeIgnoredoptional, default: true | Boolean | Include ignored paths in the status snapshot. |
debounceoptional, default: false | Boolean | Coalesce filesystem triggers through the background debounce window while awaiting a fresh snapshot. |
Returns
Promise<Object> — The refreshed immutable status snapshot.
Classified status for one path, read from the detailed status snapshot.
| Argument | Type | Description |
|---|---|---|
filePath | String | A String path, absolute or repository-relative. |
Returns
Object|null — frozen {source, conflicted, modified, added, renamed, staged, unstaged} object (source is always "snapshot"), or null for clean, ignored, unknown, and pre-snapshot paths. Both staged and unstaged can be true.
Aggregate classified status for a directory, including the
repository root. Same sourcing and shape as #getPathStatusSummary
(without renamed); returns null when nothing below the directory has
a reportable status.
| Argument | Type | Description |
|---|---|---|
directoryPath | String | An absolute or repository-relative directory path. |
Returns
Object|null — The aggregate classified status, or null when the directory has no reportable changes.
Retrieving Diffs2
Compute a structured diff between two endpoints.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Diff options. |
fromoptional | Object | The starting endpoint. |
tooptional | Object | The ending endpoint. Endpoints may be commit, index, worktree, file, or empty descriptors. |
pathsoptional | Array<String> | Literal file or directory paths limiting the diff. |
contextoptional, default: 3 | Number | Context lines. |
ignoreWhitespaceoptional, default: false | Boolean | Ignore all whitespace. |
detectRenamesoptional, default: true | Boolean | Detect renames. |
diffFilteroptional | String | A Git diff-filter value. |
formatoptional, default: "structured" | "structured"|"patch"|"both" | Select structured files, raw patch text, or both. |
maxBytesoptional, default: 10485760 | Number | Output limit. Exceeding it rejects with ERR_GIT_DIFF_TOO_LARGE. |
signaloptional | AbortSignal | Cancellation signal. |
Returns
Promise<Object> — resolving to a frozen {schemaVersion, files, rawPatch?} object; rawPatch is present only for patch and both.
Computes gutter line diffs off the renderer thread via the git-host worker,
fetching and caching the selected baseline blob before comparing it with
the buffer. A path absent from that baseline is compared as empty text
unless skipMissingBaseline is enabled.
| Argument | Type | Description |
|---|---|---|
filePath | String | The String path relative to the repository. |
text | String | The String buffer contents to compare. |
optionsoptional, default: {} | Object | Diff options. |
baseoptional, default: "head" | "head"|"index" | The comparison baseline. |
skipMissingBaselineoptional, default: false | Boolean | Return no hunks when the baseline path is absent, while retaining additions to an existing empty file. |
signaloptional | AbortSignal | Cancellation signal. |
Returns
Promise<Array<Object>> — resolving to an Array of hunk Objects, each with oldStart, newStart, oldLines, and newLines.
Reading History3
Read paginated commit history.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | History options. |
revisionoptional, default: "HEAD" | String | Starting revision. |
allRefsoptional, default: false | Boolean | Walk every local/remote branch and tag instead of one starting revision. |
pathoptional | String | Limit history to one path and follow renames. |
limitoptional, default: 50 | Number | Page size. |
cursoroptional | Object | The nextCursor from a previous page. |
signaloptional | AbortSignal | Cancellation signal. |
Returns
Promise<Object> — resolving to a frozen {commits, hasMore, nextCursor} object. Each commit has sha, parents, author, committer, subject, and body. An unborn repository resolves to an empty page.
Read one commit with its changed-file summary.
| Argument | Type | Description |
|---|---|---|
sha | String | The String commit id or any revision expression. |
optionsoptional, default: {} | Object | Read options. |
signaloptional | AbortSignal | Cancellation signal. |
Returns
Promise<Object|null> — resolving to the commit object extended with changedFiles: [{path, originalPath, status, similarity}].
Read line-by-line blame for a file.
| Argument | Type | Description |
|---|---|---|
filePath | String | A String path, absolute or repository-relative. |
optionsoptional, default: {} | Object | Blame options. |
revisionoptional | String | Revision to blame. |
ignoreWhitespaceoptional | Boolean | Ignore whitespace-only changes when attributing a line, so a reindent does not reassign every line it touched. |
signaloptional | AbortSignal | Cancellation signal. |
Returns
Promise<Object> — resolving to a frozen {revision, lines} object where each line has line, originalLine, sha, author, summary.
Reading File Contents3
Read a file’s contents at a revision.
| Argument | Type | Description |
|---|---|---|
filePath | String | A String path, absolute or repository-relative. |
revision | String | A String revision expression. |
optionsoptional, default: {} | Object | Read options. |
encodingoptional, default: "utf8" | String | Text encoding, or "buffer" for a Buffer. |
signaloptional | AbortSignal | Cancellation signal. |
Returns
Promise<String|Buffer|null> — resolving to the contents, or null when the path does not exist at that revision.
Read a file’s staged contents directly from the repository index.
| Argument | Type | Description |
|---|---|---|
filePath | String | A String path, absolute or repository-relative. |
optionsoptional, default: {} | Object | Read options. |
encodingoptional, default: "utf8" | String | Text encoding, or "buffer" for a Buffer. |
signaloptional | AbortSignal | Cancellation signal. |
Returns
Promise<String|Buffer|null> — resolving to the staged contents, or null when the path has no stage-0 index entry.
Read a blob’s contents by object id (git cat-file -p <oid>).
| Argument | Type | Description |
|---|---|---|
oid | String | A String blob object id. |
optionsoptional, default: {} | Object | Read options. |
encodingoptional, default: "utf8" | String | Text encoding, or "buffer" for a Buffer. |
signaloptional | AbortSignal | Cancellation signal. |
Returns
Promise<String|Buffer|null> — resolving to the contents, or null when the oid does not name an object.
Checking Out2
Restore the contents of a path in the working directory and index
to the version at HEAD, via the repository operation provider
(git checkout HEAD -- <path>).
| Argument | Type | Description |
|---|---|---|
filePath | String | The String path to checkout. |
Returns
Promise<Boolean> — resolving to a Boolean that’s true on success.
Checks out a branch in your repository via the repository operation provider.
| Argument | Type | Description |
|---|---|---|
reference | String | The String reference to checkout. |
createoptional, default: false | Boolean | A Boolean value which, if true creates the new reference if it doesn’t exist. |
Returns
Promise<Boolean> — resolving to a Boolean that’s true on success.
Extended API
GrammarRegistrysrc/grammar-registry.js:29
This class holds the grammars used for tokenizing.
An instance of this class is always available as the lumine.grammars global.
Language Modes6
Set a TextBuffer’s language mode based on its path and content, and continue to update its language mode as grammars are added or updated, or the buffer’s file path changes. Repeated calls share one maintenance setup; each returned disposable releases one lease.
| Argument | Type | Description |
|---|---|---|
buffer | TextBuffer | The TextBuffer whose language mode will be maintained. |
Returns
Disposable — that can be used to stop updating the buffer’s language mode.
Force a TextBuffer to use a different grammar than the one that would otherwise be selected for it.
| Argument | Type | Description |
|---|---|---|
buffer | TextBuffer|TextEditor | The TextBuffer whose grammar will be set. |
languageId | String|null | The String id of the desired language. Pass null to remove an override and restore automatic selection. |
Returns
Boolean — that indicates whether the language was successfully found.
Limit a buffer’s root language to source ranges without changing its text.
The policy follows the buffer across grammar changes and is not serialized.
The provider runs before each parse; return null to parse the whole buffer,
or an empty array to parse no source. Ranges use buffer coordinates.
| Argument | Type | Description |
|---|---|---|
buffer | TextBuffer|TextEditor | The TextBuffer whose root language is constrained. |
provider | Object | A portable policy with an absolute module path, exported method name and cloneable params. The method receives an immutable text snapshot and params, and synchronously returns ranges or null. Inline parser tests may also supply a function receiving the buffer. |
Returns
Disposable — Removes this policy and restores full-buffer parsing, unless a newer policy replaced it.
Force a TextBuffer to use a different grammar than the one that would otherwise be selected for it.
| Argument | Type | Description |
|---|---|---|
buffer | TextBuffer|TextEditor | The TextBuffer whose grammar will be set. |
grammar | TreeSitterGrammar|Object | The desired TreeSitterGrammar, or the null grammar sentinel. |
Returns
Boolean — that indicates whether the assignment was successful
Get the languageId that has been explicitly assigned to
the given buffer, if any.
| Argument | Type | Description |
|---|---|---|
buffer | TextBuffer |
Returns
String|null|undefined — The explicit language id, including text.plain.null-grammar for None, or null/undefined when no id is assigned.
Remove any language mode override that has been set for the given TextBuffer. This will assign to the buffer the best language mode available.
| Argument | Type | Description |
|---|---|---|
buffer | TextBuffer | The TextBuffer. |
Grammar Selection3
Select a grammar for the given file path and file contents.
This picks the best match by checking the file path and contents against each grammar.
| Argument | Type | Description |
|---|---|---|
filePathoptional | String|null | A String file path. |
fileContentsoptional | String | A String of text for the file path. |
Returns
TreeSitterGrammar|Object — a Tree-sitter grammar or the null grammar sentinel.
Select a grammar for a file on disk without synchronously reading it.
Scoring yields between grammars when its current slice exceeds 5 ms.
Missing files are scored by path alone. Cancellation rejects with an
AbortError and can be used to discard work when its consumer unloads.
| Argument | Type | Description |
|---|---|---|
filePath | String | The file path to read and match. |
optionsoptional, default: {} | Object | Selection options. |
signaloptional | AbortSignal | Cancels reading and scoring. |
Returns
Promise<TreeSitterGrammar|Object> — Resolves to the best grammar or the null grammar sentinel.
Evaluates a grammar’s fitness for use for a certain file.
By analyzing the file’s extension and contents — plus other criteria, like the user’s configuration — Lumine will assign a score to this grammar that represents how suitable it is for the given file.
Ultimately, whichever grammar scores highest for this file will be used to highlight it.
| Argument | Type | Description |
|---|---|---|
grammar | TreeSitterGrammar|Object | A given TreeSitterGrammar, or the null grammar sentinel. |
filePathoptional | String|null | A String path to the file. |
contentsoptional | String | The String contents of the file. |
Returns
Number
Event Subscription4
Invoke the given callback when a grammar is added to the registry.
| Argument | Type | Description |
|---|---|---|
callback | Function | to call when a grammar is added. |
grammar | TreeSitterGrammar | that was added. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a registered grammar is updated, such as when an injection point is added to it.
| Argument | Type | Description |
|---|---|---|
callback | Function | to call when a grammar is updated. |
grammar | TreeSitterGrammar | that was updated. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Register a syntax-only module in each parser owner. The module exports a factory receiving this registry followed by serializable arguments, and returns a disposable registration. It must not access renderer objects.
| Argument | Type | Description |
|---|---|---|
modulePath | String | Absolute path to the package’s syntax module. |
optionsoptional, default: {} | Object | |
methodoptional | String | Named factory export; omit for the default export. |
argsoptional | Array | Serializable factory arguments. |
Returns
Disposable — Removes this module and its injection points.
Invoke the given callback when a grammar is removed from the registry, which happens whenever the package that provides it deactivates.
| Argument | Type | Description |
|---|---|---|
callback | Function | to call when a grammar is removed. |
grammar | TreeSitterGrammar | that was removed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Language Injections1
Specify a type of syntax node that may embed other languages.
| Argument | Type | Description |
|---|---|---|
grammarId | String | The id of the parent language. |
injectionPoint | Object | Injection behavior. |
type | String | The syntax-node type that may embed other languages. |
language | String|Function | A language name declared by the target Tree-sitter grammar in injectionNames, or a function called with a matching syntax node that returns one. Prefer a string for a fixed language so operations can skip irrelevant injections before scanning. Matching ignores surrounding whitespace and letter case. |
content | Function | Called with a matching syntax node and returns the node or nodes containing embedded source. The nodes become visible buffer ranges for the injected parser. |
combinedoptional, default: false | Boolean|Function | Share child language layers for matching owners and their resolved language name. Defaults to false. A function is called with the owner node and returns whether that node can share a layer; false keeps its context independent. Without a member limit the owners form one shared document. Individual ranges remain indexed so unrelated edits do not rescan every owner. |
combinedMaxMembersoptional | Number | An optional positive safe integer limiting the number of owners in a combined child layer. Omit it for an unbounded combined document. Set a limit only when each owner remains correct at a group boundary. An owner returning several content nodes counts as one member and stays in one layer. |
includeChildrenoptional, default: false | Boolean | A Boolean that indicates whether the children (and, in fact, all descendants) of the nodes returned by content should be included in the injection’s buffer range(s). Defaults to false. |
excludeChildrenLinesoptional, default: false | Boolean | When includeChildren is false, subtract the complete physical rows occupied by each direct child, clipped to the content node and buffer. Overlapping row exclusions are merged. Defaults to false. |
newlinesBetweenoptional, default: false | Boolean | A Boolean that indicates whether each node returned from content should be separated by at least one newline character so that the parser understands them to be logically separated. Embedded languages like ERB and EJS need this. Defaults to false. |
languageScopeoptional | String|null|Function | A String or Function that returns the desired scope name to apply to each of the injection’s buffer ranges. Defaults to the injected grammar’s own language scope — e.g., source.js for the JavaScript grammar. Set to null if the language scope should be omitted. If a Function, will be called with the grammar instance as an argument, and should return either a String or null. |
coverShallowerScopesoptional, default: false | Boolean | A Boolean that indicates whether this injection should prevent shallower layers (including the layer that created this injection) from adding scopes within any of this injection’s buffer ranges. Useful for injecting languages into themselves — for instance, injecting Rust into Rust macro definitions. |
includeAdjacentWhitespaceoptional, default: false | Boolean | A Boolean that indicates whether the injection’s buffer range(s) should include whitespace that occurs between two adjacent ranges. Defaults to false. When true, if two consecutive injection buffer ranges are separated only by whitespace, those ranges will be consolidated into one range along with that whitespace. |
node | SyntaxNode | The syntax node matching the injection type. |
node | SyntaxNode | The matching syntax node whose content is requested. |
Returns
Disposable — A disposable that removes the injection point.
Loading Grammars4
Read a grammar asynchronously and add it to the registry.
| Argument | Type | Description |
|---|---|---|
grammarPath | String | A String absolute file path to a grammar file. |
callback | Function | A Function to call when loaded with the following arguments: |
error | Error|null | An Error, may be null. |
grammaroptional | TreeSitterGrammar|undefined | A TreeSitterGrammar or undefined if an error occurred. |
Returns
void
Read a grammar synchronously and add it to this registry.
| Argument | Type | Description |
|---|---|---|
grammarPath | String | A String absolute file path to a grammar file. |
Returns
Read a grammar asynchronously but don’t add it to the registry.
| Argument | Type | Description |
|---|---|---|
grammarPath | String | A String absolute file path to a grammar file. |
callbackoptional | Function | A Function to call when read with the following arguments: |
error | Error|null | An Error, may be null. |
grammaroptional | TreeSitterGrammar|undefined | A TreeSitterGrammar or undefined if an error occurred. |
Returns
void
Read a grammar synchronously but don’t add it to the registry.
| Argument | Type | Description |
|---|---|---|
grammarPath | String | A String absolute file path to a grammar file. |
Returns
Grammars1
Get all the grammars in this registry.
Returns
Array<TreeSitterGrammar> — Registered grammar instances; excludes the null sentinel and unloaded stubs.
Extended API
Guttersrc/gutter.js:13
Represents a gutter within a TextEditor.
See TextEditor#addGutter for information on creating a gutter.
Lifecycle1
Destroys the gutter.
Returns
void
Throws
Error — When called on the built-in line-number gutter.
Event Subscription2
Calls your callback when the gutter’s visibility changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
gutter | Gutter | The gutter whose visibility changed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when the gutter is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Visibility3
Hide the gutter.
Returns
void
Show the gutter.
Returns
void
Determine whether the gutter is visible.
Returns
Boolean
Decorations1
Add a decoration that tracks a DisplayMarker. When the marker moves, is invalidated, or is destroyed, the decoration will be updated to reflect the marker’s state.
Arguments
| Argument | Type | Description |
|---|---|---|
marker | DisplayMarker | A DisplayMarker you want this decoration to follow. |
options | Object | An Object representing the decoration. It is passed to TextEditor#decorateMarker as its options argument and so supports all options documented there. |
typeoptional | String | Caveat: set to 'line-number' if this is the line-number gutter, 'gutter' otherwise. This cannot be overridden. |
Returns
Decoration — object
Extended API
HistoryManagersrc/history-manager.js:13
History manager for remembering which projects have been opened.
An instance of this class is always available as the lumine.history global.
The project history is used to populate recent project lists.
Recent Projects2
Obtain a list of previously opened projects.
Returns
Array<Object> — of detached HistoryProject objects, most recent first. Their paths and dates can be changed without modifying history.
Clear all projects from the history.
Note: This is not a privacy function - other traces will still exist, e.g. window state.
Returns
Promise — that resolves when the history has been successfully cleared.
Event Subscription1
Invoke the given callback when the list of projects changes.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Essential API
IconRegistrysrc/icon-registry.js:384
The single source of every icon the editor renders — file-type
icons, the semantic names pane items return from getIconName(), and LSP
symbol kinds.
Full description
Providers form a priority chain. Each is asked in turn, and returning null
means “not mine, ask the next one”; core’s octicon mapping is the always
present provider at the bottom, so every target resolves. Returning
Icon.none() is not the same as null — it stops the chain with “no icon
here”.
An instance of this class is always available as the lumine.icons global.
Cache Invalidation1
Drop cached answers and repaint what they were rendered into.
scope is undefined or null for everything, or an object narrowing it to
{types}, {paths}, {pathPrefixes}, {names}, or {kinds}. Narrowing
matters: a provider that resolves one file extension asynchronously should
repaint the rows showing that extension, not every row in the tree.
| Argument | Type | Description |
|---|---|---|
scopeoptional | Object|null | Omit, pass null, or pass an empty object to invalidate every icon. |
typesoptional | Array<String> | Target types: path, name, or kind. |
pathsoptional | Array<String> | Exact filesystem paths. |
pathPrefixesoptional | Array<String> | Filesystem prefixes and their descendants. |
namesoptional | Array<String> | Semantic names. |
kindsoptional | Array<String> | Symbol kind names. |
Returns
void
Event Subscription1
Invoke callback when any icon may have changed.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
scope | Object|null | The scope passed to invalidate; null means all icons may have changed. |
Returns
Disposable — Dispose to unsubscribe.
Experimental API
InputDialogsrc/input-dialog.js:61
Detached query-dialog model with a mini editor and optional custom DOM content.
Full description
InputDialog owns query state, messages, sources, commands and actions without any list semantics. SelectList extends it with items, filtering, and selection. The model creates its renderer only when #getElement is first called and never inserts that element into the DOM. Use Workspace#addInputDialog when the dialog needs a modal host.
The dialog shows one message at a time, from three sources in
precedence order: loadingMessage (work in flight), then status (an
episodic overlay — a validation failure, a warning, a confirmation), then
infoMessage (the resting line: a prompt, a help text, a stat line). The
overlay never destroys the resting line, so clearing a status restores it
with nothing to save and put back.
Custom DOM can be hosted through headerElement (above the query editor)
and contentElement (below the messages).
Query processing is limited to 65536 UTF-16 units by default. Set maxQueryLength from 1 to 1048576 for a different protocol budget. Oversized drafts remain intact; sources and actions resume after the query fits again.
The query is the dialog’s own state. A modal host decides when a new session resets it, preserves it across modal-flow steps, and restores a previous session on request.
DOM Access1
Return the root element rendered for this dialog.
Returns
HTMLElement
Lifecycle2
Return whether this dialog has been destroyed.
Returns
Boolean
Destroys the dialog and cleans up resources.
Returns
Promise<void>
Actions9
Request the host’s disposition after a conditionally accepted action. Prefer an action descriptor’s disposition when completion follows its handler. Pass the captured action context when acceptance precedes asynchronous work.
| Argument | Type | Description |
|---|---|---|
disposition | String | close, complete, stay or push. |
payloadoptional, default: {} | Object | Action metadata. |
contextoptional | Object | The context captured when the action began. |
Returns
void
Return the complete declared action catalogue.
Returns
Array<Object>
Replace the action catalogue.
| Argument | Type | Description |
|---|---|---|
actions | Array|Object|null | Descriptors, [command, descriptor] pairs, or a command-keyed map; null clears the catalogue. |
Returns
Add an action and return a Disposable that removes it.
| Argument | Type | Description |
|---|---|---|
action | Array|Object | One descriptor, an array of descriptors/pairs, or a command-keyed map. |
command | String | Command name when passing one descriptor. |
context | String | item or dialog; item actions require a current item. |
disposition | String | close, complete, stay or push after success. SelectList’s keep-open mode adapts close; complete always ends the choice. |
dispatchoptional, default: "local" | String | Dispatch on local, workspace or opener. |
whenoptional, default: true | Boolean|Function | Synchronous predicate controlling applicability. |
enabledoptional, default: true | Boolean|Function | Synchronous predicate controlling execution. |
disabledReasonoptional | String|Function | Reason shown for a disabled action. |
primaryoptional, default: false | Boolean|Function | Make this the sole primary action for the current context. |
recordsRecentoptional, default: false | Boolean|Function | Record the current item after successful execution. |
confirmoptional | Boolean|Object|Function | Optional confirmation options, or a function receiving the context and AbortSignal. |
groupoptional | String | Group actions in declaration order. |
orderoptional, default: 0 | Number | Sort within the group. |
toneoptional, default: "normal" | String | normal or danger. |
Returns
Return whether an action applies to the current context.
| Argument | Type | Description |
|---|---|---|
contextoptional, default: this.getActionContext() | Object | An action context; defaults to the current dialog context. |
dialogoptional | InputDialog | The dialog model. |
itemoptional | * | The selected item, or null for an input dialog. |
itemIdoptional | * | The selected item identity, if any. |
queryoptional | String | Raw query text. |
parsedQueryoptional | Object | Parsed {text, data} query. |
openeroptional | Element|null | The element that opened the modal host. |
sourceoptional | String | The action invocation source. |
sessionIdoptional | Number | Captured modal session identity. |
keepOpenoptional | Boolean | SelectList’s captured completion mode. |
itemsoptional | Array<*> | Source items supplied by SelectList. |
Returns
Boolean
Return evaluated actions for the current context.
| Argument | Type | Description |
|---|---|---|
contextoptional, default: this.getActionContext() | Object | An action context; defaults to the current dialog context. |
dialogoptional | InputDialog | The dialog model. |
itemoptional | * | The selected item, or null for an input dialog. |
itemIdoptional | * | The selected item identity, if any. |
queryoptional | String | Raw query text. |
parsedQueryoptional | Object | Parsed {text, data} query. |
openeroptional | Element|null | The element that opened the modal host. |
sourceoptional | String | The action invocation source. |
itemsoptional | Array<*> | Source items supplied by SelectList. |
Returns
Array<Object>
Return whether any action, or one named action, is currently running.
| Argument | Type | Description |
|---|---|---|
commandoptional | String | Check one action command, or omit to check all actions. |
Returns
Boolean
Run a declared action through the shared action runner.
| Argument | Type | Description |
|---|---|---|
command | String | A declared action command. |
optionsoptional, default: {} | Object | Invocation options. |
sourceoptional, default: "api" | String | How the action was requested. |
contextoptional, default: null | Object|null | Override the current action context. |
Returns
Promise<Object> — An action completion record with command, action, context, signal and status; optional reason/value/error describe the outcome. Unknown commands throw synchronously; action failures reject.
Confirms the dialog with the current query through its primary action, or
emits onDidConfirm when no primary action is declared.
Returns
Promise<Object>|undefined — The primary action completion promise, or undefined after emitting onDidConfirm.
Event Subscription5
Invoke a callback when the query changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | The observer. |
event | Object | |
dialog | InputDialog | |
query | String | |
parsedQuery | Object | Frozen {text, data} record. |
Returns
Disposable — Dispose to unsubscribe.
Invoke a callback when confirmation has no primary action.
| Argument | Type | Description |
|---|---|---|
callback | Function | The observer. |
event | Object | |
dialog | InputDialog | |
query | String |
Returns
Disposable — Dispose to unsubscribe.
Invoke a callback during dialog destruction.
| Argument | Type | Description |
|---|---|---|
callback | Function | The observer. |
Returns
Disposable — Dispose to unsubscribe.
Invoke a callback when an action starts.
| Argument | Type | Description |
|---|---|---|
callback | Function | The observer. |
event | Object | |
command | String | |
action | Object | |
context | Object | |
signal | AbortSignal |
Returns
Disposable — Dispose to unsubscribe.
Invoke a callback when an action finishes.
| Argument | Type | Description |
|---|---|---|
callback | Function | The observer. |
event | Object | |
command | String | |
action | Object | |
context | Object | |
signal | AbortSignal | |
status | String | success, disabled, unavailable, cancelled, aborted, or error. |
reasonoptional | * | |
valueoptional | * | The dispatched command result. |
erroroptional | * |
Returns
Disposable — Dispose to unsubscribe.
Query11
Clears the query editor text.
Returns
void
Return the query editor placeholder.
Returns
String
Set the query editor placeholder.
| Argument | Type | Description |
|---|---|---|
placeholderText | String | Placeholder shown in the mini query editor. |
Returns
Promise<void>
Return the complete raw query text. Throws ERR_DIALOG_QUERY_TOO_LARGE when processing is unavailable; the draft remains accessible through the query editor snapshot.
Returns
String
Return query availability and UTF-16 length metadata without reading text.
Returns
Object — A frozen {available, length, maxLength} record.
Set the query text or immutable snapshot and optionally select it.
| Argument | Type | Description |
|---|---|---|
query | * | Query text or an immutable snapshot; other values are converted to strings and null clears it. |
optionsoptional, default: {} | Object | Selection options. |
selectoptional, default: false | Boolean | Select the complete query after setting it. |
Returns
Promise<void>
Clear the query text.
Returns
Promise<void>
Select the complete query.
Returns
void
Return the full TextEditor model used for the query.
Returns
Return the parsed query text and metadata.
Returns
Object — A frozen {text, data} record; InputDialog uses the raw query and null data.
Use the active editor’s last selection as the query when it occupies one buffer line and contains at most 4,096 UTF-16 units. Otherwise keep the current query without reading the selection’s text.
Returns
Boolean
Asynchronous Sources4
Return the configured asynchronous source, or null.
Returns
Object|null
Replace the asynchronous source and reload it when open.
| Argument | Type | Description |
|---|---|---|
source | Object|null | Replacement source, or null to disable loading. |
mode | String | snapshot loads on opening/reload; query also reloads after query changes. |
load | Function | Receives a load context and may return a publication or a promise. InputDialog accepts option objects; SelectList also accepts item arrays. Undefined publishes no final result. |
context | Object | The query, parsedQuery, AbortSignal signal, and publish(value) callback. publish returns Promise<Boolean> indicating whether the progressive value was applied. |
debounceMsoptional, default: 100 | Number | Delay for query-mode reloads in milliseconds. |
query | String | Raw query text. |
parsedQuery | Object | Frozen {text, data} query metadata. |
signal | AbortSignal | Aborted when the load is superseded, cancelled or destroyed. |
publish | Function | Publish progressive results; receives an option object or, for SelectList, an item array. |
loadingMessageoptional | * | Loading message content; defaults to Loading…. |
Returns
Promise<void>
Reload the configured source immediately.
Returns
Promise<void> — Resolves after loading settles, including for a detached model. Loader failures appear as status messages.
Return whether source work or its debounce is pending.
Returns
Boolean
Configuration1
Update one or more documented dialog options.
| Argument | Type | Description |
|---|---|---|
propsoptional, default: {} | Object | Partial dialog options. SelectList also accepts the list options described by Workspace#addSelectList. |
queryoptional | * | Replace the query text or immutable snapshot. |
maxQueryLengthoptional, default: 65536 | Number | Query protocol limit in UTF-16 units, from 1 to 1048576. Oversized drafts remain in the editor while processing and actions are unavailable. |
selectQueryoptional | Boolean | Select or clear the query selection. |
statusoptional | Object|null | Status as accepted by setStatus. |
infoMessageoptional | * | Resting message content. |
loadingMessageoptional | * | Loading message content. |
loadingBadgeoptional | * | Loading badge content. |
placeholderTextoptional | String | Query editor placeholder. |
headerElementoptional | HTMLElement|null | Caller-owned header content. |
contentElementoptional | HTMLElement|null | Caller-owned body content. |
actionsoptional | Array|Object|null | Action catalogue as accepted by setActions. |
commandsoptional | Object|null | Command-keyed functions or descriptors with a didDispatch function. |
sourceoptional | Object|null | Asynchronous source as accepted by setSource. |
Returns
Promise<void> — Resolves after the renderer update. Source loading triggered by this update settles independently.
Custom Content4
Return the caller-owned header element.
Returns
HTMLElement|null
Replace the caller-owned header element.
| Argument | Type | Description |
|---|---|---|
headerElement | HTMLElement|null | Caller-owned DOM content, or null to remove it. |
Returns
Promise<void>
Return the caller-owned content element.
Returns
HTMLElement|null
Replace the caller-owned content element.
| Argument | Type | Description |
|---|---|---|
contentElement | HTMLElement|null | Caller-owned DOM content, or null to remove it. |
Returns
Promise<void>
Experimental API
InputDialogHostsrc/input-dialog-host.js:24
Hosts a detached InputDialog model in a lazily-created modal panel. The host owns visibility, focus, modal-flow state and session lifecycle; the complete dialog model remains available through #getModel.
Model and Panel2
Return the complete detached dialog model.
Returns
Materialize and return the underlying modal Panel. Calling this method is the first point at which the host registers UI with the workspace.
Returns
Visibility5
Show the modal host and begin a model session.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
queryoptional | String | Opening query; omitted to reset it. |
selectQueryoptional, default: true | Boolean | Whether to select the opening query. |
crumboptional | String|Boolean | Modal-flow breadcrumb for this opening. |
Returns
Promise<void>
Hide the modal without emitting cancellation.
Returns
void
Hide a visible host or show a hidden one.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | Opening options passed to #show. |
Returns
Promise<void>|undefined
Dismiss the modal and emit a cancellation event.
| Argument | Type | Description |
|---|---|---|
reasonoptional, default: "api" | String | Machine-readable cancellation reason. |
Returns
void
Return whether this host’s modal panel is visible.
Returns
Boolean
Lifecycle2
Return whether this host has been destroyed.
Returns
Boolean
Destroy the host and its panel. A model created from options is destroyed with it; a model passed to the factory remains alive.
Returns
Promise<void>
Focus and Query2
Focus the model’s query editor.
Returns
void
Restore and select the query remembered from the previous session.
Returns
Boolean
Actions1
Open the shared picker for actions available on the model.
Returns
Promise<Boolean>
Event Subscription6
Invoke a callback when the host’s visibility changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
host | InputDialogHost | |
model | InputDialog | |
visible | Boolean |
Returns
Disposable — Dispose to unsubscribe.
Invoke a callback when a fresh modal session opens.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
host | InputDialogHost | |
model | InputDialog |
Returns
Disposable — Dispose to unsubscribe.
Invoke a callback when a suspended modal-flow session resumes.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
host | InputDialogHost | |
model | InputDialog |
Returns
Disposable — Dispose to unsubscribe.
Invoke a callback when a modal session fully hides.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
host | InputDialogHost | |
model | InputDialog |
Returns
Disposable — Dispose to unsubscribe.
Invoke a callback when the host is cancelled.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
host | InputDialogHost | |
model | InputDialog | |
reason | String |
Returns
Disposable — Dispose to unsubscribe.
Invoke a callback when the host is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
host | InputDialogHost | |
model | InputDialog |
Returns
Disposable — Dispose to unsubscribe.
Extended API
KeymapManagersrc/keymap-manager.js:94
Allows commands to be associated with keystrokes in a
context-sensitive way. You can access a global instance of this
object via lumine.keymaps.
Full description
Key bindings are plain JavaScript objects containing CSS selectors as their top level keys, then keystroke patterns mapped to commands.
{
".workspace": {
"ctrl-l": "package:do-something",
"ctrl-z": "package:do-something-else"
},
".mini.editor": {
"enter": "core:confirm"
}
}
When a keystroke sequence matches a binding in a given context, a custom DOM event with a type based on the command is dispatched on the target of the keyboard event.
To match a keystroke sequence, the keymap starts at the target element for the keyboard event. It looks for key bindings associated with selectors that match the target element. If multiple match, the most specific is selected. If there is a tie in specificity, the most recently added binding wins. If no bindings are found for the events target, the search is repeated again for the target’s parent node and so on recursively until a binding is found or we traverse off the top of the document.
When a binding is found, its command event is always dispatched on the
original target of the keyboard event, even if the matching element is higher
up in the DOM. In addition, .preventDefault() is called on the keyboard
event to prevent the browser from taking action. .preventDefault is only
called if a matching binding is found.
Command event objects have a non-standard method called .abortKeyBinding().
If your command handler is invoked but you programmatically determine that no
action can be taken and you want to allow other bindings to be matched, call
.abortKeyBinding() on the event object. An example of where this is useful
is binding snippet expansion to tab. If snippets:expand is invoked when
the cursor does not follow a valid snippet prefix, we abort the binding and
allow tab to be handled by the default handler, which inserts whitespace.
Multi-keystroke bindings are possible. If a sequence of one or more keystrokes partially matches a multi-keystroke binding, the keymap enters a pending state. The pending state is terminated on the next keystroke, or after #getPartialMatchTimeout milliseconds has elapsed. When the pending state is terminated via a timeout or a keystroke that leads to no matches, the longest ambiguous bindings that caused the pending state are temporarily disabled and the previous keystrokes are replayed. If there is ambiguity again during the replay, the next longest bindings are disabled and the keystrokes are replayed again.
Class Methods1
Create a keydown DOM event for testing purposes.
| Argument | Type | Description |
|---|---|---|
key | String | The key or keyIdentifier of the event. For example, 'a', '1', 'escape', 'backspace', etc. |
optionsoptional | Object | An Object containing any of the following: |
ctrloptional, default: false | Boolean | A Boolean indicating the ctrl modifier key |
altoptional, default: false | Boolean | A Boolean indicating the alt modifier key |
shiftoptional, default: false | Boolean | A Boolean indicating the shift modifier key |
cmdoptional, default: false | Boolean | A Boolean indicating the cmd modifier key |
whichoptional | Number | A Number indicating which value of the event. See the docs for KeyboardEvent for more information. |
targetoptional | Element | The target element of the event. |
Returns
KeyboardEvent — The constructed keydown event.
Construction and Destruction3
Create a new KeymapManager.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | An Object containing properties to assign to the keymap. You can pass custom properties to be used by extension methods. The following properties are also supported: |
defaultTargetoptional | Element | This will be used as the target of events whose target is document.body to allow for a catch-all element when nothing is focused. |
Clear all registered key bindings and enqueued keystrokes. For use in tests.
Unwatch all watched paths.
Event Subscription4
Invoke the given callback when one or more keystrokes completely match a key binding.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when keystrokes match a binding. |
event | Object | with the following keys: |
keystrokes | String | of keystrokes that matched the binding. |
binding | KeyBinding | that the keystrokes matched. |
keyboardEventTarget | Element | DOM element that was the target of the most recent keyboard event. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when one or more keystrokes partially match a binding.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when keystrokes partially match a binding. |
event | Object | with the following keys: |
keystrokes | String | of keystrokes that matched the binding. |
partiallyMatchedBindings | Array<KeyBinding> | The bindings partially matched by the keystrokes. |
keyboardEventTarget | Element | DOM element that was the target of the most recent keyboard event. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when one or more keystrokes fail to match any bindings.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when keystrokes fail to match any bindings. |
event | Object | with the following keys: |
keystrokes | String | of keystrokes that matched the binding. |
keyboardEventTarget | Element | DOM element that was the target of the most recent keyboard event. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a keymap file cannot be read or watched.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when a keymap file is unloaded. |
event | Error|Object | A read error, or a {path, error} object for a watcher failure. |
messageoptional | String | The message of a direct read error. |
stackoptional | String | The stack of a direct read error. |
pathoptional | String | The keymap path when the watcher fails. |
erroroptional | Error | The watcher failure. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Adding and Removing Bindings2
Construct KeyBindings from an object grouping them by CSS selector.
| Argument | Type | Description |
|---|---|---|
source | String | A String (usually a path) uniquely identifying the given bindings so they can be removed later. |
keyBindingsBySelector | Object | Bindings grouped by CSS selector, with each value mapping keystroke patterns to commands. |
priorityoptional, default: 0 | Number | A Number used to sort keybindings which have the same specificity. Defaults to 0. |
throwOnInvalidSelectoroptional, default: true | Boolean | Whether invalid selectors should throw. |
Returns
Array<KeyBinding> — The constructed bindings.
Add sets of key bindings grouped by CSS selector.
| Argument | Type | Description |
|---|---|---|
source | String | A String (usually a path) uniquely identifying the given bindings so they can be removed later. |
keyBindingsBySelector | Object | Bindings grouped by CSS selector, with each value mapping keystroke patterns to commands. |
priorityoptional, default: 0 | Number | A Number used to sort keybindings which have the same specificity. Defaults to 0. |
throwOnInvalidSelectoroptional, default: true | Boolean | Whether invalid selectors should throw. |
Returns
Disposable — A disposable that removes the bindings.
Accessing Bindings2
Get all current key bindings.
Returns
Array<KeyBinding> — of KeyBindings.
Get the key bindings for a given command and optional target.
| Argument | Type | Description |
|---|---|---|
paramsoptional | Object | An Object whose keys constrain the binding search: |
keystrokesoptional | String | A String representing one or more keystrokes, such as ‘ctrl-x ctrl-s’ |
commandoptional | String | A String representing the name of a command, such as ‘editor:backspace’ |
targetoptional | Element | An optional DOM element constraining the search. If this parameter is supplied, the call will only return bindings that can be invoked by a KeyboardEvent originating from the target element. |
Returns
Array<KeyBinding> — of key bindings.
Managing Keymap Files2
Load the key bindings from the given path.
| Argument | Type | Description |
|---|---|---|
bindingsPath | String | A keymap file or directory. Directories load every contained JSON or JSONC keymap. |
optionsoptional | Object | An Object containing the following optional keys: |
watchoptional | Boolean | If true, the keymap will also reload the file at the given path whenever it changes. This option cannot be used with directory paths. |
priorityoptional | Number | A Number used to sort keybindings which have the same specificity. |
Cause the keymap to reload the key bindings file at the given path whenever it changes.
This method doesn’t perform the initial load of the key bindings file. If
that’s what you’re looking for, call #loadKeymap with watch: true.
| Argument | Type | Description |
|---|---|---|
filePath | String | The keymap file to watch. |
optionsoptional | Object | An Object containing the following optional keys: |
priorityoptional | Number | A Number used to sort keybindings which have the same specificity. |
Managing Keyboard Events6
Dispatch a custom event associated with the matching key binding for
the given KeyboardEvent if one can be found.
If a matching binding is found on the event’s target or one of its
ancestors, .preventDefault() is called on the keyboard event and the
binding’s command is emitted as a custom event on the matching element.
If the matching binding’s command is ‘native!’, the method will terminate
without calling .preventDefault() on the keyboard event, allowing the
browser to handle it as normal.
If the matching binding’s command is ‘unset!’, the search will continue from the current element’s parent.
If the matching binding’s command is ‘abort!’, the search will terminate without dispatching a command event.
If the event’s target is document.body, it will be treated as if its
target is .defaultTarget if that property is assigned on the keymap.
| Argument | Type | Description |
|---|---|---|
event | KeyboardEvent | A keydown or keyup KeyboardEvent. |
paramoptional | Object | Internal event replay options; omit for ordinary keyboard events. |
replayoptional, default: false | Boolean | Process a replay without arming a new chord timeout. |
disabledBindingsoptional | Array<KeyBinding> | Bindings excluded during replay. |
Translate a keydown event to a keystroke string.
| Argument | Type | Description |
|---|---|---|
event | KeyboardEvent | A KeyboardEvent of type ‘keydown’ |
Returns
String — describing the keystroke.
Determine whether an iframe bridge should relay a pending chord event for its host target. This query does not dispatch, prevent default or advance matching state. Relay wrong suffixes too so they can end a pending chord; ordinary editable input stays native when this returns false. A retained keyup rule only requests its next matching keyup, even after a timeout.
| Argument | Type | Description |
|---|---|---|
event | KeyboardEvent | A keydown or keyup KeyboardEvent from the embedded document. |
optionsoptional, default: {} | Object | |
targetoptional | HTMLElement | Stable host element used when relaying events. Defaults to event.target. |
Returns
Boolean — Whether this event belongs to that target’s pending keyboard sequence.
Customize translation of raw keyboard events to keystroke strings. This API is useful for working around Chrome bugs or changing how the editor resolves certain key combinations. If multiple resolvers are installed, the most recently-added resolver returning a string for a given keystroke takes precedence.
| Argument | Type | Description |
|---|---|---|
resolver | String | A Function that returns a keystroke String and is called with an object containing the following keys: |
keystroke | String | The currently resolved keystroke string. A falsy resolver result keeps this value. |
event | KeyboardEvent | The raw DOM 3 KeyboardEvent being resolved. See the DOM API documentation for more details. |
layoutName | String | The OS-specific name of the current keyboard layout. |
keymap | Object | An object mapping DOM 3 KeyboardEvent.code values to objects with the typed character for that key in each modifier state, based on the current operating system layout. |
Returns
Disposable — A disposable that removes the resolver.
Get the number of milliseconds allowed before pending states caused by partial matches of multi-keystroke bindings are terminated.
Returns
Number
Register iframe descendants of a pane item host for native directional pane shortcuts. The parent iframe element supplies the keymap scope; child scripts do not send commands or keyboard messages. Dispose before retaining a retired frame outside its host. Custom keystroke resolvers disable native routing because their functions cannot cross processes.
| Argument | Type | Description |
|---|---|---|
root | HTMLElement | Host element in the workspace document. |
Returns
Disposable — Registration to dispose before retiring the host.
Essential API
LayerDecorationsrc/layer-decoration.js:14
Represents a decoration that applies to every marker on a given layer. Created via TextEditor#decorateMarkerLayer.
Lifecycle2
Destroys the decoration.
Returns
void
Determine whether this decoration is destroyed.
Returns
Boolean
Properties3
Get this decoration’s properties.
Returns
Object
Set this decoration’s properties.
| Argument | Type | Description |
|---|---|---|
newProperties | Object | See TextEditor#decorateMarker for more information on the properties. The type of gutter and overlay are not supported on layer decorations. |
Returns
void
Override the decoration properties for a specific marker.
| Argument | Type | Description |
|---|---|---|
marker | DisplayMarker|Marker | The DisplayMarker or Marker for which to override properties. |
properties | Object|null | An Object containing properties to apply to this marker. Pass null to clear the override. |
Returns
void
Extended API
Markersrc/marker.js:41
Represents a buffer annotation that remains logically stationary even as the buffer changes. This is used to represent cursors, folds, snippet targets, misspelled words, and anything else that needs to track a logical location in the buffer over time.
Full description
Create markers with TextBuffer#markRange, TextBuffer#markPosition, or the corresponding MarkerLayer methods rather than constructing them directly. For screen coordinates and editor decorations, use DisplayMarker instead.
Head and Tail#
Markers always have a head and sometimes have a tail. If you think of a marker as an editor selection, the tail is the part that’s stationary and the head is the part that moves when the mouse is moved. A marker without a tail always reports an empty range at the head position. A marker with a head position greater than the tail is in a “normal” orientation. If the head precedes the tail the marker is in a “reversed” orientation.
Validity#
Markers are considered valid when they are first created. Depending on the invalidation strategy you choose, certain changes to the buffer can cause a marker to become invalid, for example if the text surrounding the marker is deleted. See TextBuffer#markRange for invalidation strategies.
Event Subscription2
Invoke the given callback when the marker is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the marker is destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the state of the marker changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the marker changes. |
event | Object | with the following keys: |
oldHeadPosition | Point | representing the former head position |
newHeadPosition | Point | representing the new head position |
oldTailPosition | Point | representing the former tail position |
newTailPosition | Point | representing the new tail position |
wasValid | Boolean | indicating whether the marker was valid before the change |
isValid | Boolean | indicating whether the marker is now valid |
hadTail | Boolean | indicating whether the marker had a tail before the change |
hasTail | Boolean | indicating whether the marker now has a tail |
oldProperties | Object | containing the marker’s custom properties before the change. |
newProperties | Object | containing the marker’s custom properties after the change. |
textChanged | Boolean | indicating whether this change was caused by a textual change to the buffer or whether the marker was manipulated directly via its public API. |
origin | String | edit, undo, redo, reload, or mixed; identifies history replay and buffer reloads independently of textChanged. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Marker Ranges10
Sets the range of the marker.
| Argument | Type | Description |
|---|---|---|
range | Range|Array<Point|Array<Number>>|Object | A Range or range-compatible Array. The range will be clipped before it is assigned. |
paramsoptional | Object | An Object with the following keys: |
reversedoptional | Boolean | indicating place the head at the earlier endpoint; omission preserves the current orientation. |
exclusiveoptional | Boolean | Keep endpoint insertions outside the marked range. Omission preserves the current exclusivity setting. |
Returns
Boolean|undefined — Whether the marker changed, or undefined when no update is attempted.
Get the head position of this marker.
Returns
Point — representing the marker’s current head position.
Get the tail position, or the head position when there is no tail.
Returns
Point — representing the marker’s current tail position. If the marker has no tail, the head position will be returned instead.
Sets the tail position of the marker. If the marker doesn’t have a tail, it will after calling this method.
| Argument | Type | Description |
|---|---|---|
position | Point|Array<Number>|Object | A Point or point-compatible Array. The position will be clipped before it is assigned. |
Returns
Boolean|undefined — Whether the marker changed, or undefined when no update is attempted.
Get the earlier endpoint of this marker.
Returns
Point — representing the start position of the marker, which could be the head or tail position, depending on its orientation.
Get the later endpoint of this marker.
Returns
Point — representing the end position of the marker, which could be the head or tail position, depending on its orientation.
Removes the marker’s tail. After calling the marker’s head position will be reported as its current tail position until the tail is planted again.
Returns
Boolean|undefined — Whether the marker changed, or undefined when no update is attempted.
Plants the marker’s tail at the current head position. After calling the marker’s tail position will be its head position at the time of the call, regardless of where the marker’s head is moved.
Returns
Boolean|undefined — Whether the marker changed, or undefined when no update is attempted.
Marker Details6
Determine whether the head precedes the tail.
Returns
Boolean — indicating whether the head precedes the tail.
Determine whether this marker has a tail.
Returns
Boolean — indicating whether the marker has a tail.
Is the marker valid?
Returns
Boolean
Is the marker destroyed?
Returns
Boolean
Determine whether insertions at the endpoints stay outside this marker.
Returns
Boolean — Whether insertions at either endpoint remain outside the marked range.
Get the invalidation strategy for this marker.
Valid values include: never, surround, overlap, inside, and touch.
Returns
String
Comparison2
Determine whether this marker has the same range and options as another.
| Argument | Type | Description |
|---|---|---|
other | Marker | other marker |
Returns
Boolean — indicating whether this marker is equivalent to another marker, meaning they have the same range and options.
Compares this marker to another based on their ranges.
| Argument | Type | Description |
|---|---|---|
other | Marker |
Returns
Number — The range ordering: earlier starts sort first, then longer ranges.
Properties2
Get the custom properties associated with this marker.
Returns
Object — containing any custom properties associated with the marker.
Merges an Object containing new properties into the marker’s
existing properties.
| Argument | Type | Description |
|---|---|---|
properties | Object |
Returns
Boolean|undefined — Whether the marker changed, or undefined when no update is attempted.
Lifecycle2
Creates and returns a new Marker with the same properties as this
marker.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Marker options and custom properties to override in the copy. |
Returns
Marker — A new marker on the same layer.
Destroy the marker and notify its destruction observers.
| Argument | Type | Description |
|---|---|---|
suppressMarkerLayerUpdateEventsoptional, default: false | Boolean | Suppress this destruction’s marker-layer update notification. |
Returns
void
Range Queries3
Determine whether this marker intersects a buffer row.
| Argument | Type | Description |
|---|---|---|
row | Number | A row Number |
Returns
Boolean — indicating whether the marker’s range intersects the given row.
Experimental API
MarkerLayersrc/marker-layer.js:23
A container for a related set of markers.
Lifecycle4
Create a copy of this layer with markers in the same state and locations.
Returns
MarkerLayer — A new layer on the same buffer, including the custom range tracker.
Destroy this layer.
Returns
void
Remove all markers from this layer.
Returns
void
Determine whether this layer has been destroyed.
Returns
Boolean — Whether this layer has been destroyed.
Marker Layer Details1
Get the role assigned to this marker layer, such as selections.
Returns
String|undefined — The role assigned when the layer was created, if any.
Range Tracking2
Set custom range tracking for this layer, or pass null to restore default
tracking. The callback receives sorted {id, range} entries for markers
touching an edit, with their pre-edit ranges, and {oldRange, newRange, newText} describing the edit. It returns {id, range} entries in the new
coordinate space; omitted entries and null ranges invalidate markers.
Normal marker invalidation strategies still apply independently.
The callback must be synchronous and must not mutate the buffer or markers. Exceptions and invalid results invalidate affected markers and are logged; they do not interrupt the buffer edit. Ranges are not clipped, because a reload can apply intermediate edits after installing the final buffer text. The callback is retained by #copy, but is not serialized: reattach it after deserialization. Untouched markers continue to use the marker index.
| Argument | Type | Description |
|---|---|---|
callbackoptional | Function|null | A range tracker, or null to disable it. |
Get the custom tracker used for buffer-coordinate ranges.
Returns
Function|null — The custom range tracker, or null when default tracking is used.
Marker Creation2
Create a marker with the given buffer range.
| Argument | Type | Description |
|---|---|---|
range | Range|Array<Point|Array<Number>>|Object | The range to mark; compatible arrays and coordinate objects are accepted. |
optionsoptional, default: {} | Object | Marker options and custom properties. |
reversedoptional, default: false | Boolean | Place the head at the earlier endpoint. |
invalidateoptional, default: 'overlap' | String | Invalidation strategy: never, surround, overlap, inside, or touch. See DisplayMarker for the strategy definitions. |
exclusiveoptional | Boolean | Keep endpoint insertions outside the marker. Defaults to false, or true with the inside invalidation strategy. |
Returns
Marker — The new marker.
Create a marker with its head at the given buffer position and no tail.
| Argument | Type | Description |
|---|---|---|
position | Point|Array<Number>|Object | The position to mark; compatible arrays and coordinate objects are accepted. |
optionsoptional, default: {} | Object | Marker options and custom properties. |
invalidateoptional, default: 'overlap' | String | Invalidation strategy: never, surround, overlap, inside, or touch. See DisplayMarker for the strategy definitions. |
exclusiveoptional | Boolean | Keep endpoint insertions outside the marker. Defaults to true for markers without a tail. |
Returns
Marker — The new marker.
Event Subscription3
Subscribe to be notified whenever markers are created, updated, or destroyed on this layer. Prefer this method for optimal performance when interacting with layers that could contain large numbers of markers.
Changes made within a TextBuffer#transact block are batched: subscribers are notified once, at the end of the transaction. Changes made outside a transaction notify subscribers synchronously per change. Either way, you should re-query the layer to determine the state of markers in which you’re interested in. It may be counter-intuitive, but this is much more efficient than subscribing to events on individual markers, which are expensive to deliver.
| Argument | Type | Description |
|---|---|---|
callback | Function | A Function that will be called with no arguments when changes occur on this layer. |
Returns
Disposable — Dispose to unsubscribe.
Subscribe to be notified synchronously whenever markers are created on this layer. Avoid this method for optimal performance when interacting with layers that could contain large numbers of markers.
You should prefer #onDidUpdate when synchronous notifications aren’t absolutely necessary.
| Argument | Type | Description |
|---|---|---|
callback | Function | A Function that will be called with a Marker whenever a new marker is created. |
marker | Marker | The newly created marker. |
Returns
Disposable — Dispose to unsubscribe.
Subscribe to be notified synchronously when this layer is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — Dispose to unsubscribe.
Essential API
Matchersrc/fuzzy-matcher.js:59
A reusable candidate set returned by fuzzyMatcher.setCandidates.
Query it with #match, or replace its candidates with
#setCandidates. The ignoreDiacritics flag is fixed when the matcher
is created.
Matching2
Matches the current candidates to a string query.
Each returned object contains the candidate id, its original value, and
a score from 0 to 1. When recordMatchIndexes is enabled, it also contains
the character indexes used for highlighting.
| Argument | Type | Description |
|---|---|---|
query | String | The query used to filter the candidates. |
optionsoptional, default: {} | Object | Search options. |
algorithmoptional, default: "fuzzaldrin" | "fuzzaldrin"|"command-t" | The scoring algorithm. fuzzaldrin uses acronym, consecutive-run, basename-aware path scoring, and optional query characters. command-t is the path-tuned alternative. |
maxResultsoptional, default: Infinity | Number | The maximum number of results. Limited requests use bounded selection. |
recordMatchIndexesoptional, default: false | Boolean | Include character indexes for highlighting. |
numThreadsoptional | Number | Legacy option; JavaScript matching runs synchronously on the calling thread. |
maxGapoptional, default: Infinity | Number | With command-t, the maximum gap between consecutive letters. |
usePathScoringoptional, default: true | Boolean | With fuzzaldrin, blend basename and full-path scores by directory depth. |
useExtensionBonusoptional, default: false | Boolean | With fuzzaldrin, prefer matching file extensions. |
Returns
Array<Object> — Matching candidates ordered by relevance.
Highlight a prepared candidate without rebuilding its text.
| Argument | Type | Description |
|---|---|---|
id | Number | Candidate position returned by #match. |
query | String | The query to highlight. |
optionsoptional, default: {} | Object | Matching options accepted by #match. |
Returns
Array<Number>|null — Original UTF-16 indexes, or null for a non-match.
Candidate Sets1
Replaces this matcher’s candidates.
| Argument | Type | Description |
|---|---|---|
candidates | Array<String> | The new candidates. |
Returns
Matcher — This matcher.
Public API
Notificationsrc/notification.js:10
A notification to the user containing a message and type.
Event Subscription2
Invoke the given callback when the notification is dismissed.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the notification is dismissed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the notification is displayed.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the notification is displayed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Methods3
Get the notification severity.
Returns
String — type.
Get the notification message.
Returns
String — message.
Dismisses the notification, removing it from the UI. Calling this
programmatically will call all callbacks added via onDidDismiss.
Public API
NotificationManagersrc/notification-manager.js:14
A notification manager used to create Notifications to be shown to the user.
An instance of this class is always available as the lumine.notifications
global.
Events3
Invoke the given callback after a notification has been added.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called after the notification is added. |
notification | Notification | The Notification that was added. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback after the notifications have been cleared.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called after the notifications are cleared. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback whenever #beep is called.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called when attention is requested. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Adding Notifications6
Add a success notification.
| Argument | Type | Description |
|---|---|---|
message | String | A String message |
optionsoptional | Object | An Object with the following keys: |
buttonsoptional | Array<Object> | An Array of Object where each Object has the following options: |
classNameoptional | String | a class name to add to the button’s default class name ( btn btn-success). |
onDidClickoptional | Function | callback to call when the button has been clicked. The context will be set to the NotificationElement instance. |
text | String | inner text for the button |
titleoptional | String | Plain-text tooltip explaining the button’s action. |
descriptionoptional | String | A Markdown String containing a longer description about the notification. By default, this will not preserve newlines and whitespace when it is rendered. |
detailoptional | String | A plain-text String containing additional details about the notification. By default, this will preserve newlines and whitespace when it is rendered. |
dismissableoptional | Boolean | A Boolean indicating whether this notification can be dismissed by the user. Defaults to false. |
iconoptional | String | A String name of an icon from Octicons to display in the notification header. Defaults to 'check'. |
windowoptional | EditorWindow | The editor window in which to display the notification; defaults to the main window. |
Returns
Notification — that was added.
Add a hint notification.
A hint is the quietest thing this API can say: something the user may want
to know, that does not report a failure and asks nothing of them. It is
rendered without a severity color, so it reads as an aside rather than as a
smaller warning. Hints are expected to be transient — leave dismissable
unset unless the hint carries a button worth waiting for.
Prefer a warning when something the user asked for did not happen.
| Argument | Type | Description |
|---|---|---|
message | String | A String message |
optionsoptional | Object | An Object with the following keys: |
buttonsoptional | Array<Object> | An Array of Object where each Object has the following options: |
classNameoptional | String | a class name to add to the button’s default class name ( btn). |
onDidClickoptional | Function | callback to call when the button has been clicked. The context will be set to the NotificationElement instance. |
text | String | inner text for the button |
titleoptional | String | Plain-text tooltip explaining the button’s action. |
descriptionoptional | String | A Markdown String containing a longer description about the notification. By default, this will not preserve newlines and whitespace when it is rendered. |
detailoptional | String | A plain-text String containing additional details about the notification. By default, this will preserve newlines and whitespace when it is rendered. |
dismissableoptional | Boolean | A Boolean indicating whether this notification can be dismissed by the user. Defaults to false. |
iconoptional | String | A String name of an icon from Octicons to display in the notification header. Defaults to 'light-bulb'. |
windowoptional | EditorWindow | The editor window in which to display the notification; defaults to the main window. |
Returns
Notification — that was added.
Add an informational notification.
| Argument | Type | Description |
|---|---|---|
message | String | A String message |
optionsoptional | Object | An Object with the following keys: |
buttonsoptional | Array<Object> | An Array of Object where each Object has the following options: |
classNameoptional | String | a class name to add to the button’s default class name ( btn btn-info). |
onDidClickoptional | Function | callback to call when the button has been clicked. The context will be set to the NotificationElement instance. |
text | String | inner text for the button |
titleoptional | String | Plain-text tooltip explaining the button’s action. |
descriptionoptional | String | A Markdown String containing a longer description about the notification. By default, this will not preserve newlines and whitespace when it is rendered. |
detailoptional | String | A plain-text String containing additional details about the notification. By default, this will preserve newlines and whitespace when it is rendered. |
dismissableoptional | Boolean | A Boolean indicating whether this notification can be dismissed by the user. Defaults to false. |
iconoptional | String | A String name of an icon from Octicons to display in the notification header. Defaults to 'info'. |
windowoptional | EditorWindow | The editor window in which to display the notification; defaults to the main window. |
Returns
Notification — that was added.
Add a warning notification.
| Argument | Type | Description |
|---|---|---|
message | String | A String message |
optionsoptional | Object | An Object with the following keys: |
buttonsoptional | Array<Object> | An Array of Object where each Object has the following options: |
classNameoptional | String | a class name to add to the button’s default class name ( btn btn-warning). |
onDidClickoptional | Function | callback to call when the button has been clicked. The context will be set to the NotificationElement instance. |
text | String | inner text for the button |
titleoptional | String | Plain-text tooltip explaining the button’s action. |
descriptionoptional | String | A Markdown String containing a longer description about the notification. By default, this will not preserve newlines and whitespace when it is rendered. |
detailoptional | String | A plain-text String containing additional details about the notification. By default, this will preserve newlines and whitespace when it is rendered. |
dismissableoptional | Boolean | A Boolean indicating whether this notification can be dismissed by the user. Defaults to false. |
iconoptional | String | A String name of an icon from Octicons to display in the notification header. Defaults to 'alert'. |
windowoptional | EditorWindow | The editor window in which to display the notification; defaults to the main window. |
Returns
Notification — that was added.
Add an error notification.
| Argument | Type | Description |
|---|---|---|
message | String | A String message |
optionsoptional | Object | An Object with the following keys: |
buttonsoptional | Array<Object> | An Array of Object where each Object has the following options: |
classNameoptional | String | a class name to add to the button’s default class name ( btn btn-error). |
onDidClickoptional | Function | callback to call when the button has been clicked. The context will be set to the NotificationElement instance. |
text | String | inner text for the button |
titleoptional | String | Plain-text tooltip explaining the button’s action. |
descriptionoptional | String | A Markdown String containing a longer description about the notification. By default, this will not preserve newlines and whitespace when it is rendered. |
detailoptional | String | A plain-text String containing additional details about the notification. By default, this will preserve newlines and whitespace when it is rendered. |
dismissableoptional | Boolean | A Boolean indicating whether this notification can be dismissed by the user. Defaults to false. |
iconoptional | String | A String name of an icon from Octicons to display in the notification header. Defaults to 'flame'. |
windowoptional | EditorWindow | The editor window in which to display the notification; defaults to the main window. |
stackoptional | String | A preformatted String with stack trace information describing the location of the error. Requires detail to be set. |
Returns
Notification — that was added.
Add a fatal error notification.
| Argument | Type | Description |
|---|---|---|
message | String | A String message |
optionsoptional | Object | An Object with the following keys: |
buttonsoptional | Array<Object> | An Array of Object where each Object has the following options: |
classNameoptional | String | a class name to add to the button’s default class name ( btn btn-error). |
onDidClickoptional | Function | callback to call when the button has been clicked. The context will be set to the NotificationElement instance. |
text | String | inner text for the button |
titleoptional | String | Plain-text tooltip explaining the button’s action. |
descriptionoptional | String | A Markdown String containing a longer description about the notification. By default, this will not preserve newlines and whitespace when it is rendered. |
detailoptional | String | A plain-text String containing additional details about the notification. By default, this will preserve newlines and whitespace when it is rendered. |
dismissableoptional | Boolean | A Boolean indicating whether this notification can be dismissed by the user. Defaults to false. |
iconoptional | String | A String name of an icon from Octicons to display in the notification header. Defaults to 'bug'. |
windowoptional | EditorWindow | The editor window in which to display the notification; defaults to the main window. |
stackoptional | String | A preformatted String with stack trace information describing the location of the error. Requires detail to be set. |
Returns
Notification — that was added.
Requesting Attention1
Request audible or visual attention from notification consumers.
Getting Notifications1
Get all the notifications.
Returns
Array<Notification> — of Notifications.
Managing Notifications1
Clear all the notifications.
Extended API
Packagesrc/package.js:42
Loads and activates a package’s main module and resources such as stylesheets, keymaps, grammar, editor properties, and menus.
Event Subscription1
Invoke the given callback when this package has been deactivated.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Native Module Compatibility3
Are all native modules depended on by this package correctly compiled against the current version of Lumine?
This explicit diagnostic loads every discovered native binding. Startup loads only bindings actually required by the package; unused optional bindings do not prevent its JavaScript bootstrap from activating.
Returns
Boolean — true if compatible, false if incompatible.
Rebuild native modules in this package’s dependencies for the current version of Lumine.
Returns
Promise<Object> — that resolves with an object containing code, stdout, and stderr properties based on the results of running npm rebuild on the package.
If a previous rebuild failed, get the contents of stderr.
Returns
String|null — or null if no previous build failure occurred.
Extended API
PackageManagersrc/package-manager.js:79
Package manager for coordinating the lifecycle of Lumine packages.
Full description
An instance of this class is always available as the lumine.packages global.
Packages can be loaded, activated, and deactivated, and unloaded:
- Loading a package reads and parses the package’s metadata and resources such as keymaps, menus, stylesheets, etc.
- Activating a package registers the loaded resources and calls
activate()on the package’s main module. - Deactivating a package unregisters the package’s resources and calls
deactivate()on the package’s main module. - Unloading a package removes it completely from the package manager.
Packages can be enabled/disabled via the core.disabledPackages config
settings and also by calling enablePackage()/disablePackage().
Event Subscription7
Invoke the given callback when all packages have been loaded.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when all packages have been activated.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback after all initial package facades have been initialized, before workspace restore begins.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called after every initial package facade is initialized. |
Returns
Disposable — Dispose to unsubscribe.
Invoke the given callback when a package is activated.
| Argument | Type | Description |
|---|---|---|
callback | Function | A Function to be invoked when a package is activated. |
package | Package | The Package that was activated. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a package is deactivated.
| Argument | Type | Description |
|---|---|---|
callback | Function | A Function to be invoked when a package is deactivated. |
package | Package | The Package that was deactivated. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a package is loaded.
| Argument | Type | Description |
|---|---|---|
callback | Function | A Function to be invoked when a package is loaded. |
package | Package | The Package that was loaded. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a package is unloaded.
| Argument | Type | Description |
|---|---|---|
callback | Function | A Function to be invoked when a package is unloaded. |
package | Package | The Package that was unloaded. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Package System Data1
Get the paths being used to look for packages.
Returns
Array<String> — of String directory paths.
General Package Data2
Resolve the given package name to a path on disk.
| Argument | Type | Description |
|---|---|---|
name | String | The String package name. |
Returns
String|null — folder path or null if it could not be resolved.
Is the package with the given name bundled with Lumine?
| Argument | Type | Description |
|---|---|---|
name | String | The String package name. |
Returns
Boolean
Enabling and Disabling Packages3
Enable the package with the given name.
| Argument | Type | Description |
|---|---|---|
name | String | The String package name. |
Returns
Promise<Package|null> — Resolves when the enabled package is initialized or active.
Disable the package with the given name.
| Argument | Type | Description |
|---|---|---|
name | String | The String package name. |
Returns
Promise<Package|null> — Resolves after the package is fully deactivated.
Is the package with the given name disabled?
| Argument | Type | Description |
|---|---|---|
name | String | The String package name. |
Returns
Boolean
Accessing Active Packages3
Is the Package with the given name active?
| Argument | Type | Description |
|---|---|---|
name | String | The String package name. |
Returns
Boolean
Package Lifecycle9
Return the package’s explicit lifecycle state.
| Argument | Type | Description |
|---|---|---|
name | String | Package name. |
Returns
String|undefined — One of loaded, activating, active, or deactivating. An unloaded or unknown package has no current lifecycle record.
Check whether initial package activation has completed.
Returns
Boolean — indicating whether package activation has occurred.
Check whether initial package loading has completed.
Returns
Boolean — indicating whether package loading has occurred.
Check whether the initial package bootstrap has completed.
Returns
Boolean — indicating whether the initial package bootstrap has completed.
Initialize every enabled package before workspace state is restored.
Initialization is deliberately synchronous and is the package-facing
bootstrap phase: packages may register deserializers, openers, commands,
lightweight UI hosts, and service facades here. Expensive work belongs in
an explicit package-owned ensure method and must not be started from this
phase. Keeping this separate from activation lets workspace restoration
use those registrations without making activate() responsible for
deserialization ordering.
Atomically deactivate and unload a package in any lifecycle state. The current generation is stopped before the loaded instance is removed.
| Argument | Type | Description |
|---|---|---|
name | String | Package name. |
optionsoptional, default: {} | Object | Teardown options. |
serializeoptional, default: true | Boolean | Serialize an active package before teardown. Defaults to true. |
preserveModuleCacheoptional, default: false | Boolean | Preserve module identities for restart-required package updates and rollback. |
Returns
Promise<Package> — Resolves with the unloaded package after teardown.
Start a package according to its manifest. The synchronous facade is published during the call; the returned promise also settles after core grammar/settings resources finish loading. Expensive feature work remains package-owned and lazy.
| Argument | Type | Description |
|---|---|---|
name | String | Package name or path. |
Returns
Promise<Package> — The started package. This never waits for a future trigger.
Fully activate a package and wait for its main module and services to be ready.
Concurrent requests share one activation. Deactivation while activating
rejects with an error whose code is PACKAGE_ACTIVATION_CANCELLED.
| Argument | Type | Description |
|---|---|---|
name | String | Package name or path. |
Returns
Promise<Package> — The active package.
Deactivate a loaded package and await its teardown before it reaches the loaded state again.
| Argument | Type | Description |
|---|---|---|
name | String | Package name. |
optionsoptional, default: {} | Object | Teardown options. |
serializeoptional, default: true | Boolean | Serialize an active package before teardown. Defaults to true. |
Returns
Promise<void> — Resolves when the package reaches loaded.
Accessing Loaded Packages3
Is the package with the given name loaded?
| Argument | Type | Description |
|---|---|---|
name | String | The String package name. |
Returns
Boolean
Accessing Available Packages6
Get the directory paths of all available packages.
Returns
Array<String> — of Strings of all the available package paths.
Get the names of all available packages.
Returns
Array<String> — of Strings of all the available package names.
Get manifest metadata for all available packages.
Returns
Array<Object> — of manifest metadata objects for all available packages.
Get available package descriptors sorted by name.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | |
includeShadowedoptional, default: false | Boolean | When true, also returns the copies whose name is owned by another directory. Those never load; they exist so the UI can list every directory on disk. |
Returns
Array<Object> — Available package descriptors that own their names, sorted by name.
Get the available package that owns the given name.
| Argument | Type | Description |
|---|---|---|
name | String | The package name to look up. |
Returns
Object|undefined — package descriptor or undefined.
Forget everything read from package manifests.
The directory scan itself always runs fresh, so this only has to be called when a manifest changes on disk — after an install, update, or uninstall.
Services1
Check whether a compatible service has already been published. Service lookup never activates a provider; providers are ordinary active packages.
| Argument | Type | Description |
|---|---|---|
keyPath | String | Exact service name. |
versionRange | String | Semantic version range required by the caller. |
Returns
Promise<Boolean> — Whether a compatible non-null service is published.
Extended API
Panesrc/pane.js:33
A container for presenting content in the center of the workspace. Panes can contain multiple items, one of which is active at a given time. The view corresponding to the active item is displayed in the interface. In the default configuration, tabs are also displayed for each item.
Full description
Each pane may also contain one pending item. When a pending item is added to a pane, it will replace the currently pending item, if any, instead of simply being added. In the default configuration, the text in the tab for pending items is shown in italics.
Event Subscription16
Invoke the given callback when the pane resizes.
The callback will be invoked when pane’s flexScale property changes.
Use getFlexScale to get the current value.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the pane is resized. |
flexScale | Number | representing the pane’s flex-grow; ability for a flex item to grow if necessary. |
Returns
Disposable — on which ‘.dispose()’ can be called to unsubscribe.
Invoke the given callback with the current and future values of
getFlexScale.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with the current and future values of the getFlexScale property. |
flexScale | Number | representing the panes flex-grow; ability for a flex item to grow if necessary. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the pane is activated.
The given callback will be invoked whenever #activate is called on the pane, even if it is already active at the time.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the pane is activated. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback before the pane is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called before the pane is destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the pane is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the pane is destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the value of the #isActive property changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the value of the #isActive property changes. |
active | Boolean | indicating whether the pane is active. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Observe a change of presentation window while retaining this pane.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives sourceWindow and targetWindow. |
Returns
Disposable — Removes the observation.
Invoke the given callback with the current and future values of the #isActive property.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with the current and future values of the #isActive property. |
active | Boolean | indicating whether the pane is active. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when an item is added to the pane.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when items are added. |
event | Object | with the following keys: |
item | * | The added pane item. |
index | Number | indicating where the item is located. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when an item is removed from the pane.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when items are removed. |
event | Object | with the following keys: |
item | * | The removed pane item. |
index | Number | indicating where the item was located. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback before an item is removed from the pane.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called before items are removed. |
event | Object | with the following keys: |
item | * | The pane item to be removed. |
index | Number | indicating where the item is located. |
Invoke the given callback when an item is moved within the pane.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when items are moved. |
event | Object | with the following keys: |
item | * | The removed pane item. |
oldIndex | Number | indicating where the item was located. |
newIndex | Number | indicating where the item is now located. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with all current and future items.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with current and future items. |
item | * | An item that is present in #getItems at the time of subscription or that is added at some later time. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the value of #getActiveItem changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active item changes. |
activeItem | * | The current active item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with the current and future values of #getActiveItem.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with the current and future active items. |
activeItem | * | The current active item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback before items are destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called before items are destroyed. |
event | Object | with the following keys: |
item | * | The item that will be destroyed. |
index | Number | The location of the item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Items24
Get the items in this pane.
Returns
Array — of items.
Get the active pane item in this pane.
Returns
* — pane item.
Get the item at a zero-based tab index.
| Argument | Type | Description |
|---|---|---|
index | Number |
Returns
* — The item at the index, or undefined when no item exists there.
Makes the next item in the itemStack active.
Makes the previous item in the itemStack active.
Moves the active item to the end of the item stack once a modifier key (typically Ctrl) is lifted.
Makes the next item active.
Makes the previous item active.
Move the active tab to the right.
Move the active tab to the left
Get the index of the active item.
Returns
Number
Activate the item at the given index.
| Argument | Type | Description |
|---|---|---|
index | Number |
Make the given item active, causing it to be displayed by the pane’s view.
| Argument | Type | Description |
|---|---|---|
item | * | The item to activate |
optionsoptional, default: {} | Object | |
pendingoptional | Boolean | indicating that the item should be added in a pending state if it does not yet exist in the pane. Existing pending items in a pane are replaced with new pending items when they are opened. |
activatePaneoptional | Boolean | true also activates and focuses this pane after selecting the item, notifying workspace observers of the final selection once. |
Add the given item to the pane.
Non-mini text editors with no explicit autoHeight setting adopt the
pane’s height so their content can scroll. Explicit sizing and editors
embedded within another item are preserved.
| Argument | Type | Description |
|---|---|---|
item | * | The item to add. It can be a model with an associated view or a view. |
optionsoptional, default: {} | Object | |
indexoptional | Number | indicating the index at which to add the item. If omitted, the item is added after the current active item. |
pendingoptional | Boolean | indicating that the item should be added in a pending state. Existing pending items in a pane are replaced with new pending items when they are opened. |
transferredoptional | Boolean | Mark a newly staged cross-window item, preserving its requested placement instead of treating it as a regular open. |
Returns
* — added item.
Toggle the pending state of the active item.
Clears the pending item if the active item is already pending, otherwise
marks the active item as pending. When marking an item pending, its
buffer edits are watched for text editors so that editing them clears the
pending state, the same way natively-previewed items behave. Other items
use onDidChange. This is required because
terminatePendingState is one-shot: once an item has terminated it never
emits again, so a re-pended item could not otherwise clear itself.
Add the given items to the pane.
| Argument | Type | Description |
|---|---|---|
items | Array<*> | An Array of items to add. Items can be views or models with associated views. Any objects that are already present in the pane’s current items will not be added again. |
indexoptional, default: this.getActiveItemIndex() + 1 | Number | index at which to add the items. If omitted, the item is # added after the current active item. |
Returns
Array<*> — of added items.
Move the given item to the given index.
| Argument | Type | Description |
|---|---|---|
item | * | The item to move. |
newIndex | Number | indicating the index to which to move the item. |
Move the given item to the given index on another pane.
| Argument | Type | Description |
|---|---|---|
item | * | The item to move. |
pane | Pane | to which to move the item. |
indexoptional | Number | indicating the index to which to move the item in the given pane. |
optionsoptional, default: {} | Object | Source-pane lifetime options. |
preserveSourcePaneoptional, default: false | Boolean | Keep an emptied source pane alive after the move. |
Destroy the active item and activate the next item.
Returns
Promise<Boolean> — that resolves when the item is destroyed.
Destroy the given item.
If the item is active, the next item will be activated. If the item is the
last item, a pane in the workspace center will be destroyed if the
core.destroyEmptyPanes config setting is true. A pane in a dock will
always be destroyed when it becomes empty.
This action can be prevented by onWillDestroyPaneItem callbacks in which case nothing happens.
| Argument | Type | Description |
|---|---|---|
item | * | Item to destroy |
forceoptional | Boolean | Destroy the item without prompting to save it, even if the item’s isPermanentDockItem method returns true. |
optionsoptional, default: {} | Object | Final mutation guards for an asynchronous close. |
canDestroyoptional | Function | Return false to cancel after listeners and save prompts have completed. |
Returns
Promise<Boolean> — that resolves with a Boolean indicating whether or not the item was destroyed.
Destroy all items.
Destroy all items except for the active item.
Find the first pane item with the given URI.
| Argument | Type | Description |
|---|---|---|
uri | String | containing a URI. |
Returns
*|undefined — first item that matches the given URI or undefined if none exists.
Activate the first item that matches the given URI.
| Argument | Type | Description |
|---|---|---|
uri | String | containing a URI. |
Returns
Boolean — indicating whether an item matching the URI was found.
Activation3
Apply a synchronous group of pane changes and notify workspace observers once with the final active pane and item. Changes and pane-local view events remain synchronous. Nested transactions and other containers touched by the callback share the outer operation. Only its final activation request is published, before the other containers report their final items.
| Argument | Type | Description |
|---|---|---|
callback | Function | synchronous work to perform; async callbacks and Promise return values are rejected. A thrown error still commits notifications for changes already made and clears the transaction. |
Returns
* — the callback’s return value.
Determine whether the pane is active.
Returns
Boolean
Makes this pane the active pane, causing it to gain focus.
Saving Items5
Save the active item.
| Argument | Type | Description |
|---|---|---|
nextActionoptional | Function | Receives a save error on failure, or no argument after success. |
Returns
Promise<*>|undefined
Prompt the user for a location and save the active item with the path they select.
| Argument | Type | Description |
|---|---|---|
nextActionoptional | Function | which will be called after the item is successfully saved. |
Returns
Promise<*> — that resolves when the save is complete
Save the given item.
| Argument | Type | Description |
|---|---|---|
item | * | The item to save. |
nextActionoptional | Function | which will be called with no argument after the item is successfully saved, or with the error if it failed. The callback return value is used only when saving through saveItemAs. |
Returns
Promise<*>|undefined — Settles after the save attempt; an unsaveable item can return undefined. Save-as results follow saveItemAs. Save cancellation may reject, while other write errors are reported to nextAction or notifications.
Prompt the user for a location and save the given item with the path they select.
| Argument | Type | Description |
|---|---|---|
item | * | The item to save. |
nextActionoptional | Function | which will be called with no argument after the item is successfully saved, or with the error if it failed. The return value will be that of nextAction or undefined if it was not provided. |
Returns
Promise<*> — Resolves with the optional callback result. Cancellation reports a SaveCancelledError to the callback, or resolves to undefined when no callback is supplied.
Save all saveable items whose file state is not unmodified.
Returns
Promise<Array<*>> — that resolves when all items have been saved.
Lifecycle2
Close the pane and destroy all its items.
Closing the active pane activates the most recently used remaining pane.
If this is the last pane, all the items will be destroyed but the pane itself will not be destroyed.
Determine whether this pane has been destroyed.
Returns
Boolean
Splitting4
Create a new pane to the left of this pane.
| Argument | Type | Description |
|---|---|---|
paramsoptional | Object | with the following keys: |
itemsoptional | Array | of items to add to the new pane. |
activateoptional | Boolean | false will leave the currently active pane active instead of activating the new pane. Defaults to true. |
Returns
Create a new pane to the right of this pane.
| Argument | Type | Description |
|---|---|---|
paramsoptional | Object | with the following keys: |
itemsoptional | Array | of items to add to the new pane. |
activateoptional | Boolean | false will leave the currently active pane active instead of activating the new pane. Defaults to true. |
Returns
Creates a new pane above the receiver.
| Argument | Type | Description |
|---|---|---|
paramsoptional | Object | with the following keys: |
itemsoptional | Array | of items to add to the new pane. |
activateoptional | Boolean | false will leave the currently active pane active instead of activating the new pane. Defaults to true. |
Returns
Creates a new pane below the receiver.
| Argument | Type | Description |
|---|---|---|
paramsoptional | Object | with the following keys: |
itemsoptional | Array | of items to add to the new pane. |
activateoptional | Boolean | false will leave the currently active pane active instead of activating the new pane. Defaults to true. |
Returns
Public API
PaneContainersrc/pane-container.js:13
Pane Container Details1
Get the editor window presenting this container.
Returns
EditorWindow|null — The presentation, or null before attachment.
Pane Presentation2
Present one pane independently of its split layout without recreating or disconnecting its live view. The caller owns its visual positioning. Visual navigation treats it as the container’s only pane and uses the container’s bounds when finding neighboring docks. Activating a different pane or changing the split layout ends the presentation.
| Argument | Type | Description |
|---|---|---|
pane | Pane | A pane in this connected container. |
Returns
Object — A handle with element, slot, dispose() and onDidDispose(callback).
Get the pane currently representing this container’s visible presentation.
Returns
Pane|null — The presented pane, or null for the normal split layout.
Text Editors2
Get the file-content editor of this container’s active item.
Returns
TextEditor|undefined — The editor, including a notebook’s backing source.
Get the editor being edited inside this container’s active item.
Returns
TextEditor|undefined — The editor, including an active notebook cell.
Event Subscription2
Observe this window-local active file-content editor.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives the current and future TextEditor or undefined. |
Returns
Disposable — Removes the observation.
Observe the active editable editor inside this container’s active item.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives the current and future TextEditor or undefined. |
Returns
Disposable — Removes the observation.
Extended API
PaneItemTransferScopesrc/pane-item-transfer-service.js:418
A disposable group of transfers owned by a package or core operation.
Transfer Sessions2
Capture a pane item and retain its exact source identity until settlement.
| Argument | Type | Description |
|---|---|---|
pane | Pane | The pane containing the item. |
item | * | The exact item to move. |
Returns
Object — A serializable workspace drag descriptor.
Abandon a retained source session without destroying its item.
| Argument | Type | Description |
|---|---|---|
token | String | The retained transfer token. |
reasonoptional, default: "transfer abandoned" | * | A serializable rollback reason. |
Returns
Boolean — Whether a retained transfer was released.
Drop Operations3
Validate a complete descriptor before resolving or creating a destination.
| Argument | Type | Description |
|---|---|---|
descriptor | Object | The normalized pane-item drag descriptor. |
paneoptional | Pane | The potential destination pane, used to decide whether splitting is allowed. |
Returns
Object|null — Prepared transfer state, or null for an unsupported payload.
Complete a prepared drop, staging remote content before source commit.
| Argument | Type | Description |
|---|---|---|
context | Object | The drop target context and destination pane placement. |
prepared | Object | A non-null result from prepareDrop. |
Returns
Promise<Object> — The destination pane and item.
Move an item into a freshly opened window using the same staged transfer. The source remains intact until the destination acknowledges its content.
| Argument | Type | Description |
|---|---|---|
pane | Pane | The source pane. |
item | * | The exact source item. |
Returns
Promise<Object> — The destination window identity as {windowId}, after the source transfer commits.
Construction and Destruction1
Cancel outstanding source sessions and prevent destination work from committing.
Extended API
PaneItemTransferServicesrc/pane-item-transfer-service.js:27
Moves exact pane items locally and stages their content before committing a move between windows. Scopes tie transfers to their caller’s lifecycle.
Construction and Destruction1
Own a group of source sessions and destination operations.
Returns
PaneItemTransferScope — Dispose the scope when its caller unloads.
Extended API
Panelsrc/panel.js:13
A container representing a panel on the edges of the editor window.
You should not create a Panel directly, instead use Workspace#addTopPanel
and friends to add panels.
Examples: status-bar and search-panel both use panels.
Construction and Destruction1
Destroy and remove this panel from the UI.
Event Subscription2
Invoke the given callback when this panel is hidden or shown.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the panel’s visibility changes. |
visible | Boolean | true when the panel has been shown |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when this panel is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the panel is destroyed. |
panel | Panel | this panel |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Panel Details2
Get the content item displayed by this panel.
Returns
* — panel’s item.
Get the stacking priority assigned to this panel.
Returns
Number — indicating this panel’s priority.
Visibility3
Determine whether this panel is shown.
Returns
Boolean — true when the panel is visible.
Hide this panel.
Show this panel.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | |
crumboptional | String|Boolean | Modal panels only. A String, or true to use the label the panel declared when it was added. The panel announces “display me now and take me into the breadcrumb”: the modal that is visible at this moment becomes the previous entry of the window’s modal trail, the breadcrumb strip shows the path, and modal:go-back (Shift-Escape) or a click on an earlier crumb returns to it. Without crumb the panel is shown standalone, exactly as before — and showing a modal standalone ends whatever trail another flow had built. |
Experimental API
PasteProviderRegistrysrc/paste-provider-registry.js:46
Lets a package claim a paste before the editor turns the clipboard into text.
Full description
An instance of this class is always available as the lumine.pasteProviders
global.
This is a dispatch table, not a second clipboard. Clipboard owns what the clipboard holds; this owns who gets first refusal on putting it somewhere. The two are deliberately separate, because a provider is chosen by the paste’s target — a text editor, a tree-view directory — and that is workspace vocabulary the clipboard has no business knowing.
Providers are offered the paste highest priority first, and equal
priorities keep registration order. The first one to resolve to true
claims it and no later provider is consulted; when none does, the caller
falls back to its own behavior — inserting text, in the editor’s case. A paste that sets
skipPasteProviders in its options skips the registry outright, which is how
editor:paste-without-reformatting guarantees it pastes raw text.
A provider may return a Promise, but it must copy everything it needs from
a native paste ClipboardEvent before its first asynchronous step because
clipboardData is readable only for the duration of that event.
Examples#
Take over pasting an image, and leave every other paste alone:
lumine.pasteProviders.add({
handlePaste({ target, clipboardData }) {
if (target.type !== 'text-editor') return false
const image = imageFrom(clipboardData)
if (!image) return false
saveAndInsert(image, target.editor) // may finish asynchronously
return true
}
}, { priority: 100 })
Methods2
Register a paste provider. Returns a Disposable that
unregisters it.
Throws a TypeError when the provider has no handlePaste method, or when
priority is not a finite number.
| Argument | Type | Description |
|---|---|---|
provider | Object | An Object with a handlePaste(context) method. It receives exactly what #handlePaste was given, and returns or resolves to true to claim the paste or false to pass it on. |
optionsoptional, default: {} | Object | Registration options. |
priorityoptional, default: 0 | Number | The order in which providers are consulted, highest first. Ties preserve registration order. |
Returns
Disposable — A disposable that unregisters the provider.
Offer a paste to each registered provider in turn.
The text editor calls this for you. Call it directly when your own package is somewhere a paste can land: the tree-view does, so that pasting onto a directory row reaches the same providers an editor paste would. Providers are captured when dispatch starts. Removed providers are skipped, and newly registered providers participate in the next paste.
| Argument | Type | Description |
|---|---|---|
context | Object | An Object describing the paste, with the following keys: |
target | Object | An Object naming where the paste lands. Today that is {type: 'text-editor', editor}, {type: 'directory', path}, or {type: 'terminal', model, path} — where path is the directory the terminal was launched in. Always branch on type and return false for one you do not recognize — the set grows as more of the workspace offers its pastes here. |
clipboardoptional | Clipboard|Object | The Clipboard to read the paste from. Inside a native paste event this is a DataTransfer-backed clipboard, so readWithMetadata() sees the metadata of the window that did the copy; outside one it is lumine.clipboard. Absent when the caller is not a text editor. |
clipboardDataoptional | DataTransfer|null | The event’s DataTransfer, or null when the paste did not arrive as a native paste event. Custom formats and non-text items such as files and images are readable only from here. |
optionsoptional | Object | An Object of the paste options the editor would otherwise have used, such as autoIndent and normalizeLineEndings. |
Returns
Boolean|Promise<Boolean> — true when a provider claimed the paste and the caller must not handle it itself, false when none did, or a Promise resolving to either value when a provider decides asynchronously.
Public API
Pointsrc/point.js:20
Represents a point in a buffer in row/column coordinates.
Full description
Every public method that takes a point also accepts a point-compatible
Array. This means a 2-element array containing Numbers representing the
row and column. So the following are equivalent:
new Point(1, 2)
[1, 2] // Point-compatible Array
Constants2
Construction3
Convert any point-compatible object to a Point.
| Argument | Type | Description |
|---|---|---|
object | Point|Array<Number>|Object | A Point, an array containing the row and column, or an object with row and column properties. An existing point is returned unless copying is requested. |
copyoptional, default: false | Boolean | An optional boolean indicating whether to force the copying of objects that are already points. |
Returns
Point — A point based on the given object.
Construct a Point object.
| Argument | Type | Description |
|---|---|---|
rowoptional, default: 0 | Number | row |
columnoptional, default: 0 | Number | column |
Comparison8
Validation1
Operations4
Build and return a new Point by traversing the rows and columns specified by the given point.
This method differs from the direct, vector-style addition offered by #translate. Rather than adding the rows and columns directly, it derives the new point from traversing in “typewriter space”. At the end of every row traversed, a carriage return occurs that returns the columns to 0 before continuing the traversal.
Examples
Traversing 0 rows, 2 columns:
new Point(10, 5).traverse(new Point(0, 2)) # => [10, 7]
Traversing 2 rows, 2 columns. Note the columns reset from 0 before adding:
new Point(10, 5).traverse(new Point(2, 2)) # => [12, 2]
| Argument | Type | Description |
|---|---|---|
other | Point|Array<Number>|Object | A Point providing the rows and columns to traverse by. |
Returns
Conversion3
Convert this point to a row-and-column array.
Returns
Array<Number> — The row and column, in that order.
Serialize this point as a row-and-column array.
Returns
Array<Number> — The row and column, in that order.
Get a string representation of this point.
Returns
String — string representation of the point.
Extended API
Projectsrc/project.js:22
Represents a project that’s opened in Lumine.
An instance of this class is always available as the lumine.project global.
Event Subscription7
Invoke the callback before a confirmed project session replacement tears down its outgoing center or rebinds package workspace storage. Cancel project-bound asynchronous work here while outgoing paths and storage still agree. The callback runs synchronously and cannot veto the transition. A later failure may restore the outgoing project. Direct root edits through #setPaths emit only #onDidChangePaths.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called before replacing the project session. |
projectPaths | Array<String> | Readonly incoming project paths. |
Returns
Disposable — The event subscription.
Invoke the given callback when the project paths change.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called after the project paths change. |
projectPaths | Array<String> | An Array of String project paths. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a text buffer is added to the project.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when a text buffer is added. |
buffer | TextBuffer | A TextBuffer item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with all current and future text buffers in the project.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with current and future text buffers. |
buffer | TextBuffer | A TextBuffer item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke a callback when a filesystem change occurs within any open project path.
const disposable = lumine.project.onDidChangeFiles(events => {
for (const event of events) {
// "created", "updated", or "deleted"
console.log(`Event action: ${event.action}`)
// absolute path to the filesystem entry that was touched
console.log(`Event path: ${event.path}`)
}
})
disposable.dispose()
Project roots are watched recursively, and the recursive backend reports a
move as a "deleted" followed by a "created" — it never emits
"renamed" and never sets oldPath. Handle the move as the two events it
arrives as; a "renamed" branch written against this method is dead code.
File and directory subscriptions retain their originally requested paths.
Paths are absolute and spelled the way the root was registered, matching #getPaths and #relativizePath, so an event path can be compared against a stored one directly.
To watch paths outside of open projects, use the watchDirectory function instead; see FileWatchHandle.
When writing tests against functionality that uses this method, be sure to wait for the
Promise returned by #getWatcherPromise before manipulating the filesystem to ensure that
the watcher is receiving events.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with batches of filesystem events reported by the operating system. |
events | Array<Object> | An Array of objects that describe a batch of filesystem events. |
action | String | describing the filesystem action that occurred. One of "created", "updated", or "deleted". |
path | String | containing the absolute path to the filesystem entry that was acted upon. |
Returns
Disposable — to manage this event subscription.
Observe restored filesystem observation after a gap. Consumers must reread the affected roots; changes made during the gap are not replayed.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives rootPaths, reason and generation. |
Returns
Disposable — The event subscription.
Invoke the given callback with the project’s file paths, now and whenever they change.
Where #crawl answers “what is there right now” once, the file index keeps the answer, streams it as it arrives, and maintains it against the filesystem watcher. Prefer these methods over crawling on a timer or rebuilding on #onDidChangeFiles by hand: a package that does either is reimplementing this one, and the ignore semantics are easy to get subtly wrong.
The first call is synchronous and reports everything currently indexed as
added, so a consumer has exactly one code path: apply removed, then
apply added.
const disposable = lumine.project.observeFilePaths(({ added, removed, indexing }) => {
for (const filePath of removed) this.items.delete(filePath);
for (const filePath of added) this.items.set(filePath, this.build(filePath));
this.setLoading(indexing);
});
Changes are coalesced, so one call can carry a whole batch, and during the
first crawl the callback fires repeatedly with partial results — check
indexing rather than assuming the first call is complete. A deleted
directory reports every file that was under it, so no consumer needs its own
prefix sweep.
The whole-index array is deliberately not passed: rebuilding derived state from it on every call is quadratic over a progressive crawl. Call #getFilePaths if you want it — that is memoized, so asking on every callback costs nothing extra.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with each batch of changes. |
added | Array<String> | An Array of String absolute paths new to the index. |
removed | Array<String> | An Array of String absolute paths no longer in it. |
indexing | Boolean | A Boolean, true while a crawl is still running. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Accessing Git Repositories2
Get the repository for a given directory asynchronously.
| Argument | Type | Description |
|---|---|---|
directory | Directory | for which to get a GitRepository. |
Returns
Promise<GitRepository|null> — The containing repository, or null when none is found.
Get the repository that contains a given file or directory path asynchronously.
This is a convenience over #repositoryForDirectory for callers that have
a path String rather than a Directory. Providers receive the path
directly and perform discovery asynchronously.
| Argument | Type | Description |
|---|---|---|
filePath | String | path of a file or directory. |
optionsoptional, default: {} | Object | Resolution options. |
refreshoptional, default: true | Boolean | Re-run providers instead of using an exact-path discovery cache entry. |
Returns
Promise<GitRepository|null> — The containing repository, or null when none is found.
Managing Paths8
Get an Array of Strings containing the paths of the project’s
directories.
Returns
Array<String>|undefined — Root directory paths, or undefined if corrupt window state prevents reading them.
Set the paths of the project’s directories.
| Argument | Type | Description |
|---|---|---|
projectPaths | Array | of String paths. |
optionsoptional, default: {} | Object | An optional Object that may contain the following keys: |
mustExistoptional | Boolean | If true, throw an Error if any projectPaths do not exist. Any remaining projectPaths that do exist will still be added to the project. Default: false. |
exactoptional | Boolean | If true, only add a projectPath if it names an existing directory. If false and any projectPath is a file or does not exist, its parent directory will be added instead. Default: false. |
Add a path to the project’s list of root paths.
| Argument | Type | Description |
|---|---|---|
projectPath | String | The path to the directory to add. |
optionsoptional, default: {} | Object | An optional Object that may contain the following keys: |
mustExistoptional | Boolean | If true, throw an Error if the projectPath does not exist. If false, a projectPath that does not exist is ignored. Default: false. |
exactoptional | Boolean | If true, only add projectPath if it names an existing directory. If false, if projectPath is a file or does not exist, its parent directory will be added instead. |
Add multiple paths to the project’s list of root paths,
emitting a single did-change-paths event after all paths are added.
| Argument | Type | Description |
|---|---|---|
projectPaths | Array<String> | An Array of String paths to add. |
optionsoptional, default: {} | Object | An optional Object passed to #addPath for each path. |
Remove a path from the project’s list of root paths.
| Argument | Type | Description |
|---|---|---|
projectPath | String | The path to remove. |
Returns
Boolean — Whether a project root was removed.
Get the root directories associated with this project.
Returns
Array<Directory> — The current project root directory objects.
Get the path to the project directory that contains the given path, and the relative path from that project directory to the given path.
projectPathTheStringpath to the project directory that contains the given path, ornullif none is found.relativePathStringThe relative path from the project directory to the given path.
| Argument | Type | Description |
|---|---|---|
fullPath | String | An absolute path. |
Returns
Array — with two elements:
Determines whether the given path (real or symbolic) is inside the project’s directory.
This method does not actually check if the path exists, it just checks their locations relative to each other.
Examples
Basic operation
// Project's root directory is /foo/bar
project.contains('/foo/bar/baz') // => true
project.contains('/usr/lib/baz') // => false
Existence of the path is not required
// Project's root directory is /foo/bar
fs.existsSync('/foo/bar/baz') // => false
project.contains('/foo/bar/baz') // => true
| Argument | Type | Description |
|---|---|---|
pathToCheck | String | path |
Returns
Boolean — whether the path is inside the project’s root directory.
Managing Project State1
Open a different project in this window.
Where #setPaths changes the folders and leaves everything else alone —
so the editors open on the old project stay open on the new one — this
changes the whole state: the current folders and the editors open on them
are saved together, and whatever was last saved for projectPaths is
restored in their place. No new window is opened, so packages, themes and
grammars stay loaded.
Only the workspace center is restored. Docks belong to the window rather than to the project it has open, so a tree view, a terminal or a panel keeps running across the change — as does anything a package put there.
Three things are worth knowing before reaching for this:
- Development and safe mode belong to the window, so they cannot change
here. Use
lumine.application.openWindowwithnewWindowfor those. - Each window keeps its own state for a set of folders. If this window has never opened them, it can adopt the most recently saved state only while no other window has that project open.
- Package state stays with the window. A package that follows the project observes #onDidChangePaths and rebuilds itself.
Changes run sequentially, so a second call saves the project left by the
first. Every requested path must name an available directory; a missing
folder or a file rejects the change before the current editors are closed.
Editors retained by docks keep their live buffers and edit history.
Resetting or closing the window cancels pending changes with ABORT_ERR.
| Argument | Type | Description |
|---|---|---|
projectPaths | Array | of String paths to the directories the window should have open. |
Returns
Promise<Boolean> — that resolves to true once the new state is in place, or to false if the window was left as it was — because the paths were already open, none was given, or the user cancelled at the save prompt.
Filesystem Watching1
Access a Promise that resolves when the filesystem watcher associated with a project
root directory is ready to begin receiving events.
This is especially useful in test cases, where it’s important to know that the watcher is ready before manipulating the filesystem to produce events.
| Argument | Type | Description |
|---|---|---|
projectPath | String | One of the project’s root directories. |
Returns
Promise<Object> — The root’s initialized watcher handle. The default backend supplies a FileWatchHandle; directory providers may supply their own handle. The Promise will reject with an error instead if projectPath is not currently a root directory.
File Indexing8
Compile the editor’s ignored-name semantics into an immutable matcher.
Patterns without a slash match a name at any depth. Patterns containing a
slash are rooted at a project directory, and matching a directory excludes
everything beneath it. Paths passed to matches must be relative to the
applicable project root; either path separator is accepted.
The result is a snapshot. Compile it again after the underlying config changes.
| Argument | Type | Description |
|---|---|---|
additionalIgnoredNamesoptional, default: [ | Array<String> | ] - an Array of additional String globs. |
optionsoptional, default: {} | Object | |
useCoreIgnoredNamesoptional | Boolean | whether to include core.ignoredNames; defaults to true. |
Returns
Object — an immutable {patterns, matches(relativePath)} matcher.
Lists the files under the project’s directories.
The crawl runs in a separate process (the bundled ripgrep binary), honors
.gitignore unless told otherwise, and streams results as it finds them
rather than resolving with one large array. Prefer it over walking the
filesystem yourself: core.ignoredNames and core.excludeVcsIgnoredPaths
are respected here in one place.
const crawl = lumine.project.crawl({
didFindPaths: (paths) => results.push(...paths),
});
await crawl;
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
didFindPathsoptional | Function | called with an Array of absolute paths as they are found. Called several times over the life of one crawl. |
directoryPathsoptional | Array<String> | an Array of String paths to crawl. Defaults to the project’s root directories. |
inclusionoptional | String | glob scoping the crawl. ** means “everything”. |
ignoredNamesoptional | Array<String> | an Array of additional String globs to exclude. |
useCoreIgnoredNamesoptional | Boolean | whether to include core.ignoredNames; defaults to true. |
followSymlinksoptional | Boolean | whether to descend into symlinked directories. Defaults to core.followSymlinks. |
excludeVcsIgnoredPathsoptional | Boolean | whether to honor VCS ignore files. Defaults to core.excludeVcsIgnoredPaths. Only takes effect inside a repository — a directory with no .git above it lists everything. |
sortoptional | Boolean | whether to return paths in a stable order. Costs ripgrep its parallel walk, so only ask when the order is observable. |
Returns
Promise — with a cancel() method that resolves the crawl early.
Every file under the project’s root directories.
Files only, and project roots only — for a glob subset, a directory listing,
or anywhere outside the project, use #crawl. The index applies core
policy only (core.ignoredNames, core.excludeVcsIgnoredPaths,
core.followSymlinks), so it is a superset of what any one consumer wants
and a package’s own exclusions stay a cheap filter over it.
Paths are absolute and spelled from the registered root, matching #getPaths and #relativizePath. They are not sorted: sorting costs the crawl its parallel walk, and only one consumer has ever observed the order, so it sorts for itself.
The array is memoized and shared, rebuilt only when the index changes. Do not mutate it — like #getDirectories, this hands back the index’s own array rather than copying six figures’ worth of strings per call.
The first call to any file-path method builds the index and starts the crawl, so this returns an empty array until that settles; see #isIndexing. Ask when the feature that needs it is first used rather than during package activation, or the crawl happens in every window whether anything wanted it or not.
Returns
Array<String> — of String absolute paths.
Every indexed file under one project root.
A file reachable through two nested roots is listed under both, because each root is crawled independently. Memoized and shared on the same terms as #getFilePaths.
| Argument | Type | Description |
|---|---|---|
root | String|Directory | a project root path, or its Directory. |
Returns
Array<String> — of String absolute paths, empty for a path that is not a project root.
Whether a path is in the file index.
Constant time, where scanning #getFilePaths is not. The path must be spelled the way the index spells it: absolute, from the registered root.
This is a different question from #contains, which asks only whether a path lies under a root and answers for a file that is ignored, or that does not exist at all.
| Argument | Type | Description |
|---|---|---|
filePath | String | an absolute path. |
Returns
Boolean
How many files are indexed.
Cheaper than getFilePaths().length, which materializes the array.
Returns
Number
Whether the file index is crawling.
True for the first crawl and for every later refresh alike, so a spinner driven by this shows during background reindexing too.
Returns
Boolean
Crawl the project again and update the file index.
Rarely needed: the index follows #onDidChangeFiles and re-crawls a root by itself when the evidence says it must. Reach for this to back a user-facing “reindex” command, or after changing something on disk that the watcher cannot see. The index is shared, so this re-crawls for every consumer, not just the caller.
Existing contents stay readable and are replaced when the crawl completes, so a refresh does not empty a list the user is looking at.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
rootPathsoptional | Array<String> | An Array of String roots to re-crawl. Defaults to all of them. |
Returns
Promise<void> — that resolves when the crawl settles.
Public API
Rangesrc/range.js:32
Represents a region in a buffer in row/column coordinates.
Full description
Every public method that takes a range also accepts a range-compatible
Array. This means a 2-element array containing Points or point-compatible
arrays. So the following are equivalent:
Examples#
new Range(new Point(0, 1), new Point(2, 3))
new Range([0, 1], [2, 3])
[[0, 1], [2, 3]] // Range-compatible array
Construction4
Convert any range-compatible object to a Range.
| Argument | Type | Description |
|---|---|---|
object | Range|Array<Point|Array<Number>>|Object | A Range, an array containing two point-compatible endpoints, or an object with start and end properties. An existing range is returned unless copying is requested. |
copyoptional, default: false | Boolean | An optional boolean indicating whether to force the copying of objects that are already ranges. |
Returns
Range — A range based on the given object.
Construct a range from a point and independent row and column offsets.
Both offsets are added to the original coordinates. The resulting endpoints are ordered in buffer order, so a negative offset can place the supplied point at the end of the range.
| Argument | Type | Description |
|---|---|---|
startPoint | Point|Array<Number>|Object | A point, a [row, column] array, or an object with row and column properties. |
rowDelta | Number | The number of rows to add to the supplied point. |
columnDelta | Number | The number of columns to add to the supplied point. |
Returns
Range — The range spanning the supplied point and the offset point.
Create a range with the same start and end positions.
Returns
Range — new range with the same start and end positions.
Serialization and Deserialization2
Call this with the result of Range#serialize to construct a new Range.
| Argument | Type | Description |
|---|---|---|
arrayoptional | Array<Array<Number>> | of params to pass to the #constructor |
Returns
Range — The restored range, or an empty range when the input is not an array.
Serialize this range as two row-and-column arrays.
Returns
Array<Array<Number>> — The start and end positions as row-and-column arrays.
Operations5
Create a range with its endpoints negated and reordered.
Returns
Range — new range with the start and end positions negated.
Build and return a new range by translating this range’s start and end points by the given delta(s).
| Argument | Type | Description |
|---|---|---|
startDelta | Point|Array<Number>|Object | A Point by which to translate the start of this range. |
endDeltaoptional | Point|Array<Number>|Object | A Point to by which to translate the end of this range. If omitted, the startDelta will be used instead. |
Returns
Build and return a new range by traversing this range’s start and end points by the given delta.
See Point#traverse for details of how traversal differs from translation.
| Argument | Type | Description |
|---|---|---|
delta | Point|Array<Number>|Object | A Point containing the rows and columns to traverse to derive the new range. |
Returns
Range Details4
Is the start position of this range equal to the end position?
Returns
Boolean
Determine whether this range starts and ends on the same row.
Returns
Boolean — indicating whether this range starts and ends on the same row.
Get the number of rows in this range.
Returns
Number
Get all row numbers touched by this range.
Returns
Array<Number> — Every row from the start row through the end row, inclusive.
Comparison3
Range Queries5
Determines whether this range intersects with the argument.
| Argument | Type | Description |
|---|---|---|
otherRange | Range|Array<Point|Array<Number>>|Object | A Range or range-compatible Array |
exclusiveoptional, default: false | Boolean | indicating whether to exclude endpoints when testing for intersection. Defaults to false. |
Returns
Boolean
Determine whether this range contains another range.
| Argument | Type | Description |
|---|---|---|
otherRange | Range|Array<Point|Array<Number>>|Object | A Range or range-compatible Array |
exclusiveoptional, default: false | Boolean | including that the containment should be exclusive of endpoints. Defaults to false. |
Returns
Boolean — indicating whether this range contains the given range.
Determine whether this range contains a buffer position.
| Argument | Type | Description |
|---|---|---|
point | Point|Array<Number>|Object | A Point or point-compatible Array |
exclusiveoptional, default: false | Boolean | including that the containment should be exclusive of endpoints. Defaults to false. |
Returns
Boolean — indicating whether this range contains the given point.
Determine whether this range intersects a row.
| Argument | Type | Description |
|---|---|---|
row | Number | Row Number |
Returns
Boolean — indicating whether this range intersects the given row Number.
Determine whether this range intersects an inclusive range of rows.
| Argument | Type | Description |
|---|---|---|
startRow | Number | start row |
endRow | Number | end row |
Returns
Boolean — indicating whether this range intersects the row range indicated by the given startRow and endRow Numbers.
Conversion1
Get a string representation of this range.
Returns
String — string representation of the range.
Public API
RepositoryRegistrysrc/repository-registry.js:284
Every Git repository this window knows about, available as
lumine.repositories.
Full description
Project roots are where repositories are discovered and what keeps them alive, but a repository’s identity is independent of them: one root can hold several repositories, one repository can span several roots, and a file opened from outside every root still resolves to the repository that contains it.
Finding a repository#
#getForPath answers from what is already known and never touches the filesystem, which is what a renderer wants. #resolveForPath may discover and register a repository that was not known yet, at the cost of being asynchronous:
const repository = lumine.repositories.getForPath(editor.getPath())
if (repository) console.log(repository.getShortHead())
Following the one the user is in#
#observeActiveRepository tracks the repository behind the active pane item, so a status bar or a panel does not have to work it out itself:
lumine.repositories.observeActiveRepository(({ repository, workingDirectory }) => {
// repository is null when the active item belongs to none
})
Operations#
The registry performs no Git work of its own. A package provides an implementation through #addOperationProvider, and everything under “Operations” and “Running Git” below is routed to whichever provider claims the capability. Ask #canPerformOperation before offering an action, since a window with no provider installed can answer nothing.
Active Repository7
The repository the window is currently working in. It follows the active pane item unless a consumer pinned a selection with #setActiveRepository. An item whose path lies outside every repository clears it; only path-less items keep the current selection.
Returns
GitRepository|null — or null when the active item belongs to none.
The active repository together with the directory it applies to.
The working directory is always present while a file-backed item is focused: it is the repository’s working directory, or, when the item’s path lies outside every repository, the directory a consumer would initialize or clone into — its containing project root, or the item’s own directory.
repositoryThe active GitRepository, ornull.workingDirectoryTheStringdirectory the context applies to, ornullwhen no file-backed item is focused.pinnedABoolean,truewhile a manual selection holds.
Returns
Object — frozen Object.
Whether the active repository is pinned to a manual selection.
Returns
Boolean
Invoke the callback whenever the active repository context changes.
It fires for moves between out-of-repository directories too, while the
repository itself stays null.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with the context #getActiveRepositoryContext |
Returns
Disposable — A subscription that can be disposed to unsubscribe.
Invoke the callback with the current context immediately, and again on every change.
This is what a status bar or a panel wants: it is called once on subscription, so there is no gap to fill in by hand.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with the context #getActiveRepositoryContext |
Returns
Disposable — A subscription that can be disposed to unsubscribe.
Select the active repository manually.
Throws a TypeError if the repository is unregistered or destroyed.
| Argument | Type | Description |
|---|---|---|
repository | GitRepository|null | The GitRepository to activate, or null to clear any pin and recompute the active repository from the workspace. |
optionsoptional, default: {} | Object | Activation options. |
pinoptional, default: false | Boolean | Keep the selection until it is cleared instead of following the next pane-item change. |
Resolve the repository for a path and make it the active one.
Unlike #setActiveRepository this discovers a repository that was not registered yet, so it is asynchronous.
| Argument | Type | Description |
|---|---|---|
filePath | String | The String path to resolve. |
optionsoptional, default: {} | Object | Activation options. |
pinoptional, default: false | Boolean | Keep the selection as in #setActiveRepository. |
Returns
Promise<GitRepository|null> — that resolves to the GitRepository, or to null when the path is not in one.
Accessing Repositories3
The registered repositories together with the version they were read at.
The version increments on every change, so a consumer holding derived state can tell whether its copy is still current without diffing.
versionANumber.repositoriesA frozenArrayof GitRepository.
Returns
Object — frozen Object.
Every registered repository.
This is a snapshot. Use #observeRepositories to keep up with the ones registered later.
Returns
Array<GitRepository> — of GitRepository.
Look a repository up by the id the registry gave it.
| Argument | Type | Description |
|---|---|---|
id | String | The String id. |
Returns
GitRepository|null — or null if nothing is registered under it.
Event Subscription10
Invoke the callback with every registered repository, now and in the future.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with each GitRepository. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the callback when a repository is registered.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with the new GitRepository. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the callback when a repository is removed.
Release anything keyed on the repository here: it is destroyed once nothing holds it any more.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with the removed GitRepository. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Observe cached state or available-operation changes in registered repositories. The subscription is passive: it does not load snapshots, retain repositories, create operation implementations or perform Git or filesystem reads. Registration and removal remain available through their separate events.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with a frozen {repository} object. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the callback once per batch of changes to the registered set, with everything that changed together.
Cheaper than the individual events when a consumer rebuilds derived state, since adding a project root registers many repositories at once.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with a frozen Object. |
version | Number | The Number the registry is now at. |
added | Array<GitRepository> | An Array of newly registered GitRepository. |
removed | Array<GitRepository> | An Array of GitRepository no longer registered. |
updated | Array<GitRepository> | An Array of GitRepository whose routing changed. |
rootsAdded | Array<String> | An Array of String project roots added. |
rootsRemoved | Array<String> | An Array of String project roots removed. |
routingChangedPrefixes | Array<String> | An Array of String directories whose path-to-repository routing is no longer what it was. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the callback when a rescan of the project roots begins.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with a frozen Object. |
id | Number | A Number identifying this rescan. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the callback when a rescan finishes, whether or not it succeeded.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with a frozen Object. |
id | Number | The Number of the rescan that started. |
repositories | Array<GitRepository> | A frozen Array of the GitRepository it found. |
error | Error|null | The Error that ended the scan, or null. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the callback when an operation is queued behind another on the same repository.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with an operation snapshot; see #getPendingOperations. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the callback when an operation starts running.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with an operation snapshot; see #getPendingOperations. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the callback when an operation finishes, whether or not it succeeded.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with an operation snapshot; see #getPendingOperations. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Resolving Paths5
The repository a path belongs to, from what is already registered.
Synchronous and free of filesystem access, so it is safe on a hot path such as rendering a gutter. When several repositories contain the path, the one with the longest matching working directory wins, which is what a submodule or a nested checkout should do. Use #resolveForPath when the path may belong to a repository nobody has discovered yet.
| Argument | Type | Description |
|---|---|---|
filePath | String | The String path to look up. |
Returns
GitRepository|null — or null.
Observe the current repository of a changing file path, including discovery, routing changes, repository destruction and initial snapshot readiness.
| Argument | Type | Description |
|---|---|---|
getPath | Function | Returns the current absolute path or null. |
callback | Function | Receives the repository and {path, ready, error}. |
optionsoptional | Object | onDidChangePath subscription and snapshots selection. |
Returns
Disposable — disposing discovery delivery and repository retention.
Combine Git’s cached path status with a buffer’s persistence state.
Returns null outside a repository or before its status (including ignored
paths) is ready. Git ignore rules, conflicts and untracked files take
precedence over unsaved edits. canDiff identifies paths with a usable
Git baseline; directory summaries should only aggregate buffers owned by
that directory’s repository. No filesystem access or Git process occurs.
| Argument | Type | Description |
|---|---|---|
filePath | String | Absolute path of the buffer’s backing file. |
optionsoptional, default: {} | Object | Buffer and repository context. |
fileStateoptional, default: "unmodified" | String | Current buffer persistence state. |
pendingSaveoptional, default: false | Boolean | Preserve the unsaved status until a post-save Git snapshot arrives. |
repositoryoptional | GitRepository|null | Already resolved repository; otherwise uses the registry’s cached owner. |
Returns
Object|null — Frozen {status, staged, unstaged, ignored, conflicted, untracked, canDiff, bufferModified} summary, or null when Git status is unavailable.
Resolve the context of a repository or file command. Repository commands honor the selected/pinned repository; file commands honor their target editor.
| Argument | Type | Description |
|---|---|---|
eventoptional | Object | Command dispatch event. |
optionsoptional, default: {} | Object | scope, either repository or file. |
Returns
Object — frozen {repository, editor, path} context.
The repository a path belongs to, discovering and registering one if it is not known yet.
| Argument | Type | Description |
|---|---|---|
filePath | String | The String path to resolve. |
optionsoptional, default: {} | Object | Discovery options. |
refreshoptional, default: true | Boolean | Run discovery again instead of using its exact-path cache. |
Returns
Promise<GitRepository|null> — that resolves to a GitRepository, or to null when the path is not in one.
Managing Repositories4
Keep a repository alive for as long as you hold the result.
A repository is destroyed once nothing owns it — no project root contains it, no open buffer belongs to it. Retain one you intend to keep using across those changes, and dispose the result when you are done, or it will outlive its usefulness.
| Argument | Type | Description |
|---|---|---|
repository | GitRepository | The GitRepository to hold. |
sourceoptional, default: "pin" | String | A String label for the hold, for debugging. |
Returns
Disposable — that releases the hold.
Register the repository containing a path, and keep it.
For a repository the user chose that no project root covers. It is held until the returned handle is disposed, and by default remembered across window reloads.
repositoryThe GitRepository.disposeAFunctionthat releases it.
| Argument | Type | Description |
|---|---|---|
filePath | String | The String path inside the repository to add. |
optionsoptional, default: {} | Object | Registration options. |
persistoptional, default: true | Boolean | Remember the repository across window reloads. Pass false to keep it for this session only. |
Returns
Promise<Object|null> — that resolves to an Object, or to null when no live repository remains registered after discovery.
Drop every manual hold #add placed on a repository.
The repository stays registered while a project root or an open buffer still owns it.
| Argument | Type | Description |
|---|---|---|
repository | GitRepository | The GitRepository to forget. |
Returns
Boolean — true if the repository was registered.
Discover the current repository set again, then refresh every repository’s already-active caches and snapshots.
Snapshot caches stay lazy: a status or refs snapshot that no consumer has initialized is not loaded merely because of an update. A refresh failure in one repository does not prevent the others from updating.
Returns
Promise<Array<GitRepository>> — that resolves to an Array of every registered GitRepository.
Operations8
Run your own work against a repository, holding it alive for the duration.
#retain for the length of one asynchronous call, without the bookkeeping.
Throws an Error if the repository cannot be registered.
| Argument | Type | Description |
|---|---|---|
repository | GitRepository | The GitRepository to work with. |
operation | Function | An async Function called with the repository. |
Returns
Promise<*> — for whatever the operation returned.
Supply the Git implementation behind the registry’s operations.
The registry routes work but performs none of it. A provider implements at
least one of createRepositoryOperations, initializeRepository,
cloneRepository or executeGit, and the first provider claiming a
capability handles it.
Throws a TypeError if the provider implements none of those methods, and
an Error if the registry has been destroyed.
| Argument | Type | Description |
|---|---|---|
provider | Object | The Object implementing the operations. |
optionsoptional, default: {} | Object | Provider options. |
fallbackoptional, default: false | Boolean | Put the provider last so later registrations take precedence. |
Returns
Disposable — that removes the provider and everything it implemented.
The operations available on a repository.
| Argument | Type | Description |
|---|---|---|
repository | GitRepository | The GitRepository. |
Returns
Object|null — The stable operation facade, or null when the repository is not registered. Use #canPerformOperation to check which methods providers can run.
Whether an operation can be performed on a repository right now.
Ask before offering an action. A window where no package provides Git can answer nothing, and the honest response is to hide the command rather than to fail when it is invoked.
| Argument | Type | Description |
|---|---|---|
repository | GitRepository | The GitRepository. |
operationName | String | The String name of the operation, such as "commit". |
Returns
Boolean
Every operation any provider can perform on a repository.
| Argument | Type | Description |
|---|---|---|
repository | GitRepository | The GitRepository. |
Returns
Array<String> — frozen Array of String operation names.
The operations queued or running right now.
Operations on one repository run one at a time, so a long fetch leaves the next one queued. This is what a progress indicator reads.
idANumberidentifying the operation.nameTheStringoperation name.statusAString,"queued"or"running".workingDirectoryTheStringdirectory it runs in, ornull.queuedAtTheNumbertimestamp it was queued at.startedAtTheNumbertimestamp it started at, ornull.
| Argument | Type | Description |
|---|---|---|
repositoryoptional | GitRepository | The GitRepository to report on. Omit it for every repository, plus the workspace operations that belong to none. |
Returns
Array<Object> — frozen Array of frozen Objects.
Execute a complete workflow in one repository write turn. The callback gets direct operations that share the turn and never enqueue behind themselves.
| Argument | Type | Description |
|---|---|---|
repository | GitRepository | Repository retained for the workflow. |
name | String | Workflow name used in operation progress events. |
callback | Function | Receives direct operations. |
optionsoptional, default: {} | Object | signal, expectedHead, guards, refresh selection. |
Returns
Promise<*> — callback result, with partial/unknown outcomes on failure.
Fetch, pull or push the selected repository’s current branch using a fresh remote/upstream snapshot inside the same serialized workflow.
| Argument | Type | Description |
|---|---|---|
repository | GitRepository | Repository to act on. |
name | String | fetch, pull or push. |
optionsoptional, default: {} | Object | Named operation options. |
Returns
Promise<*> — the named operation result.
Creating Repositories4
Which of initialize and clone a provider can perform.
These belong to no repository — they are what creates one — so they are asked for separately from #getOperationCapabilities.
Returns
Array<String> — frozen Array of String operation names.
Whether a repository-creating operation can be performed.
| Argument | Type | Description |
|---|---|---|
operationName | String | A String, "initialize" or "clone". |
Returns
Boolean
Create a repository in a directory and register it.
| Argument | Type | Description |
|---|---|---|
directoryPath | String | The String directory to initialize. |
optionsoptional | Object | passed through to the provider. |
Returns
Promise<GitRepository> — that resolves to the new GitRepository. It rejects when no provider implements initialize, and with an Error whose code is ERR_REPOSITORY_DISCOVERY_FAILED if the command succeeded but nothing was found at the path afterwards.
Clone a remote into a directory and register the result.
| Argument | Type | Description |
|---|---|---|
remoteUrl | String | The String URL to clone. |
destinationPath | String | The String directory to clone into. |
optionsoptional | Object | passed through to the provider. |
Returns
Promise<GitRepository> — that resolves to the new GitRepository, and rejects the same way #initialize does.
Running Git2
Whether any provider can run raw Git commands.
Returns
Boolean
Run a Git command through whichever provider offers one.
The escape hatch for what the operation set does not cover. Prefer a named operation where one exists — it is the part a provider can implement without shelling out.
| Argument | Type | Description |
|---|---|---|
args | Array<String> | An Array of String arguments, without the leading git. |
workingDirectory | String | The String directory to run in. |
optionsoptional | Object | passed through to the provider. |
Returns
Promise<*> — for the provider’s result. It rejects with a TypeError if args is not an array, and with an Error whose code is ERR_GIT_EXECUTION_UNAVAILABLE when no provider runs Git commands.
Public API
RuntimeServicesrc/runtime-service.js:7
Renderer-runtime readiness and unhandled-error events.
Event Subscription2
Subscribe before an unhandled renderer error is reported.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives error details and preventDefault(), which suppresses opening the developer tools. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Subscribe after an unhandled renderer error is reported.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives the reported renderer error details. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Shell Environment2
Wait until the current renderer has loaded its shell environment.
Returns
Promise<void> — that resolves once environment loading is complete.
Get the time taken to load the shell environment.
Returns
Number|null — The shell-environment load time captured at bootstrap, or null when no timing was recorded.
Extended API
ScopeDescriptorsrc/scope-descriptor.js:25
Wraps an Array of Strings. The Array describes a path from the
root of the syntax tree to a token including all scope names for the entire
path.
Full description
Methods that take a ScopeDescriptor will also accept an Array of String
scope names e.g. ['.source.js'].
You can use ScopeDescriptors to get language-specific config settings via
Config#get.
You should not need to create a ScopeDescriptor directly.
- TextEditor#getRootScopeDescriptor to get the language’s descriptor.
- TextEditor#scopeDescriptorForBufferPosition to get the descriptor at a specific position in the buffer.
- Cursor#getScopeDescriptor to get a cursor’s descriptor based on position.
See the scopes and scope descriptor guide for more information.
Construction1
Create a ScopeDescriptor object.
| Argument | Type | Description |
|---|---|---|
object | Object | Scope data. |
scopes | Array<String> | The ordered syntax scopes. |
Scope Details1
Get the ordered syntax scope names.
Returns
Array<String> — The ordered, non-empty syntax scope names.
Public API
ScrollbarManagersrc/scrollbar-manager.js:18
Shared scrollbar presentation and local geometry for document and package views.
Access this namespace through lumine.scrollbars.
DOM Surfaces1
Attach shared scrollbar chrome without wrapping or reparenting the scrollport.
| Argument | Type | Description |
|---|---|---|
element | HTMLElement | Existing DOM scrollport. |
optionsoptional, default: {} | Object | kind (document, panel or inline), layout (overlay or gutter), policy (auto, always or hover), edge (left or right), focusOwner, zIndex and horizontal/vertical axis overrides. Kind selects semantic defaults: persistent document overlays with a separator, transient panel overlays, or reserved always-visible inline gutters. Location supplies the default kind; explicit options or data-scrollbar-kind can select a utility panel even in the center. |
Returns
Object|null — A controller with refresh() and dispose(), or null for an inert document.
Geometry3
Read track thickness and viewport/document extents in CSS pixels. Thickness stays stable when a thumb is hidden or content fits the viewport.
| Argument | Type | Description |
|---|---|---|
element | HTMLElement | Editor element or native DOM scrollport. |
Returns
Object — layout (overlay or gutter); CSS-pixel verticalSize and horizontalSize track thicknesses, viewportWidth and viewportHeight excluding reserved gutters, verticalTrackSize and horizontalTrackSize lengths (vertical spans the full height including any horizontal gutter, horizontal excludes the vertical rail), scrollWidth and scrollHeight, canScrollVertically and canScrollHorizontally. Editor snapshots also include rowGeometryVersion for marker projection invalidation.
Obtain the local vertical track for a noninteractive marker canvas. A DOM scrollport is attached to the shared manager if needed.
| Argument | Type | Description |
|---|---|---|
element | HTMLElement | Editor element or native DOM scrollport. |
Returns
HTMLElement|null — Track owned by this scroll surface.
Observe geometry changes, independently of thumb movement.
| Argument | Type | Description |
|---|---|---|
element | HTMLElement | Editor element or native DOM scrollport. |
callback | Function | Receives an immediate getGeometry(element) snapshot, then changed layout or geometry; scroll position alone does not trigger it. |
Returns
Disposable — Removes exactly this observation.
Isolated Documents1
Get the same DOM scrollbar runtime and styles for a trusted isolated frame.
Returns
String — Standalone browser script; contains no Node integration.
Public API
SecretStoresrc/secret-store.js:36
Somewhere to keep an access token, available as lumine.secrets.
Full description
For the sensitive strings a package must remember between sessions — a
forge token, an API key, a password. Never lumine.config: everything in
there is written to disk in plain text and shown in the settings view.
Keys are opaque strings and values are strings. Namespace your own keys, by convention with the package name:
await lumine.secrets.set('github.token', token)
const token = await lumine.secrets.get('github.token')
Storage#
Values are encrypted with the operating system’s own facility — DPAPI on Windows, the Keychain on macOS, libsecret or kwallet on Linux — and kept as base64 in one file under the config directory.
Where the OS offers no encryption, typically a headless Linux box with no
keyring, the store keeps values in memory for the session only and warns the
user once. It never writes a secret to disk in the clear. A package should
therefore expect #get to return null for something it stored in an
earlier session, and ask again rather than fail.
Encryption1
Storing Secrets3
Read a secret.
| Argument | Type | Description |
|---|---|---|
key | String | The String key it was stored under. |
Returns
Promise<String|null> — that resolves to the String value, or to null when nothing is stored under the key or it can no longer be decrypted — which happens after the OS credential store is reset, or when this session has no encryption and an earlier one did.
Store a secret.
| Argument | Type | Description |
|---|---|---|
key | String | The String key to store it under. |
value | String|null|undefined |
Returns
Promise<void> — that resolves once the value is written.
Forget a secret.
Deleting a key that was never stored is not an error and emits nothing.
| Argument | Type | Description |
|---|---|---|
key | String | The String key to remove. |
Returns
Promise<void> — that resolves once the key is gone.
Event Subscription1
Invoke the callback when a secret is stored or removed.
The event names the key but never carries the value; read it with #get if you need it.
| Argument | Type | Description |
|---|---|---|
callback | Function | called with an Object. |
key | String | The String key that changed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Extended API
Selectionsrc/selection.js:41
Represents a selection in the TextEditor.
Event Subscription2
Calls your callback when the selection was moved.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
oldBufferRange | Range | |
oldScreenRange | Range | |
newBufferRange | Range | |
newScreenRange | Range | |
textChanged | Boolean | whether a buffer text change moved the selection. |
origin | String | edit, undo, redo, reload, or mixed; identifies history replay and buffer reloads independently of textChanged. |
selection | Selection | that triggered the event |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when the selection was destroyed
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Managing the Selection Range5
Modifies the screen range for the selection.
| Argument | Type | Description |
|---|---|---|
screenRange | Range|Array|Object | The new Range to use. |
optionsoptional | Object | options matching those found in #setBufferRange. |
Modifies the buffer Range for the selection.
| Argument | Type | Description |
|---|---|---|
bufferRange | Range|Array|Object | The new Range to select. |
optionsoptional, default: {} | Object | with the keys: |
reversedoptional | Boolean | indicating whether to set the selection in a reversed orientation. |
preserveFoldsoptional | Boolean | if true, the fold settings are preserved after the selection moves. |
autoscrolloptional | Boolean | indicating whether to autoscroll to the new range. Defaults to true if this is the most recently added selection, false otherwise. |
modeoptional | String|Number|Array<Number> | The scroll mode when autoscrolling. See TextEditor#scrollToScreenRange. |
flashoptional, default: false | Boolean | Flash the selection decoration after moving it. |
Get the first and last buffer rows touched by the selection.
Returns
Array<Number> — The starting and ending buffer rows highlighted by the selection.
Selection Details6
Determine whether the selection contains no text.
Returns
Boolean — Whether the selection contains no text.
Determine whether the selection’s head precedes its tail in buffer coordinates.
Returns
Boolean — Whether the selection head precedes its tail.
Determine whether the selection fits on one screen line.
Returns
Boolean — whether the selection is a single line or not.
Get the selected text.
Returns
String — text in the selection.
Folds1
Creates a fold containing the current selection.
Managing Multiple Selections3
Add a similarly shaped selection on the next eligible screen row below.
Add a similarly shaped selection on the next eligible screen row above.
Combines the given selection into this selection and then destroys the given selection.
| Argument | Type | Description |
|---|---|---|
otherSelection | Selection | A Selection to merge with. |
optionsoptional, default: {} | Object | options matching those found in #setBufferRange. |
Comparison1
Compare this selection’s buffer range to another selection’s buffer range.
See Range#compare for more details.
Returns
Number — -1, 0, or 1 according to the ordering of the selection ranges.
Experimental API
SelectListsrc/select-list.js:82
Extends InputDialog
Detached fuzzy-searchable select-list model. Extends InputDialog with items, filtering, selection and list rendering. Call InputDialog#getElement to lazily create its unmounted surface, or use Workspace#addSelectList to give it a modal host.
Full description
Hosted lists support keep-open mode by default. Set supportsKeepOpen: false
for a surface that must finish after one choice. Individual terminal actions
in a repeatable list declare disposition complete.
A flat items source may also supply overflowSections, an alternative
grouping of exactly the same items. It applies only while the unfiltered
list actually overflows its viewport; shorter lists retain their natural
order without section separators. Pass null to remove this alternative.
Built-in fuzzy search uses a dedicated Chromium worker per list by default,
regardless of list size. It prepares text, scores, sorts and traces the first
page. Set search.worker: false for a list known to always be small; this
path prepares candidates on demand and matches synchronously.
Set search.prepareOnIdle: true to prepare the worker’s candidates before
a query when getFilterText is pure. This option applies only to workers.
Source replacement and destruction cancel pending preparation.
While the worker filters, the previous rows remain visible and selection
and actions cannot confirm a stale match. A spinner replaces the action
affordance after 250 ms of continuous filtering; superseding a query does
not restart that delay. Source loading retains its separate loading message.
All matches are published together, and setQuery() resolves after rendering.
New input, source changes and destruction cancel obsolete requests.
Query sources, custom matchers and custom filters retain their own execution contract. Custom sort callbacks still run on the UI thread after worker ranking. Pure score modifiers run there in yielding batches; only numeric scores cross back to the worker. There is no global backend setting.
A recents adapter’s save(ids, change) receives the operation’s intent:
{type: 'record'|'remove'|'clear'|'limit'|'replace', id?, limit}. Apply it to
the latest stored IDs with updateRecentItemIds inside a scoped
state’s mutate() callback. Returning the committed IDs synchronizes a
successful no-op too; returning nothing remains valid for other adapters.
Set adapter.serializesWrites: true when the adapter owns write ordering.
Core then invokes save immediately, letting scoped state capture the current
project before a rebind. Other adapters retain core’s serial save queue.
Project adapters notify onDidChange on a project rebind even when the IDs
are equal. Use the scoped state’s observe() subscription, skipping its
initial callback, so a pending save cannot project into a different project.
Destroy this model with the inherited InputDialog#destroy; calling the inherited InputDialog#confirm delegates to #confirmSelection.
Actions3
Return whether successful actions keep this list open for another use. Actions declaring complete still close the list.
Returns
Boolean
Return whether this list supports keep-open mode.
Returns
Boolean — False for an explicit supportsKeepOpen opt-out and internal action lists.
Set this session’s keep-open mode. Fresh modal sessions start with it off.
| Argument | Type | Description |
|---|---|---|
keepOpen | Boolean | Whether ordinary close actions leave the list open. |
Returns
Promise<void> — Resolves after the view updates.
Event Subscription6
Invoke a callback when the session’s keep-open mode changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives an event with list and keepOpen. |
Returns
Disposable — Dispose to unsubscribe.
Invoke a callback when source items change.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
list | SelectList | |
items | Array<*> |
Returns
Disposable — Dispose to unsubscribe.
Invoke a callback when the logical selection changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
list | SelectList | |
item | * | The selected source item, or null for a selection-change event. |
itemId | * | Its stable ID, or null. |
index | Number|null | |
previousItem | * | |
reason | String |
Returns
Disposable — Dispose to unsubscribe.
Invoke a callback when recent item IDs change.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
list | SelectList | |
recentItemIds | Array<*> |
Returns
Disposable — Dispose to unsubscribe.
Invoke a callback when confirmation has no primary item action.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
list | SelectList | |
item | * | The selected source item, or null for a selection-change event. |
itemId | * | Its stable ID, or null. |
Returns
Disposable — Dispose to unsubscribe.
Invoke a callback when an empty selection is confirmed.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
list | SelectList |
Returns
Disposable — Dispose to unsubscribe.
Query1
Return the parsed search text and package metadata.
Returns
Object — A frozen {text, data} record; data is the arbitrary metadata returned by search.parseQuery.
Asynchronous Sources1
Replace the asynchronous source and keep local filtering aligned with its mode. Query sources own filtering; snapshot sources and a null source use the list’s current parsed query.
| Argument | Type | Description |
|---|---|---|
source | Object|null | Source options accepted by InputDialog.setSource; query sources own filtering. |
Returns
Promise<void>
Items8
Return a snapshot of all source items.
Returns
Array<*>
Prepare an immutable source snapshot without publishing it. Source loaders may await this before returning {items}; cancellation leaves the list intact.
| Argument | Type | Description |
|---|---|---|
items | Array | Frozen array whose items and IDs will not be mutated. |
options | Object | Optional AbortSignal in signal. |
Returns
Promise<Array> — The same array, ready for a subsequent update.
Return the number of source items.
Returns
Number
Replace a flat item source while preserving selection by default.
| Argument | Type | Description |
|---|---|---|
items | Array<*> | Replacement source. |
optionsoptional, default: {} | Object | Selection behavior for this update. |
selectionoptional | Object | Override selection with {mode: “first”}, {mode: “none”}, or {id}. Otherwise preserve selection by stable ID when possible. |
Returns
Promise<void>
Replace the source with explicitly grouped sections.
| Argument | Type | Description |
|---|---|---|
sections | Array<Object> | Section records with a required non-null primitive id and items array; additional section metadata is retained. |
optionsoptional, default: {} | Object | Selection behavior for this update. |
selectionoptional | Object | Override selection with {mode: “first”}, {mode: “none”}, or {id}. Otherwise preserve selection by stable ID when possible. |
Returns
Promise<void>
Re-render the current source after items changed in place.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Selection options accepted by setItems/setSections. |
Returns
Promise<void>
Recompute ranking after state captured by search.scoreModifier changes. Prepared candidate text and the existing worker remain reusable.
Returns
Promise<void>
Returns the stable identifier used by the model for an item. Object
items default to their id property; primitive items identify themselves.
| Argument | Type | Description |
|---|---|---|
item | * | A source item. |
Returns
* — A non-null primitive stable ID from getItemId, object.id, or a primitive item.
Filtering4
Return all items in current filtered order.
Returns
Array<*>
Return the number of filtered matches.
Returns
Number
Returns the filter key for an item.
| Argument | Type | Description |
|---|---|---|
item | * | A source item. |
Returns
String|null
Returns the match indices for an item, computing lazily if needed. Match indices indicate which characters in the filter key matched the query.
| Argument | Type | Description |
|---|---|---|
item | * | A source item. |
filterKeyoptional | String | Use this filter text instead of deriving it from the item. |
Returns
Array<Number>|null
Pagination5
Return the currently displayed page without UI rows.
Returns
Array<*>
Reveals the next batch of matches in place of the “Show more…” row. The first newly revealed item takes the selection — it sits exactly where the row was.
Pressing the row (a click, or Enter while it is highlighted) keeps the
scroller where it is, so the list never jumps under the pointer. Keyboard
navigation that lands on the row from afar — Ctrl-End crossing the whole
list — passes followSelection: true instead, and the viewport moves to
the newly selected item like any other selection change.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Paging options. |
followSelectionoptional, default: false | Boolean | Scroll to the first newly revealed item instead of preserving the viewport. |
Returns
Promise<Boolean>
Return whether another result page remains.
Returns
Boolean
Return the number of matches beyond the displayed page.
Returns
Number
Collapse displayed results to the first page.
Returns
Promise<void>
Selection11
Return the selected package item, or null.
Returns
* — The selected source item, or null when no item is selected.
Return the stable ID of the selected item, or null.
Returns
* — The selected non-null primitive stable ID, or null when none is selected.
Return the selected filtered index, or null.
Returns
Number|null
Select the previous item, respecting the optional empty state.
Returns
Promise<void|Boolean>
Select the next item, revealing another page when needed.
Returns
Promise<void|Boolean>
Select the first matching item.
Returns
Promise<void|Boolean> — Resolves after selection or after revealing another page.
Select the last item in the displayed page.
Returns
Promise<void|Boolean> — Resolves after selection or after revealing another page.
Clear the logical selection.
Returns
Promise<void>
Select an item by its displayed index.
| Argument | Type | Description |
|---|---|---|
index | Number|undefined | Displayed index, or undefined to clear selection; out-of-bounds indices wrap. |
updateComponentoptional, default: true | Boolean | Schedule rendering when true. |
reasonoptional, default: "programmatic" | String | Included in the selection-change event. |
Returns
Promise<void>
Select an item by value or object identity.
| Argument | Type | Description |
|---|---|---|
item | * | A source item. |
Returns
Promise<void>
Select an item by stable ID.
| Argument | Type | Description |
|---|---|---|
id | * | A non-null primitive item ID; throws when absent from the source. |
Returns
Promise<void>
Scrolling4
Return the list viewport’s vertical scroll offset.
Returns
Number
Set the list viewport’s vertical scroll offset.
| Argument | Type | Description |
|---|---|---|
scrollTop | Number | Vertical offset in pixels; has no effect before materialization. |
Returns
void
Select and reveal an item or stable ID.
| Argument | Type | Description |
|---|---|---|
itemOrId | * | A source item or its non-null primitive stable ID. |
Returns
Boolean
Reveal the currently selected row.
Returns
Boolean
Recent Items8
Return recent item IDs in most-recent-first order.
Returns
Array<*>
Replace and optionally persist recent item IDs.
| Argument | Type | Description |
|---|---|---|
recentIds | Array<*> | Non-null primitive item IDs in most-recent-first order. |
optionsoptional, default: {} | Object | Persistence options. |
persistoptional, default: true | Boolean | Save through the configured recents adapter. |
Returns
Promise<SelectList>
Return the configured maximum recent item count.
Returns
Number
Set the maximum recent item count and trim persisted state.
| Argument | Type | Description |
|---|---|---|
limit | Number | A non-negative integer or Infinity. Requires a configured recents adapter. |
Returns
Promise<SelectList>
Return whether an item or stable ID is recent.
| Argument | Type | Description |
|---|---|---|
itemOrId | * | A source item or its non-null primitive stable ID. |
Returns
Boolean
Move an item to the front of the recent section.
| Argument | Type | Description |
|---|---|---|
item | * | A source item. |
Returns
Promise<SelectList>
Remove an item from the recent section.
| Argument | Type | Description |
|---|---|---|
itemOrId | * | A source item or its non-null primitive stable ID. |
Returns
Promise<SelectList>
Clear the recent section.
Returns
Promise<SelectList>
Confirmation1
Confirms the current selection through the applicable primary action, or emits the corresponding confirmation event when none is declared.
Returns
Promise<Object|Boolean>|undefined — Primary action completion, a paging result for the Show more row, or undefined after a confirmation event.
Experimental API
SelectListHostsrc/select-list-host.js:13
Extends InputDialogHost
Modal host for a detached SelectList model. It inherits the complete visibility, focus, modal-flow and session lifecycle of InputDialogHost while narrowing #getModel to SelectList.
Model and Panel1
Return the complete detached select-list model.
Returns
Public API
ServiceHubsrc/service-hub.js:154
Methods4
Provide a service by invoking the callback of all current and future consumers matching the given service name and version range.
| Argument | Type | Description |
|---|---|---|
keyPath | String | A String naming the service. Names are matched exactly. A . is a grouping convention for related services (linter.provider, linter.registry) and carries no lookup meaning: consuming linter does not match a provider of linter.provider. |
version | String|Object | A semantic version, or an object mapping version strings to services when service is omitted. |
serviceoptional | * | The service API supplied at version; omit it when passing a version-to-service map. |
Returns
Disposable — on which .dispose() can be called to remove the provided service.
Consume a service by invoking the given callback for all current and future provided services matching the given service name and version range.
| Argument | Type | Description |
|---|---|---|
keyPath | String | A String naming the service. Names are matched exactly; see #provide. |
versionRange | String | A String containing a semantic version range that any provided services for the given service name must satisfy. |
callback | Function | A Function to be called with current and future matching services. |
Returns
Disposable — on which .dispose() can be called to remove the consumer. Disposing it also disposes whatever the callback returned, so a package that deactivates unregisters itself from the services it took.
Names consumed by someone and provided by no one.
Deliberately not reported on its own: a consumer with no provider is
ordinary when an optional package is disabled. It is a question to ask at
a moment the caller chooses – a diagnostic command, timecop – rather
than a warning this class can time correctly.
Returns
Array<Object> — of {keyPath, versionRange}.
Clear out all service consumers and providers, disposing of any disposables returned by previous consumers.
Public API
ShellServicesrc/shell-service.js:9
Operating-system shell integrations.
File Operations3
Move an item to the operating system trash.
| Argument | Type | Description |
|---|---|---|
filePath | String | The filesystem path to move to the trash. |
Returns
Promise<void> — that resolves when the operation completes.
Reveal a path in the operating system file browser.
| Argument | Type | Description |
|---|---|---|
filePath | String | The filesystem path to reveal. |
Returns
Promise<void> — that resolves when the request completes.
Open a path with its operating system default application.
Rejects when the path is unavailable, the system refuses the request, or the operating-system request does not settle within 60 seconds. A timed-out system operation may still complete later.
| Argument | Type | Description |
|---|---|---|
filePath | String | The filesystem path to open. |
Returns
Promise<void> — that resolves when the request completes.
Application Launching1
Launch a GUI application directly from the main process, independently of the editor’s lifetime. Arguments are passed literally without a shell.
| Argument | Type | Description |
|---|---|---|
executablePath | String | Absolute path to the application executable. |
argsoptional, default: [] | Array<String> | Literal application arguments. |
optionsoptional, default: {} | Object | An optional absolute working directory in cwd. |
Returns
Promise<Number> — resolving to the process ID when the application starts, or rejecting if it cannot start. Window activation remains subject to the operating system and the application’s own behavior.
External URLs1
Open an HTTP, HTTPS, or mailto URL with its operating system default handler.
Relative, malformed, and other-scheme URLs are rejected before they reach the operating system. Requests that do not settle within 60 seconds reject; the operating-system operation may still complete later.
| Argument | Type | Description |
|---|---|---|
url | String | An absolute HTTP, HTTPS, or mailto URL. |
Returns
Promise<void> — that resolves when the request completes.
Extended API
StorageScopesrc/package-storage.js:283
Package-owned JSON values in one persistent scope. Package lifecycle hooks
receive these handles as context.globalState and context.workspaceState.
Global values are shared by every window and project in the profile. Workspace
values follow the set of project roots; an empty workspace uses the persistent
window identity. Existing workspace handles and observers follow scope changes.
Values are detached JSON data. Writes become visible after their durable
transaction commits, before the returned promise resolves.
Full description
Methods6
Return a detached cached value, or the default when this key is absent.
| Argument | Type | Description |
|---|---|---|
key | String | Package-owned key. |
defaultValueoptional | * | JSON value returned for an absent key. |
Returns
* — A detached JSON value, or undefined when absent without a default.
List this package’s keys in the selected scope.
Returns
Array<String> — Stored keys, excluding removed values.
Persist a JSON value, or remove the key when the value is undefined.
The input is detached when this method is called.
| Argument | Type | Description |
|---|---|---|
key | String | Package-owned key. |
value | * | JSON value to persist, or undefined to remove the key. |
Returns
Promise<void> — Resolves after the transaction commits.
Atomically update the latest persisted value, including writes from other
windows. The pure updater runs synchronously inside a short transaction and
receives a detached value, or undefined for an absent key. It must return
JSON data, or undefined to remove the key, and must not perform I/O or
modify other storage keys. This is a Lumine extension to the memento API.
| Argument | Type | Description |
|---|---|---|
key | String | Package-owned key. |
updater | Function | Synchronous function returning the replacement value. |
Returns
Promise<*> — Resolves to the committed, detached value.
Call immediately with the cached value, then after committed changes. An
absent key supplies undefined. A workspace observer also runs when its
handle follows different project roots, even when the value is unchanged.
| Argument | Type | Description |
|---|---|---|
key | String | Package-owned key. |
callback | Function | Receives a detached current value and readonly {scopeChanged} metadata. The flag is true only when an existing workspace handle follows different project roots. |
Returns
Disposable — Stops observing when disposed.
Observe value changes without an immediate callback. Workspace scope changes emit only when the old and new values differ.
| Argument | Type | Description |
|---|---|---|
key | String | Package-owned key. |
callback | Function | Receives {oldValue, newValue} with detached values and readonly {scopeChanged} metadata. |
Returns
Disposable — Stops observing when disposed.
Extended API
StyleManagersrc/style-manager.js:16
A singleton instance of this class available via lumine.styles,
which you can use to globally query and observe the set of active style
sheets. The StyleManager doesn’t add any style elements to the DOM on its
own, but is instead subscribed to by individual <lumine-styles> elements,
which clone and attach style elements in different contexts.
Event Subscription4
Invoke callback for all current and future style elements.
| Argument | Type | Description |
|---|---|---|
callback | Function | that is called with style elements. |
styleElement | HTMLStyleElement | An HTMLStyleElement instance. The .sheet property will be null because this element isn’t attached to the DOM. If you want to attach this element to the DOM, be sure to clone it first by calling .cloneNode(true) on it. The style element will also have the following non-standard properties: |
sourcePath | String | A String containing the path from which the style element was loaded. |
context | String | A String indicating the target context of the style element. |
Returns
Disposable — on which .dispose() can be called to cancel the subscription.
Invoke callback when a style element is added.
| Argument | Type | Description |
|---|---|---|
callback | Function | that is called with style elements. |
styleElement | HTMLStyleElement | An HTMLStyleElement instance. The .sheet property will be null because this element isn’t attached to the DOM. If you want to attach this element to the DOM, be sure to clone it first by calling .cloneNode(true) on it. The style element will also have the following non-standard properties: |
sourcePath | String | A String containing the path from which the style element was loaded. |
context | String | A String indicating the target context of the style element. |
Returns
Disposable — on which .dispose() can be called to cancel the subscription.
Invoke callback when a style element is removed.
| Argument | Type | Description |
|---|---|---|
callback | Function | that is called with style elements. |
styleElement | HTMLStyleElement | An HTMLStyleElement instance. |
Returns
Disposable — on which .dispose() can be called to cancel the subscription.
Invoke callback when an existing style element is updated.
| Argument | Type | Description |
|---|---|---|
callback | Function | that is called with style elements. |
styleElement | HTMLStyleElement | An HTMLStyleElement instance. The .sheet property will be null because this element isn’t attached to the DOM. The style element will also have the following non-standard properties: |
sourcePath | String | A String containing the path from which the style element was loaded. |
context | String | A String indicating the target context of the style element. |
Returns
Disposable — on which .dispose() can be called to cancel the subscription.
Reading Style Elements1
Get all loaded style elements.
Returns
Array<HTMLStyleElement>
Paths1
Get the path of the user style sheet in ~/.lumine.
Returns
String
Extended API
Tasksrc/task.js:46
Run a node script in a separate process.
Full description
Used by fuzzy file search and find-and-replace in project.
For a real-world example, see the replace-handler.
Examples#
In your package code:
const {Task} = require('lumine');
let task = Task.once('/path/to/task-file.js', parameter1, parameter2, function() {
console.log('task has finished');
});
task.on('some-event-from-the-task', (data) => {
console.log(data.someString); // prints 'yep this is it'
});
In '/path/to/task-file.js':
module.exports = function(parameter1, parameter2) {
// Indicates that this task will be async.
// Call the `callback` to finish the task
const callback = this.async();
emit('some-event-from-the-task', {
someString: 'yep this is it'
});
return callback();
};
Construction2
Create and start a task that terminates after its completion event.
| Argument | Type | Description |
|---|---|---|
taskPath | String | The JavaScript module path exporting the task function. |
...args | ...* | Arguments passed to the task function; an optional final Function receives the completion result. |
Returns
Task — The started task.
Create a task process without starting its exported function. Use .once to create and run it in one call.
| Argument | Type | Description |
|---|---|---|
taskPath | String | The JavaScript module path exporting the task function. |
Task Execution3
Starts the task.
Throws an error if this task has already been terminated or if sending a message to the child process fails.
| Argument | Type | Description |
|---|---|---|
...args | ...* | Arguments passed to the function exported by the task script. |
callbackoptional | Function | Called when the task completes. |
Forcefully stop the running task.
Child-process events stop after termination. Calling #cancel can still emit the local task:cancelled event.
Returns
Boolean — indicating whether the task was terminated.
Cancel the running task and emit an event if it was canceled.
Returns
Boolean — indicating whether the task was terminated.
Messaging1
Send message to the task.
Throws an error if this task has already been terminated or if sending a message to the child process fails.
| Argument | Type | Description |
|---|---|---|
message | * | A value serializable by the child-process IPC channel. |
Event Subscription1
Subscribe to an event emitted by the task process.
| Argument | Type | Description |
|---|---|---|
eventName | String | The String name of the event to handle. |
callback | Function | The Function to call when the event is emitted. |
Returns
Disposable — that can be used to stop listening for the event.
Extended API
TextBuffersrc/text-buffer.js:198
A mutable text container with undo/redo support and the ability to annotate logical regions in the text.
Full description
Observing Changes#
You can observe changes in a TextBuffer using methods like #onDidChange,
#onDidStopChanging, and #getChangesSinceCheckpoint. These methods report
aggregated buffer updates as arrays of change objects containing the following
fields: oldRange, newRange, oldText, and newText. The oldText,
newText, and newRange fields are self-explanatory, but the interpretation
of oldRange is more nuanced:
The reported oldRange is the range of the replaced text in the original
contents of the buffer irrespective of the spatial impact of any other
reported change. So, for example, if you wanted to apply all the changes made
in a transaction to a clone of the observed buffer, the easiest approach would
be to apply the changes in reverse:
buffer1.onDidChange(({changes}) => {
for (const {oldRange, newText} of changes.reverse()) {
buffer2.setTextInRange(oldRange, newText)
}
})
If you needed to apply the changes in the forwards order, you would need to incorporate the impact of preceding changes into the range passed to #setTextInRange, as follows:
buffer1.onDidChange(({changes}) => {
for (const {oldRange, newRange, newText} of changes) {
const rangeToReplace = Range(
newRange.start,
newRange.start.traverse(oldRange.getExtent())
)
buffer2.setTextInRange(rangeToReplace, newText)
}
})
Construction5
Create a new buffer with the given params.
function Object() { [native code] }
| Argument | Type | Description |
|---|---|---|
paramsoptional | Object|String | or String of text |
textoptional | String | The initial String text of the buffer. |
filePathoptional | String | The initial backing path; the constructor does not load its contents. |
encodingoptional, default: utf8 | String | The initial character encoding. |
preferredLineEndingoptional, default: null | String|null | Preferred line ending for inserted text, or null to derive it from the buffer. |
maxUndoEntriesoptional | Number | Maximum undo history size; defaults to the buffer limit. |
Create a new buffer backed by the given file path.
| Argument | Type | Description |
|---|---|---|
source | String|Object | Either a String path to a local file or (experimentally) a file Object as described by the #setFile method. |
paramsoptional | Object | An Object with the following properties: |
encodingoptional | String | The file’s encoding. |
mustExistoptional, default: false | Boolean | Reject a missing path instead of creating an empty buffer. |
Returns
Promise<TextBuffer> — Resolves to the buffer when the operation completes.
Create a new buffer backed by the given file path. For better performance, use TextBuffer.load instead.
| Argument | Type | Description |
|---|---|---|
filePath | String | The String file path. |
paramsoptional | Object | An Object with the following properties: |
encodingoptional | String | The file’s encoding. |
mustExistoptional, default: false | Boolean | Reject a missing path instead of creating an empty buffer. |
Returns
TextBuffer — instance.
Create an immutable text snapshot from a string, an existing snapshot or the segmented LumineText value returned by portable session capture. Existing immutable roots are reused; segmented input is validated and joined without materializing a document string or creating a live buffer.
| Argument | Type | Description |
|---|---|---|
valueoptional, default: "" | String|Object | Text or serialized snapshot; defaults to empty text. |
Returns
Object — An immutable snapshot supporting chunks, subtext and source-coordinate reads.
Restore a TextBuffer based on an earlier state created using
the TextBuffer.serialize method.
| Argument | Type | Description |
|---|---|---|
params | Object | An Object returned from TextBuffer.serialize |
Returns
Promise<TextBuffer|undefined> — Resolves to the restored buffer, or undefined when the serialized version is incompatible.
Serialization1
Capture this buffer’s state for restoration with TextBuffer.deserialize.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | Serialization options. |
markerLayersoptional, default: true | Boolean | Include persistent marker layers. |
historyoptional, default: true | Boolean | Include undo and redo history. |
textSnapshotsoptional, default: false | Boolean | Keep immutable text roots for the session store. Other callers receive segmented text for large payloads; stream their JSON instead of constructing one document-sized string. |
Returns
Object — State accepted by TextBuffer.deserialize.
Event Subscription17
Invoke the given callback synchronously before the content of the buffer changes.
Because observers are invoked synchronously, it’s important not to perform any expensive operations via this method. Observers may read the document but must not edit it, undo, or redo. Reentrant edits belong in post-transaction notifications instead.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the buffer changes. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback synchronously when a transaction finishes with a list of all the changes in the transaction.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when a transaction in which textual changes occurred is completed. |
event | Object | with the following keys: |
origin | String | edit for editor and API mutations, undo or redo for history replay, reload for text loaded from the backing file, or mixed when a transaction contains more than one origin. edit includes programmatic changes and does not prove that a key was pressed. |
oldRange | Range | The smallest combined Range containing all of the old text. |
newRange | Range | The smallest combined Range containing all of the new text. |
changes | Array<Object> | of Objects summarizing the aggregated changes that occurred during the transaction. See Working With Aggregated Changes in the description of the TextBuffer class for details. |
oldRange | Range | The Range of the deleted text in the contents of the buffer as it existed before the batch of changes reported by this event. |
newRange | Range | The Range of the inserted text in the current contents of the buffer. |
oldText | String | A String representing the deleted text. |
newText | String | A String representing the inserted text. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the callback synchronously at the end of a transaction with its individual edits in application order, before the consolidated change event. Each edit uses the coordinates of the buffer immediately before and after that edit. Edits that cancel each other still appear, allowing external range snapshots to follow every applied edit.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives an object containing a changes array of immutable edits with oldRange, newRange, oldText, newText, startIndex, oldEndIndex, and newEndIndex. Indices and columns count UTF-16 code units. beforeRevision and afterRevision identify the text states surrounding the batch; compare them with #getTextRevision. isCurrent() returns false after the buffer advances beyond this batch. origin identifies the batch as edit, undo, redo, reload, or mixed; each individual edit also carries its own origin. |
Returns
Disposable — Subscription to the applied edit batches.
Subscribe to aggregated buffer changes; an alias of #onDidChange.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called when tokenization completes. |
Returns
Disposable — Subscription to the same change events as #onDidChange.
Invoke the given callback asynchronously following one or more changes after #getStoppedChangingDelay milliseconds elapse without an additional change.
This method can be used to perform potentially expensive operations that don’t need to be performed synchronously. If you need to run your callback synchronously, use #onDidChange instead.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the buffer stops changing. |
event | Object | with the following keys: |
origin | String | edit, undo, redo, reload, or mixed, covering all transactions in this idle interval. mixed means that more than one origin occurred. |
transactions | Array | Immutable transaction snapshots in application order, each containing origin and changes. Their ranges use the coordinates of their own transaction. Use these for reactions to the latest edit rather than treating the combined diff as user input. |
changes | Array<Object> | An Array containing Objects summarizing the aggregated changes. See Working With Aggregated Changes in the description of the TextBuffer class for details. |
oldRange | Range | The Range of the deleted text in the contents of the buffer as it existed before the batch of changes reported by this event. |
newRange | Range | The Range of the inserted text in the current contents of the buffer. |
oldText | String | A String representing the deleted text. |
newText | String | A String representing the inserted text. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the value of #getFileState changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with the new state string from #getFileState. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when all marker ::onDidChange
observers have been notified following a change to the buffer.
The order of events following a buffer change is as follows:
- The text of the buffer is changed
- All markers are updated accordingly, but their
::onDidChangeobservers are not notified. TextBuffer::onDidChangeobservers are notified.Marker::onDidChangeobservers are notified.TextBuffer::onDidUpdateMarkersobservers are notified.
Basically, this method gives you a way to take action after both a buffer change and all associated marker changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called after markers are updated. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a marker is created.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when a marker is created. |
marker | Marker | that was created. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the value of #getPath changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the path changes. |
path | String|undefined | representing the buffer’s current path on disk. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the value of #getEncoding changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the encoding changes. |
encoding | String | character set encoding of the buffer. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback before the buffer is saved to disk.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called before the buffer is saved. If this function returns a Promise, then the buffer will not be saved until the promise resolves. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback after the buffer is saved to disk.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called after the buffer is saved. |
event | Object | with the following keys: |
path | String | The path to which the buffer was saved. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback before the buffer is reloaded from the contents of its file on disk.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called before the buffer is reloaded. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback after the buffer is reloaded from the contents of its file on disk.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called after the buffer is reloaded. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the buffer is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the buffer is destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when there is an error in watching the file.
| Argument | Type | Description |
|---|---|---|
callback | Function | callback |
errorObject | Object | |
error | Object | the error object |
handle | Function | call this to indicate you have handled the error. The error will not be thrown if this function is called. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Call the given callback whenever the buffer’s language mode changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | A Function to call when the language mode changes. |
languageMode | Object | The buffer’s new language mode Object. See TextBuffer#setLanguageMode for its interface. |
oldLanguageMode | Object | The buffer’s old language mode Object. See TextBuffer#setLanguageMode for its interface. |
Returns
Disposable — that can be used to stop the callback from being called.
Configuration1
Get the number of milliseconds that will elapse without a change before #onDidStopChanging observers are invoked following a change.
Returns
Number
File Details7
Get the buffer’s mutually exclusive persistence state.
"unmodified" matches the saved base, "modified" has local changes,
"conflicted" has diverged from its backing file, and "removed" has lost
its backing file.
Returns
String — "unmodified", "modified", "conflicted", or "removed".
Get the path of the associated file.
Returns
String|undefined — The backing path, or undefined when the buffer has no backing file.
Set the path for the buffer’s associated file.
| Argument | Type | Description |
|---|---|---|
filePath | String|null | A String representing the new file path |
Set a custom File object as the buffer’s backing store.
| Argument | Type | Description |
|---|---|---|
file | Object|null | An Object with the following properties: |
getPath | Function | A Function that returns the String path to the file. |
setPathoptional | Function | A Function that retargets this same data source, optionally returning a Promise. Supplying it opts into editor-initiated filesystem moves; without it, the provider owns relocation. |
createReadStream | Function | A Function that returns a Readable stream that can be used to load the file’s content. |
createWriteStream | Function | A Function that returns a Writable stream that can be used to save content to the file. |
existsSync | Function | A Function that returns a Boolean, true if the file exists, false otherwise. |
onDidChangeoptional | Function | A Function that invokes its callback argument when the file changes. The method should return a Disposable that can be used to prevent further calls to the callback. |
onDidDeleteoptional | Function | A Function that invokes its callback argument when the file is deleted. The method should return a Disposable that can be used to prevent further calls to the callback. |
onDidRenameoptional | Function | A Function that invokes its callback argument when the file is renamed. The method should return a Disposable that can be used to prevent further calls to the callback. |
Sets the character set encoding for this buffer.
| Argument | Type | Description |
|---|---|---|
encodingoptional, default: "utf8" | String | The String encoding to use (default: ‘utf8’). |
Get the character encoding used by this buffer.
Returns
String — encoding of this buffer.
Get the path of the associated file.
Returns
String|undefined — The backing path, or undefined when the buffer has no backing file.
Reading Text19
Determine whether the buffer is empty.
Returns
Boolean
Get the entire text of the buffer. Avoid using this unless you know that the buffer’s text is reasonably short.
Returns
String
Check a full-text allocation budget without reading or copying the text. The runtime’s maximum string length remains an upper bound even when the supplied budget is larger. Use snapshots and chunk readers for other work.
| Argument | Type | Description |
|---|---|---|
maxLengthoptional, default: Infinity | Number | Maximum UTF-16 units to materialize. |
Returns
Boolean — Whether this document fits both limits.
Capture immutable text without copying the document. The snapshot remains
valid after edits, undo and buffer destruction. Its read interface exposes
length, lineCount, slice(start, end), charCodeAt(index), chunks(),
lines(startRow, endRow), lineReader(), positionAt(index) and offsetAt(point).
subtext(start, end) captures a shared subrange; replace(start, end, text)
returns a new snapshot, accepting a string or another snapshot. Neither
operation mutates the captured text or materializes the whole document.
mapChunks(mapper, {cache, signal, isCurrent}) asynchronously transforms
bounded chunks with cooperative yields. A cache is a WeakMap owned by one
pure context-free mapper; unchanged branches are reused across revisions.
The mapper receives a string and synchronously returns a string or snapshot.
It must preserve its own semantics across arbitrary chunk boundaries.
commonPrefixLength(other, limit) and commonSuffixLength(other, limit)
compare UTF-16 units exactly while skipping shared immutable branches.
The default limit is the shorter snapshot’s length.
A line reader returns a row-to-text function with efficient sequential reads
and indexed jumps; requests outside the snapshot return undefined.
Offsets count UTF-16 units; line iteration strips LF/CRLF and uses an
exclusive end row. Explicit string reads materialize only their range.
Read #getTextRevision alongside the snapshot when preparing an
asynchronous edit plan, then pass that revision when applying the plan.
Returns
Object — An immutable text snapshot with indexed and sequential readers.
Capture a clipped buffer range as immutable shared text without creating a string. Snapshot offsets and row positions are relative to the range start. Pass the snapshot to #setTextInRange, #insert or #append to copy text of any size with normal change events and undo history.
| Argument | Type | Description |
|---|---|---|
range | Range|Array|Object | The buffer range to capture. |
Returns
Object — An immutable text snapshot with the interface of #getTextSnapshot.
Run a read-only analysis in this buffer’s syntax owner. The request survives closing one editor split and is cancelled by text, grammar or buffer disposal.
| Argument | Type | Description |
|---|---|---|
modulePath | String | Absolute path to the analysis module. |
method | String | Named export to execute with a syntax context. |
params | * | Serializable analysis parameters. |
optionsoptional | Object | Optional signal and streamed-data consumer. |
Returns
Promise<*> — Data, or null when analysis is unavailable, disabled by None, or the captured revision is invalidated.
Identify the current settled syntax without exposing parser objects. Compare tokens by identity; null means syntax is pending or unavailable.
Returns
Object|null — An opaque immutable token for revision-bound caches.
Get the revision of the current text state. Revisions increase before change observers read the new text, including undo, redo and file loads. A revision identifies a state of this buffer, not an undo entry or byte offset.
Returns
Number — Monotonically increasing text revision for this buffer.
Get the text of all lines in the buffer, without their line endings.
Returns
Array<String> — The buffer lines, excluding line endings.
Get the text of the last line of the buffer, without its line ending.
Returns
String
Get the text of the line at the given 0-indexed row, without its line ending.
| Argument | Type | Description |
|---|---|---|
row | Number | A Number representing the row. |
Returns
String
Get the line ending for the given 0-indexed row.
| Argument | Type | Description |
|---|---|---|
row | Number | A Number indicating the row. |
Returns
String — The returned newline is represented as a literal string: '\n', '\r\n', or '' for the last line of the buffer, which doesn’t end in a newline.
Reads persistent tree metadata in constant time. A lone CR is ordinary text.
Returns
Set<string> — LF and/or CRLF endings currently present in the buffer.
Get the length of the line for the given 0-indexed row, without its line ending.
| Argument | Type | Description |
|---|---|---|
row | Number | A Number indicating the row. |
Returns
Number
Determine if the given row contains only whitespace.
| Argument | Type | Description |
|---|---|---|
row | Number | A Number representing a 0-indexed row. |
Returns
Boolean
Given a row, find the first preceding row that’s not blank.
| Argument | Type | Description |
|---|---|---|
startRow | Number | A Number identifying the row to start checking at. |
Returns
Number|null — The preceding non-blank row, or null when none exists.
Given a row, find the next row that’s not blank.
| Argument | Type | Description |
|---|---|---|
startRow | Number | A Number identifying the row to start checking at. |
Returns
Number|null — The next non-blank row, or null when none exists.
Determine whether the buffer contains Unicode surrogate pairs.
Returns
Boolean — Whether the buffer contains astral-plane Unicode characters encoded as surrogate pairs.
Mutating Text11
Replace the entire contents of the buffer with the given text.
| Argument | Type | Description |
|---|---|---|
text | String | A String |
Returns
Range — spanning the new buffer contents.
Compute diff changes to target text without modifying this buffer, its history, markers or observers. Ranges use UTF-16 buffer coordinates.
| Argument | Type | Description |
|---|---|---|
text | String|PieceTree | Target text or immutable snapshot. |
Returns
Array<Object> — Changes containing oldRange, newRange, source snapshots and lazy oldText/newText string getters.
Replace the current buffer contents by applying a diff based on the given text.
| Argument | Type | Description |
|---|---|---|
text | String|PieceTree | The new buffer contents as a string or immutable snapshot. |
Set the text in the given range.
| Argument | Type | Description |
|---|---|---|
range | Range|Array|Object | A Range |
newText | String|Object | A string or immutable snapshot from #getTextSnapshot or #getTextSnapshotInRange. |
optionsoptional | Object | |
normalizeLineEndingsoptional | Boolean | (default: true) |
undooptional | String | Deprecated String ‘skip’ will cause this change to be grouped with the preceding change for the purposes of undo and redo. This property is deprecated. Call groupLastChanges() on the buffer after instead. |
Returns
Range — of the inserted text.
Apply disjoint edits against the current revision as one undo operation. Ranges may span multiple rows but cannot overlap or share a start. Text is stored literally unless line-ending normalization is requested. Input order does not matter. All edits are validated before changing text; stale revisions and overlapping ranges reject.
Dense batches share unchanged text and update display geometry once. Widely spaced edits in large documents retain local display updates. Custom range trackers retain intermediate-text callbacks.
| Argument | Type | Description |
|---|---|---|
edits | Array<Object> | Objects with a buffer range and replacement text (string or immutable text snapshot). |
optionsoptional, default: {} | Object | Batch options. |
expectedRevisionoptional | Number | Required current revision for an asynchronous plan. |
normalizeLineEndingsoptional, default: false | Boolean | Normalize replacements using each original start row’s line ending. |
Returns
Boolean — Whether the batch changed text.
Prepare an ordered stream of disjoint edits with shared text and compressed coordinate runs, then publish one atomic undo operation. Ranges address the captured revision and must be ordered, in bounds, with distinct starts. Marker positions and invalidation follow forward individual edit semantics. Text and markers remain unchanged on cancellation or stale preparation. Custom range trackers receive each intermediate edit inside the transaction.
| Argument | Type | Description |
|---|---|---|
edits | Iterable|AsyncIterable | Entries with range and text (string or immutable snapshot), optionally grouped into arrays of at most 1024 entries to amortize asynchronous delivery. |
optionsoptional, default: {} | Object | |
expectedRevisionoptional | Number | Required source revision. |
signaloptional | AbortSignal | Cancels preparation before publication. |
normalizeLineEndingsoptional, default: false | Boolean | Normalize inserted line endings. |
isCurrentoptional | Function | Optional synchronous owner-validity predicate checked through publication. |
didCommitoptional | Function | Optional synchronous selection finalizer inside the transaction. A throwing finalizer aborts the transaction; failures from later observers report committed: true. |
withCommitoptional | Function | Optional synchronous presentation wrapper that must invoke its commit callback exactly once. |
Returns
Promise<Number> — Number of committed edits; a committed observer failure has committed: true.
Insert text at the given position.
| Argument | Type | Description |
|---|---|---|
position | Point|Array<Number>|Object | A Point representing the insertion location. The position is clipped before insertion. |
text | String|Object | A string or immutable text snapshot to insert. |
optionsoptional | Object | |
normalizeLineEndingsoptional | Boolean | (default: true) |
undooptional | String | Deprecated The value skip groups this edit with the preceding change. Call #groupLastChanges afterward instead. |
Returns
Range — of the inserted text.
Append text to the end of the buffer.
| Argument | Type | Description |
|---|---|---|
text | String|Object | A string or immutable text snapshot to append. |
optionsoptional | Object | |
normalizeLineEndingsoptional | Boolean | (default: true) |
undooptional | String | Deprecated The value skip groups this edit with the preceding change. Call #groupLastChanges afterward instead. |
Returns
Range — of the inserted text
Delete the line associated with a specified 0-indexed row.
| Argument | Type | Description |
|---|---|---|
row | Number | A Number representing the row to delete. |
Returns
Range — of the deleted text.
Delete the lines associated with the specified 0-indexed row range.
If the row range is out of bounds, it will be clipped. If the startRow is
greater than the endRow, they will be reordered.
| Argument | Type | Description |
|---|---|---|
startRow | Number | A Number representing the first row to delete. |
endRow | Number | A Number representing the last row to delete, inclusive. |
Returns
Range — of the deleted text.
Markers9
Create a layer to contain a set of related markers.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | An Object containing the following keys: |
maintainHistoryoptional | Boolean | A Boolean indicating whether or not the state of this layer should be restored on undo/redo operations. Defaults to false. |
persistentoptional | Boolean | A Boolean indicating whether or not this marker layer should be serialized and deserialized along with the rest of the buffer. Defaults to false. If true, the marker layer’s id will be maintained across the serialization boundary, allowing you to retrieve it via #getMarkerLayer. |
roleoptional | String | A String indicating role of this marker layer |
trackRangesoptional | Function | A synchronous (ranges, change) callback overriding the ranges of markers touched by an edit. ranges is a sorted array of {id, range} entries in pre-edit buffer coordinates; each range is a Range. change contains oldRange, newRange and newText. Return an array of {id, range} entries in post-edit coordinates, using each supplied id at most once. Omitting an id or returning a null range invalidates that marker. Untouched markers follow the standard index update. The callback must not edit the buffer or markers; exceptions and invalid results are reported and invalidate the touched markers without cancelling the text edit. The callback is retained by layer copies but is not serialized; see MarkerLayer#setRangeTracker to replace or remove it. |
Returns
Get a MarkerLayer by id.
| Argument | Type | Description |
|---|---|---|
id | String | The id of the marker layer to retrieve. |
Returns
MarkerLayer|undefined — The layer, or undefined when the id is unknown.
Get the default MarkerLayer.
All Marker APIs not tied to an explicit layer interact with this default
layer.
Returns
Create a Marker with the given range in the default MarkerLayer.
This marker will maintain its logical location as the buffer is changed,
so if you mark a particular word, the marker will remain over that word
even if the word’s location in the buffer changes.
| Argument | Type | Description |
|---|---|---|
range | Range|Array|Object | A Range or range-compatible Array |
propertiesoptional | Object | A hash of key-value pairs to associate with the marker. There are also reserved property names that have marker-specific meaning. |
reversedoptional | Boolean | Creates the marker in a reversed orientation. (default: false) |
invalidateoptional | String | Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility:
|
exclusiveoptional | Boolean | indicating whether insertions at the start or end of the marked range should be interpreted as happening outside the marker. Defaults to false, except when using the inside invalidation strategy or when the marker has no tail, in which case it defaults to true. Explicitly assigning this option overrides the default. |
Returns
Create a Marker at the given position with no tail in the default
marker layer.
| Argument | Type | Description |
|---|---|---|
position | Point | or point-compatible Array |
optionsoptional | Object | An Object with the following keys: |
invalidateoptional | String | Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility:
|
exclusiveoptional | Boolean | indicating whether insertions at the start or end of the marked range should be interpreted as happening outside the marker. Defaults to false, except when using the inside invalidation strategy or when the marker has no tail, in which case it defaults to true. Explicitly assigning this option overrides the default. |
Returns
Get all existing markers on the default marker layer.
Returns
Array<Marker> — The matching markers.
Get an existing marker by its id from the default marker layer.
| Argument | Type | Description |
|---|---|---|
id | Number | id of the marker to retrieve |
Returns
Marker|undefined — The marker on the default layer, or undefined when the id is unknown.
Find markers conforming to the given parameters in the default marker layer.
Markers are sorted based on their position in the buffer. If two markers start at the same position, the larger marker comes first.
| Argument | Type | Description |
|---|---|---|
paramsoptional | Object | A hash of key-value pairs constraining the set of returned markers. You can query against custom marker properties by listing the desired key-value pairs here. In addition, the following keys are reserved and have special semantics: |
startPositionoptional | Point | Only include markers that start at the given Point. |
endPositionoptional | Point | Only include markers that end at the given Point. |
startsInRangeoptional | Range | Only include markers that start inside the given Range. |
endsInRangeoptional | Range | Only include markers that end inside the given Range. |
containsPointoptional | Point | Only include markers that contain the given Point, inclusive. |
containsRangeoptional | Range | Only include markers that contain the given Range, inclusive. |
startRowoptional | Number | Only include markers that start at the given row Number. |
endRowoptional | Number | Only include markers that end at the given row Number. |
intersectsRowoptional | Number | Only include markers that intersect the given row Number. |
Returns
Array<Marker> — The matching markers.
Get the number of markers in the default marker layer.
Returns
Number
History11
Undo the last operation. If a transaction is in progress, aborts it.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | |
selectionsMarkerLayeroptional | MarkerLayer | Restore snapshot of selections marker layer to given selectionsMarkerLayer. |
Returns
Boolean — of whether or not a change was made.
Redo the last operation
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | |
selectionsMarkerLayeroptional | MarkerLayer | Restore snapshot of selections marker layer to given selectionsMarkerLayer. |
Returns
Boolean — of whether or not a change was made.
Batch multiple operations as a single undo/redo step.
Any group of operations that are logically grouped from the perspective of undoing and redoing should be performed in a transaction. If you want to abort the transaction, call #abortTransaction to terminate the function’s execution and revert any changes performed up to the abortion.
Pass only a callback to use default options. A numeric first argument supplies a grouping interval.
The callback runs synchronously; returned promises are not awaited before committing.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object|Number|Function | |
fnoptional | Function | A Function to call inside the transaction. |
groupingIntervaloptional | Number | Milliseconds for which this transaction remains open for grouping. A subsequent transaction committed in that interval is merged with it for undo and redo. |
selectionsMarkerLayeroptional | MarkerLayer | Skip snapshots for other selection marker layers. |
Returns
* — The callback result, or undefined when the transaction is aborted.
Abort the currently running transaction
Only intended to be called within the fn option to #transact
Clear the undo stack.
Clear the redo stack without changing text or the undo stack.
Create a pointer to the current state of the buffer for use with #revertToCheckpoint and #groupChangesSinceCheckpoint.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | |
selectionsMarkerLayeroptional | MarkerLayer | When provided, skip taking snapshot for other selections markerLayers except given one. |
Returns
Number — checkpoint id value.
Revert the buffer to the state it was in when the given checkpoint was created.
The redo stack will be empty following this operation, so changes since the checkpoint will be lost. If the given checkpoint is no longer present in the undo history, no changes will be made to the buffer and this method returns false.
| Argument | Type | Description |
|---|---|---|
checkpoint | Number | id of the checkpoint to revert to. |
optionsoptional | Object | |
selectionsMarkerLayeroptional | MarkerLayer | Restore snapshot of selections marker layer to given selectionsMarkerLayer. |
Returns
Boolean — Whether the operation succeeded.
Group all changes since the given checkpoint into a single transaction for purposes of undo/redo.
If the given checkpoint is no longer present in the undo history, no
grouping will be performed and this method will return false.
| Argument | Type | Description |
|---|---|---|
checkpoint | Number | id of the checkpoint to group changes since. |
optionsoptional | Object | |
selectionsMarkerLayeroptional | MarkerLayer | When provided, skip taking snapshot for other selections markerLayers except given one. |
Returns
Boolean — indicating whether the operation succeeded.
Group the last two text changes for purposes of undo/redo.
This operation will only succeed if there are two changes on the undo stack. It will not group past the beginning of an open transaction.
Returns
Boolean — indicating whether the operation succeeded.
Get the aggregated text changes since a checkpoint.
If the given checkpoint is no longer present in the undo history, this
method will return an empty Array.
| Argument | Type | Description |
|---|---|---|
checkpoint | Number | id of the checkpoint to get changes since. |
Returns
Array<Object> — Changes since the checkpoint. See Working With Aggregated Changes in the TextBuffer class description for the fields.
Searching and Replacing20
Scan regular expression matches in the entire buffer, calling the given iterator function on each match.
If you’re programmatically modifying the results, you may want to try #backwardsScan to avoid tripping over your own changes.
When options is omitted, pass the callback in its place.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
optionsoptional, default: {} | Object|Function | |
iteratoroptional | Function | A Function that’s called on each match with an Object containing the following keys: |
leadingContextLineCountoptional | Number | default 0; The number of lines before the matched line to include in the results object. |
trailingContextLineCountoptional | Number | default 0; The number of lines after the matched line to include in the results object. |
result | Object | Match information supplied as the callback’s only argument. |
match | Array | The current regular expression match. |
matchText | String | A String with the text of the match. |
range | Range | The Range of the match. |
stop | Function | Call this Function to terminate the scan. |
replace | Function | Call this Function with a String to replace the match. |
leadingContextLines | Array<String> | An Array with leadingContextLineCount lines before the match. |
trailingContextLines | Array<String> | An Array with trailingContextLineCount lines after the match. |
Scan regular expression matches in the entire buffer in reverse order, calling the given iterator function on each match.
When options is omitted, pass the callback in its place.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
optionsoptional, default: {} | Object|Function | |
iteratoroptional | Function | A Function that’s called on each match with an Object containing the following keys: |
leadingContextLineCountoptional | Number | default 0; The number of lines before the matched line to include in the results object. |
trailingContextLineCountoptional | Number | default 0; The number of lines after the matched line to include in the results object. |
result | Object | Match information supplied as the callback’s only argument. |
match | Array | The current regular expression match. |
matchText | String | A String with the text of the match. |
range | Range | The Range of the match. |
stop | Function | Call this Function to terminate the scan. |
replace | Function | Call this Function with a String to replace the match. |
leadingContextLines | Array<String> | An Array with leadingContextLineCount lines before the match. |
trailingContextLines | Array<String> | An Array with trailingContextLineCount lines after the match. |
Scan regular expression matches in a given range , calling the given iterator function on each match.
When options is omitted, pass the callback in its place.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
range | Range|Array|Object | A Range in which to search. |
optionsoptional, default: {} | Object|Function | |
callbackoptional | Function | A Function that’s called on each match with an Object containing the following keys: |
reverseoptional, default: false | Boolean | Visit matches in reverse order. Defaults to false. |
leadingContextLineCountoptional | Number | default 0; The number of lines before the matched line to include in the results object. |
trailingContextLineCountoptional | Number | default 0; The number of lines after the matched line to include in the results object. |
result | Object | Match information supplied as the callback’s only argument. |
match | Array | The original native regular expression match, including captures and groups. Its index, indices and input refer to a bounded search window. |
inputOffset | Number | UTF-16 offset of that search window in the captured buffer snapshot; add it to match.index for the original match offset. |
matchText | String | A String with the text of the match. |
range | Range | The Range of the match. |
stop | Function | Call this Function to terminate the scan. |
replace | Function | Call this Function with a String to replace the match. |
leadingContextLines | Array<String> | An Array with leadingContextLineCount lines before the match. |
trailingContextLines | Array<String> | An Array with trailingContextLineCount lines after the match. |
Scan regular expression matches in a given range in reverse order, calling the given iterator function on each match.
When options is omitted, pass the callback in its place.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
range | Range|Array|Object | A Range in which to search. |
optionsoptional, default: {} | Object|Function | |
iteratoroptional | Function | A Function that’s called on each match with an Object containing the following keys: |
leadingContextLineCountoptional | Number | default 0; The number of lines before the matched line to include in the results object. |
trailingContextLineCountoptional | Number | default 0; The number of lines after the matched line to include in the results object. |
result | Object | Match information supplied as the callback’s only argument. |
match | Array | The original native regular expression match, including captures and groups. Its index, indices and input refer to a bounded search window. |
inputOffset | Number | UTF-16 offset of that search window in the captured buffer snapshot; add it to match.index for the original match offset. |
matchText | String | A String with the text of the match. |
range | Range | The Range of the match. |
stop | Function | Call this Function to terminate the scan. |
replace | Function | Call this Function with a String to replace the match. |
Replace all regular expression matches in the entire buffer. This synchronous compatibility API is limited to 8 Mi UTF-16 units so native RegExp execution and replacement expansion stay bounded. Use #replaceAllMatches for cooperative snapshot-backed bulk replacement.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp representing the matches to be replaced. |
replacementText | String | A String representing the text to replace each match. |
Returns
Number — representing the number of replacements made.
Search an immutable revision without flattening the document. The returned session provides cancellable iteration, exact counting, sparse navigation checkpoints and a separately bounded list of presentation ranges.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | Expression to search for. |
optionsoptional, default: {} | Object | Optional range and AbortSignal. |
Returns
Object — Revision-bound search session.
Prepare all replacements against one snapshot, then commit atomically as one undo operation. Cancellation or concurrent edits discard the plan.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | Expression to replace. |
replacement | String | ECMAScript replacement template. |
optionsoptional, default: {} | Object | Ranges, signal, literalReplacement and transformReplacement. |
didCommitoptional | Function | Synchronous finalizer run after all text changes and before public change observers. |
Returns
Promise<Number> — Number of replaced matches.
Prepare replacements without publishing text or markers. The one-use plan exposes count, snapshot, validate(), commit() and dispose().
| Argument | Type | Description |
|---|---|---|
regex | RegExp | Expression to replace. |
replacement | String | Replacement template. |
optionsoptional, default: {} | Object | Replacement options and cancellation signal. |
Returns
Promise<Object> — Revision-bound replacement plan.
Publish prepared replacements across buffers before delivering any change observers.
| Argument | Type | Description |
|---|---|---|
plans | Array<Object> | One prepared replacement plan per buffer. |
optionsoptional, default: {} | Object | Optional signal, isCurrent predicate, and synchronous didCommit model-publication callback. |
Returns
Number — Replaced occurrences; observer failures are marked committed.
Asynchronously search the buffer for a given regex.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
Returns
Promise<Object|null> — Resolves to the first range-compatible object with start/end points, or null when no match exists. Use Range.fromObject when a Range instance is needed.
Asynchronously search a given range of the buffer for a given regex.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
range | Range|Array|Object | A Range to search within. |
Returns
Promise<Object|null> — Resolves to the first range-compatible object with start/end points, or null when no match exists. Use Range.fromObject when a Range instance is needed.
Search the buffer for a given regex.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
Returns
Object|null — The first range-compatible object with start/end points, or null when no match exists. Use Range.fromObject when a Range instance is needed.
Search a given range of the buffer for a given regex.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
range | Range|Array|Object | A Range to search within. |
Returns
Object|null — The first range-compatible object with start/end points, or null when no match exists. Use Range.fromObject when a Range instance is needed.
Asynchronously search the buffer for a given regex.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
Returns
Promise<Array<Object>> — Resolves to range-compatible objects with start/end points. Convert an entry with Range.fromObject when a Range instance is needed.
Asynchronously search a given range of the buffer for a given regex.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
range | Range|Array|Object | A Range to search within. |
Returns
Promise<Array<Object>> — Resolves to range-compatible objects with start/end points. Convert an entry with Range.fromObject when a Range instance is needed.
Run an regexp search on the buffer
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
Returns
Array<Object> — Range-compatible objects with start/end points. Convert an entry with Range.fromObject when a Range instance is needed.
Search a given range of the buffer for a given regex.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
range | Range|Array|Object | A Range to search within. |
Returns
Array<Object> — Range-compatible objects with start/end points. Convert an entry with Range.fromObject when a Range instance is needed.
Search a given range of the buffer for a given regex. Store the matching ranges in the given marker layer.
| Argument | Type | Description |
|---|---|---|
markerLayer | MarkerLayer | A MarkerLayer to populate. |
regex | RegExp | A RegExp to search for. |
range | Range|Array|Object | A Range to search within. |
optionsoptional, default: {} | Object | Options for this operation. |
exclusiveoptional | Boolean | Treat edits at the marker endpoints as outside the marker. |
invalidateoptional, default: overlap | String | Marker invalidation strategy; see #markRange. |
tailedoptional, default: true | Boolean | Whether each match marker retains a tail. |
Returns
Array<Marker> — The matching markers.
Find fuzzy match suggestions in the buffer
| Argument | Type | Description |
|---|---|---|
query | String | A String to search for. |
extraWordCharacters | String | A String of additional word characters to use when deciphering word boundaries |
maxCount | Number | A Number that limits the number of matches returned |
Returns
Promise<Array<Object>|null> — Resolves to subsequence matches containing plain row/column positions, or null when the search provides no result.
Find fuzzy match suggestions in the buffer in a given range
| Argument | Type | Description |
|---|---|---|
query | String | A String to search for. |
extraWordCharacters | String | A String of additional word characters to use when deciphering word boundaries |
maxCount | Number | A Number that limits the number of matches returned |
range | Range|Array|Object | A Range that specifies the portion of the buffer to search |
Returns
Promise<Array<Object>|null> — Resolves to subsequence matches containing plain row/column positions, or null when the search provides no result.
Searching1
Find completion words in an immutable snapshot without allocating every occurrence. Coordinates are absolute UTF-16 buffer points. Each result contains word, score, matchIndices, the first position, occurrences, minimum row distance and containsPosition (inclusive of the word’s end). Words and queries are limited to 80 UTF-16 units. Word characters cannot include line endings; use the legacy subsequence API for multiline tokens.
| Argument | Type | Description |
|---|---|---|
query | String | Typed subsequence. |
optionsoptional, default: {} | Object | Search options. |
rangeoptional | Range | Clipped search range; defaults to the buffer. |
positionoptional | Point | Cursor for distance and containment. |
extraWordCharactersoptional | String | Additional word characters. |
maxCountoptional, default: 20 | Number | Maximum distinct words returned. |
signaloptional | AbortSignal | Cancel obsolete work; resolves to an empty list. |
Returns
Promise<Array<Object>> — Ranked candidates. Distance is Infinity without a position.
Buffer Range Details12
Get the range spanning from [0, 0] to #getEndPosition.
Returns
Get the number of lines in the buffer.
Returns
Number
Get the last 0-indexed row in the buffer.
Returns
Number
Get the first position in the buffer, which is always [0, 0].
Returns
Get the maximal position in the buffer, where new text would be appended.
Returns
Get the length of the buffer’s text.
Returns
Number — The number of UTF-16 code units, including line endings.
Get the length of the buffer in characters.
Returns
Number
Get the range for the given row
| Argument | Type | Description |
|---|---|---|
row | Number | A Number representing a 0-indexed row. |
includeNewlineoptional | Boolean | A Boolean indicating whether or not to include the newline, which results in a range that extends to the start of the next line. (default: false) |
Returns
Convert an absolute character offset, inclusive of newlines, to a position in the buffer in row/column coordinates.
The offset is clipped prior to translating.
| Argument | Type | Description |
|---|---|---|
offset | Number | A Number. |
Returns
Clip the given range so it starts and ends at valid positions.
For example, the position [1, 100] is out of bounds if the line at row 1 is
only 10 characters long, and it would be clipped to (1, 10).
Returns
Range — given Range if it is already in bounds, or a new clipped Range if the given range is out-of-bounds.
Clip the given point so it is at a valid position in the buffer.
For example, the position (1, 100) is out of bounds if the line at row 1 is only 10 characters long, and it would be clipped to (1, 10)
| Argument | Type | Description |
|---|---|---|
position | Point|Array<Number>|Object | A Point or point-compatible Array. |
optionsoptional | Object | Options for this operation. |
clipDirectionoptional | String | The value forward moves a position at or beyond a non-final line ending to the start of the next row. |
Returns
Point — new Point if the given position is invalid, otherwise returns the given position.
Buffer Operations7
Save the buffer.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
windowoptional | EditorWindow | Window that owns a save-confirmation notification; defaults to the focused window. |
Returns
Promise<TextBuffer> — Resolves to the saved buffer, or rejects with SaveCancelledError when confirmation is cancelled.
Save the buffer at a specific path.
| Argument | Type | Description |
|---|---|---|
filePath | String | The path to save at. |
optionsoptional, default: {} | Object | |
windowoptional | EditorWindow | Window that owns a save-confirmation notification; defaults to the focused window. |
Returns
Promise<TextBuffer> — Resolves to the saved buffer, or rejects with SaveCancelledError when confirmation is cancelled. A successful save to another path clears the confirmation policy.
Require confirmation before saving to the current backing path. The serializable policy is shared by all editors of this buffer. The warning offers approval once, approval for this buffer’s session, or cancellation. Session approval is not serialized. Setting the same policy again preserves its pending warning and session approval.
| Argument | Type | Description |
|---|---|---|
confirmation | Object|null | Warning text, or null to clear it. |
message | String | The question shown before saving. |
detailoptional | String | Additional plain-text context. |
Return a copy of the current backing path’s save-confirmation policy.
Returns
Object|null — The message and optional detail, or null.
Determine whether the current path can be saved automatically without asking for confirmation. Ordinary buffers and paths approved for this buffer’s session return true; policies awaiting approval return false.
Returns
Boolean — Whether an automatic save may proceed.
Reload the file’s content from disk.
Returns
Promise<TextBuffer|undefined> — Resolves to this buffer after loading, or undefined when a newer operation supersedes the load.
Wait until this buffer’s file watcher is ready to report external changes.
Returns
Promise — that resolves once this buffer’s file watcher has been armed and is delivering external-change events. Watching is served asynchronously by the file-watcher worker; this lets callers wait for it before relying on external-change detection. Resolves immediately when the buffer has no path or a custom data source that watches synchronously.
Language Modes2
Get the language mode associated with this buffer.
Returns
Object — language mode Object (See TextBuffer#setLanguageMode for its interface).
Set the language mode for this buffer.
| Argument | Type | Description |
|---|---|---|
languageMode | Object | an Object with the following methods: |
getLanguageId | Function | A Function that returns a String identifying the language. |
bufferDidChange | Function | A Function that is called whenever the buffer changes. |
change | Object | An Object with the following fields: |
oldText | String | The deleted text |
oldRange | Range | The Range of the deleted text before the change took place. |
newText | String | The inserted text |
newRange | Range | The Range of the inserted text after the change took place. |
onDidChangeHighlighting | Function | A Function that takes a callback Function and calls it with a Range argument whenever the syntax of a given part of the buffer is updated. |
buildHighlightIterator | Function | A function that returns an iterator object with the following methods: |
seek | Function | A Function that takes a Point and resets the iterator to that position. |
moveToSuccessor | Function | A Function that advances the iterator to the next token |
getPosition | Function | A Function that returns a Point representing the iterator’s current position in the buffer. |
getCloseScopeIds | Function | A Function that returns an Array of Numbers representing scopes that end at the current position. |
getOpenScopeIds | Function | A Function that returns an Array of Numbers representing scopes that begin at the current position. |
bufferDidFinishTransaction | Function | Called after the text changes in a transaction have been aggregated. |
Lifecycle2
Destroy this buffer, dispose its file watcher and marker layers, and notify destruction observers.
Determine whether this buffer has been destroyed.
Returns
Boolean — Whether the buffer has been destroyed.
Essential API
TextEditorsrc/text-editor.js:154
This class represents all essential editing state for a single TextBuffer, including cursor and selection positions, folds, and soft wraps. If you’re manipulating the state of an editor, use this class.
Full description
A single TextBuffer can belong to multiple editors. For example, if the same file is open in two different panes, Lumine creates a separate editor for each pane. If the buffer is manipulated the changes are reflected in both editors, but each maintains its own cursor position, folded lines, etc.
Accessing TextEditor Instances#
The easiest way to get hold of TextEditor objects is by registering a callback
with ::observeTextEditors on the lumine.workspace global. Your callback will
then be called with all current editor instances and also when any editor is
created in the future.
lumine.workspace.observeTextEditors(editor => {
editor.insertText('Hello World')
})
Buffer vs. Screen Coordinates#
Because editors support folds and soft-wrapping, the lines on screen don’t always match the lines in the buffer. For example, a long line that soft wraps twice renders as three lines on screen, but only represents one line in the buffer. Similarly, if rows 5-10 are folded, then row 6 on screen corresponds to row 11 in the buffer.
Your choice of coordinates systems will depend on what you’re trying to achieve. For example, if you’re writing a command that jumps the cursor up or down by 10 lines, you’ll want to use screen coordinates because the user probably wants to skip lines on screen. However, if you’re writing a package that jumps between method definitions, you’ll want to work in buffer coordinates.
When in doubt, just default to buffer coordinates, then experiment with soft wraps and folds to ensure your code interacts with them correctly.
View State2
Capture the cursor, selection, and viewport state without references to this editor’s buffer or marker layers. The returned object can be passed through JSON and restored on another editor for the same text.
Returns
Object
Restore state produced by #serializeViewState. Invalid portions of the state are ignored.
| Argument | Type | Description |
|---|---|---|
state | Object | A portable editor view-state object. |
Lifecycle2
Destroy this editor, dispose its views and selections, and release its buffer.
Determine whether this editor has been destroyed.
Returns
Boolean — Whether the editor has been destroyed.
Event Subscription32
Calls your callback when the buffer’s title has changed.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when the buffer’s path, and therefore title, has changed.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the callback synchronously when the display changes, including text edits, folding, wrapping and prepared syntax highlighting. Subscribe to TextBuffer#onDidChangeText for changes to source text only.
Ranges reported for text changes carry the buffer’s origin: edit,
undo, redo, reload, or mixed. Color-only display updates use highlight.
A complete display reset reports an empty object instead of range changes.
For buffer-coordinate transactions, subscribe to
TextBuffer#onDidChange on #getBuffer instead.
Because observers are invoked synchronously, it’s important not to perform any expensive operations via this method. Consider #onDidStopChanging to delay expensive operations until after changes stop occurring.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke callback when the buffer’s contents change. It is
emit asynchronously 300ms after the last buffer change. This is a good place
to handle changes to the buffer without compromising typing performance.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when a Cursor is moved. If there are
multiple cursors, your callback will be called for each cursor.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
oldBufferPosition | Point | |
oldScreenPosition | Point | |
newBufferPosition | Point | |
newScreenPosition | Point | |
textChanged | Boolean | |
origin | String | edit, undo, redo, reload, or mixed; identifies history replay and buffer reloads independently of textChanged. |
cursor | Cursor | that triggered the event |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when a selection’s screen range changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | |
oldBufferRange | Range | |
oldScreenRange | Range | |
newBufferRange | Range | |
newScreenRange | Range | |
textChanged | Boolean | whether a buffer text change moved the selection. |
origin | String | edit, undo, redo, reload, or mixed; identifies history replay and buffer reloads independently of textChanged. |
selection | Selection | that triggered the event |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when soft wrap was enabled or disabled.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when the effective soft-wrap column changes, after
the display layer has adopted the new column. Unwrapped large documents
report Infinity.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
column | Number | The new wrapping column. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when overtype (overwrite) mode is enabled or
disabled for this editor.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
overtypeMode | Boolean | indicating the new state. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when the buffer’s encoding has changed.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when the grammar that interprets and
colorizes the text has been changed. Immediately calls your callback with
the current grammar.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
grammar | TreeSitterGrammar|Object | A Tree-sitter grammar or the null grammar sentinel. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when the grammar that interprets and
colorizes the text has been changed.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
grammar | TreeSitterGrammar|Object | A Tree-sitter grammar or the null grammar sentinel. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when the value of #getFileState changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with the new state string from #getFileState. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback before text has been inserted.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | event Object |
text | String | text to be inserted |
cancel | Function | Call to prevent the text from being inserted |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback after text has been inserted.
Called once per published insertion. Worker-backed automatic indentation is
prepared before publication, including Enter, typing and multiline paste.
Cancelled preparation emits no insertion.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
event | Object | event Object |
text | String | Inserted text; prepared source events materialize this lazily. |
textSourceoptional | Object | Immutable inserted source on prepared source events. |
range | Range | Range at notification time; later edits may move it. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Contribute synchronous edits to an insertion before its final indentation and publication. Edit only the supplied editor: worker-backed input uses a private candidate. This hook also runs inside ordinary insertion transactions.
| Argument | Type | Description |
|---|---|---|
callback | Function | Synchronous callback; promises are rejected. |
event | Object | The insertion being prepared. |
editor | TextEditor | Editor to modify during this callback. |
range | Range | Inserted range before callback edits. |
text | String | Inserted text; source-backed events materialize lazily. |
textSourceoptional | Object | Immutable inserted source; inspect its length before materializing. |
Returns
Disposable — Subscription to insertion preparation.
Invoke the given callback after the buffer is saved to disk.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called after the buffer is saved. |
event | Object | with the following keys: |
path | String | The path to which the buffer was saved. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the editor is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the editor is destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when a Cursor is added to the editor.
Immediately calls your callback for each existing cursor.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
cursor | Cursor | that was added |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when a Cursor is added to the editor.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
cursor | Cursor | that was added |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when a Cursor is removed from the editor.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
cursor | Cursor | that was removed |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when a Selection is added to the editor.
Immediately calls your callback for each existing selection.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
selection | Selection | that was added |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when a Selection is added to the editor.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
selection | Selection | that was added |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when a Selection is removed from the editor.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
selection | Selection | that was removed |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback with each Decoration added to the editor.
Calls your callback immediately for any existing decorations.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
decoration | Decoration |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when a Decoration is added to the editor.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
decoration | Decoration | that was added |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when a Decoration is removed from the editor.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
decoration | Decoration | that was removed |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when the placeholder text is changed.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
placeholderText | String|undefined | new text |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the callback when this editor starts or stops rejecting text edits.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives the current read-only Boolean. |
Returns
Disposable — Removes the subscription.
Calls your callback when a Gutter is added to the editor.
Immediately calls your callback for each existing gutter.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
gutter | Gutter | that currently exists/was added. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when a Gutter is added to the editor.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
gutter | Gutter | that was added. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Calls your callback when a Gutter is removed from the editor.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
name | String | The name of the Gutter that was removed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Editing Behavior2
Enable or disable read-only mode for this editor.
| Argument | Type | Description |
|---|---|---|
readOnly | Boolean | Whether text mutations require an explicit bypass. |
Determine whether this editor rejects text changes without an explicit bypass.
Returns
Boolean — Whether the editor is read-only.
Buffer1
Retrieves the current TextBuffer.
Returns
TextBuffer — The buffer shared by this editor.
File Details6
Get the editor’s title for display in other parts of the UI such as the tabs.
If the editor’s buffer is saved, its title is the file name. If it is unsaved, its title is “untitled”.
Returns
String
Get unique title for display in other parts of the UI, such as the window title.
If the editor’s buffer is unsaved, its title is “untitled” If the editor’s buffer is saved, its unique title is formatted as one of the following,
filenamewhen it is the only editing buffer with this file name.filename — unique-dir-prefixwhen other buffers have this file name.
Returns
String
Get the backing path of this editor’s text buffer.
Returns
String|undefined — The backing path, or undefined when the buffer has no backing file.
Get the character encoding used by this editor’s text buffer.
Returns
String — character set encoding of this editor’s text buffer.
Set the character set encoding to use in this editor’s text buffer.
| Argument | Type | Description |
|---|---|---|
encodingoptional | String | The String character set encoding name such as ‘utf8’ |
Get the editor’s mutually exclusive persistence state, as described by TextBuffer#getFileState.
Returns
String — "unmodified", "modified", "conflicted", or "removed".
Reading Text11
Determine whether this editor contains no text.
Returns
Boolean — true if this editor has no content.
Get the complete text of this editor.
Returns
String — representing the entire contents of the editor.
Get the number of buffer lines.
Returns
Number — representing the number of lines in the buffer.
Get the number of screen lines, accounting for folds and soft wrapping.
Returns
Number — representing the number of screen lines in the editor. This accounts for folds.
Get the zero-indexed last buffer row.
Returns
Number — representing the last zero-indexed buffer row number of the editor.
Get the zero-indexed last screen row.
Returns
Number — representing the last zero-indexed screen row number of the editor.
Get the text of a buffer row, excluding its line ending.
| Argument | Type | Description |
|---|---|---|
bufferRow | Number | A Number representing a zero-indexed buffer row. |
Returns
String — representing the contents of the line at the given buffer row.
Get the displayed text of a screen row.
| Argument | Type | Description |
|---|---|---|
screenRow | Number | A Number representing a zero-indexed screen row. |
Returns
String|undefined — The screen-line text, or undefined when the row is outside the rendered screen lines.
Request cached highlighting for a rendering surface’s complete screen-row window. Pass its stable owner to tokensForScreenRow while drawing. Empty windows release that owner’s request; completion emits highlighting changes.
| Argument | Type | Description |
|---|---|---|
owner | Object | The rendering surface that owns this window. |
startRow | Number | Inclusive screen row. |
endRow | Number | Exclusive screen row. |
Get the inclusive buffer-row bounds of the paragraph surrounding the most recently added cursor.
Returns
Array<Number>|undefined|Promise<Array<Number>|undefined> — Inclusive paragraph row bounds, or undefined on a blank row. Worker syntax resolves asynchronously.
File Operations5
Saves the editor’s text buffer.
See TextBuffer#save for more details.
Returns
Promise<TextBuffer> — Resolves to the saved text buffer, or rejects with SaveCancelledError when save confirmation is cancelled.
Saves the editor’s text buffer as the given path.
See TextBuffer#saveAs for more details.
| Argument | Type | Description |
|---|---|---|
filePath | String | A String path. |
Returns
Promise<TextBuffer> — Resolves to the saved text buffer, or rejects with SaveCancelledError when save confirmation is cancelled.
Require an explicit decision before saving to this editor’s current path. The policy belongs to the shared buffer, survives session restoration, and is cleared after a successful Save As to another path. Approval for the session is shared with split editors and resets after restoration. Setting an identical policy preserves its pending warning and decision.
| Argument | Type | Description |
|---|---|---|
confirmation | Object|null | The warning text, or null to clear it. |
message | String | The question shown before saving. |
detailoptional | String | Additional plain-text context. |
Return a copy of this editor’s shared save-confirmation policy.
Returns
Object|null — The message and optional detail, or null.
Determine whether this editor’s current path can be saved automatically. Editors without a policy and paths approved for the shared buffer’s session return true; policies awaiting approval return false.
Returns
Boolean — Whether an automatic save may proceed.
Mutating Text25
Replaces the entire contents of the buffer with the given String.
| Argument | Type | Description |
|---|---|---|
text | String | Text to replace the buffer contents with. |
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. |
Returns
Range|undefined — The range spanning the new contents, or undefined when a read-only editor refuses the edit.
Set the text in the given Range in buffer coordinates.
| Argument | Type | Description |
|---|---|---|
range | Range|Array|Object | A Range or range-compatible Array. |
text | String | A String |
optionsoptional, default: {} | Object | |
normalizeLineEndingsoptional | Boolean | (default: true) |
undooptional | String | Deprecated The value skip groups this edit with the preceding change. Call TextBuffer#groupLastChanges afterward instead. |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
Returns
Range|undefined — The inserted range, or undefined when a read-only editor refuses the edit.
For each selection, replace the selected text with the given text.
| Argument | Type | Description |
|---|---|---|
text | String | A String representing the text to insert. |
optionsoptional, default: {} | Object | See Selection#insertText. |
groupUndooptional, default: false | Boolean | Group this insertion with recent edits within the editor’s undo grouping interval. |
Returns
Array<Range>|Boolean|undefined|Promise — The inserted range for each selection, or a promise when automatic indentation requires syntax preparation. Await it before reading the result or issuing dependent edits. Returns false on cancellation, or undefined when a read-only editor refuses the edit.
For each selection, replace the selected text with a newline.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
For each selection, if the selection is empty, delete the character following the cursor. Otherwise delete the selected text.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
For each selection, if the selection is empty, delete the character preceding the cursor. Otherwise delete the selected text.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
Mutate the text of all the selections in a single transaction.
All the changes made inside the given Function can be reverted with a
single call to #undo.
| Argument | Type | Description |
|---|---|---|
fn | Function | |
groupingIntervaloptional, default: 0 | Number | Milliseconds during which this transaction can group with adjacent edits. Defaults to 0. |
Returns
Array<*>|undefined — The callback result for each selection, or undefined when the transaction is aborted.
For each selection, transpose the selected text.
If the selection is empty, the characters preceding and following the cursor are swapped. Otherwise, selected Unicode code points are reversed without splitting surrogate pairs.
Large selections are prepared from immutable chunks before publication. Changes to the document or selection cancel pending work.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
signaloptional | AbortSignal | Cancels asynchronous preparation. |
Returns
Boolean|undefined|Promise<Boolean> — True on completion, false on cancellation, or undefined when refused.
Convert the selected text to upper case.
For each selection, if the selection is empty, converts the containing word to upper case. Otherwise convert the selected text to upper case.
Large selections are prepared from immutable chunks before publication. Changes to the document or selection cancel pending work.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
signaloptional | AbortSignal | Cancels asynchronous preparation. |
Returns
Boolean|undefined|Promise<Boolean> — True on completion, false on cancellation, or undefined when refused.
Convert the selected text to lower case.
For each selection, if the selection is empty, converts the containing word to lower case. Otherwise convert the selected text to lower case.
Large selections are prepared from immutable chunks before publication. Changes to the document or selection cancel pending work.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
signaloptional | AbortSignal | Cancels asynchronous preparation. |
Returns
Boolean|undefined|Promise<Boolean> — True on completion, false on cancellation, or undefined when refused.
Toggle line comments for rows intersecting selections.
If the current grammar doesn’t support comments, does nothing.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
Reduce every run of blank lines in the buffer to a single blank line.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
Collapse runs of spaces in line content without changing indentation.
The complete leading whitespace prefix is preserved, including mixed tabs and spaces. Runs of spaces after that prefix are reduced to one space.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
For each cursor, insert a newline at beginning the following line.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
For each cursor, insert a newline at the end of the preceding line.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
For each selection, if the selection is empty, delete all characters of the containing word that precede the cursor. Otherwise delete the selected text.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
Similar to #deleteToBeginningOfWord, but deletes only back to the previous word boundary.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
Similar to #deleteToEndOfWord, but deletes only up to the next word boundary.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
For each selection, if the selection is empty, delete all characters of the containing subword following the cursor. Otherwise delete the selected text.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
For each selection, if the selection is empty, delete all characters of the containing subword following the cursor. Otherwise delete the selected text.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
For each selection, if the selection is empty, delete all characters of the containing line that precede the cursor. Otherwise delete the selected text.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
For each selection, if the selection is not empty, deletes the selection; otherwise, deletes all characters of the containing line following the cursor. If the cursor is already at the end of the line, deletes the following newline.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
Delete through the indentation of the line following each selection.
Empty selections start at their cursor. Non-empty selections also consume the rest of their final selected line. Selection direction does not affect the result.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
For each selection, if the selection is empty, delete all characters of the containing word following the cursor. Otherwise delete the selected text.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
Delete all lines intersecting selections.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
History8
Undo the last change.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
Redo the last change.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. (default: false) |
Batch multiple operations as a single undo/redo step.
Any group of operations that are logically grouped from the perspective of undoing and redoing should be performed in a transaction. If you want to abort the transaction, call #abortTransaction to terminate the function’s execution and revert any changes performed up to the abortion.
Pass only a callback to use the default grouping interval.
The callback runs synchronously; returned promises are not awaited before committing.
| Argument | Type | Description |
|---|---|---|
groupingIntervaloptional | Number|Function | The Number of milliseconds for which this transaction should be considered ‘groupable’ after it begins. If a transaction with a positive groupingInterval is committed while the previous transaction is still ‘groupable’, the two transactions are merged with respect to undo and redo. |
fnoptional | Function | A Function to call inside the transaction. |
Returns
* — The callback result, or undefined when the transaction is aborted.
Prepare an editing operation and its automatic indentation, then publish text and selections together as one undo step. With worker syntax, the callback receives a private editor sharing the document’s immutable text. Make all edits through that editor and keep the callback synchronous. Await completion before reading the live document or performing follow-up edits. Cancellation or a superseding edit leaves the live document intact.
| Argument | Type | Description |
|---|---|---|
callback | Function | Synchronous editing callback receiving an editor. |
optionsoptional, default: {} | Object | |
signaloptional | AbortSignal | Cancels preparation. |
bypassReadOnlyoptional, default: false | Boolean | Allows changing a read-only editor. |
groupUndooptional, default: false | Boolean | Groups publication with recent edits. |
Returns
*|Promise — The synchronous result, or a promise for prepared publication.
Abort an open transaction, undoing any operations performed so far within the transaction.
Create a pointer to the current state of the buffer for use with #revertToCheckpoint and #groupChangesSinceCheckpoint.
Returns
Number — checkpoint value.
Revert the buffer to the state it was in when the given checkpoint was created.
The redo stack will be empty following this operation, so changes since the checkpoint will be lost. If the given checkpoint is no longer present in the undo history, no changes will be made to the buffer and this method returns false.
| Argument | Type | Description |
|---|---|---|
checkpoint | Number | The checkpoint to revert to. |
Returns
Boolean — Whether the operation succeeded.
Group all changes since the given checkpoint into a single transaction for purposes of undo/redo.
If the given checkpoint is no longer present in the undo history, no
grouping will be performed and this method will return false.
| Argument | Type | Description |
|---|---|---|
checkpoint | Number | The checkpoint from which to group changes. |
Returns
Boolean — indicating whether the operation succeeded.
Coordinates9
Convert a position in buffer-coordinates to screen-coordinates.
The position is clipped via #clipBufferPosition prior to the conversion.
The position is also clipped via #clipScreenPosition following the
conversion, which only makes a difference when options are supplied.
| Argument | Type | Description |
|---|---|---|
bufferPosition | Point|Array<Number>|Object | A Point or Array of [row, column]. |
optionsoptional | Object | An options object for #clipScreenPosition. |
Returns
Convert a position in screen-coordinates to buffer-coordinates.
The position is clipped via #clipScreenPosition prior to the conversion.
| Argument | Type | Description |
|---|---|---|
screenPosition | Point|Array<Number>|Object | The screen position to convert. |
optionsoptional | Object | Options for #clipScreenPosition. |
Returns
Convert a rectangular block of screen positions – the same two columns across a span of screen rows – to buffer coordinates in bulk.
For each screen row from startRow through endRow, the returned entry
carries the buffer range delimited by [row, startColumn] and
[row, endColumn], translated exactly as
#bufferRangeForScreenRange translates them, with default clipping.
Columns beyond the end of a row’s screen line clip to the end of that
line.
When both columns clip to the same buffer position the entry’s range is
empty, and screenColumn reports the screen column that position
occupies – what #screenPositionForBufferPosition would return
for it. That is the datum which tells a row whose text ends before the
block apart from a row the block genuinely intersects. For non-empty
ranges screenColumn is null.
This is equivalent to calling #bufferRangeForScreenRange once per row, but the display layer walks its spatial index over the whole span a single time, which is substantially faster for large blocks.
| Argument | Type | Description |
|---|---|---|
startRow | Number | The first screen row of the block. |
endRow | Number | The last screen row of the block, inclusive. Must be at least startRow. |
startColumn | Number | The screen column of the block’s first edge. |
endColumn | Number | The screen column of the block’s second edge. May be less than startColumn; the two are translated in the order given. |
Returns
Array — of {bufferRange, screenColumn} objects, one per screen row, where bufferRange is a Range and screenColumn is a Number or null.
Clip the given Point to a valid position in the buffer.
If the given Point describes a position that is actually reachable by the cursor based on the current contents of the buffer, it is returned unchanged. If the Point does not describe a valid position, the closest valid position is returned instead.
Examples
editor.clipBufferPosition([-1, -1]) // -> `[0, 0]`
// When the line at buffer row 2 is 10 characters long
editor.clipBufferPosition([2, Infinity]) // -> `[2, 10]`
| Argument | Type | Description |
|---|---|---|
bufferPosition | Point|Array<Number>|Object | The Point representing the position to clip. |
Returns
Clip the start and end of the given range to valid positions in the buffer. See #clipBufferPosition for more information.
Returns
Clip the given Point to a valid position on screen.
If the given Point describes a position that is actually reachable by the cursor based on the current contents of the screen, it is returned unchanged. If the Point does not describe a valid position, the closest valid position is returned instead.
Examples
editor.clipScreenPosition([-1, -1]) // -> `[0, 0]`
// When the line at screen row 2 is 10 characters long
editor.clipScreenPosition([2, Infinity]) // -> `[2, 10]`
| Argument | Type | Description |
|---|---|---|
screenPosition | Point|Array<Number>|Object | The Point representing the position to clip. |
optionsoptional | Object | |
clipDirectionoptional | String | If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'. |
Returns
Point — The clipped screen position.
Clip the start and end of the given range to valid positions on screen. See #clipScreenPosition for more information.
| Argument | Type | Description |
|---|---|---|
screenRange | Range|Array|Object | The Range to clip. |
optionsoptional | Object | See #clipScreenPosition options. |
Returns
Decorations8
Add a decoration that tracks a DisplayMarker. When the marker moves, is invalidated, or is destroyed, the decoration will be updated to reflect the marker’s state.
The following are the supported decorations types:
- line: Adds the given CSS
classto the lines overlapping the rows spanned by the marker. - line-number: Adds the given CSS
classto the line numbers overlapping the rows spanned by the marker - text: Injects spans into all text overlapping the marked range, then adds
the given
classorstyleto these spans. Use this to manipulate the foreground color or styling of text in a range. - highlight: Creates an absolutely-positioned
.highlightdiv to the editor containing nested divs that cover the marked region. For example, when the user selects text, the selection is implemented with a highlight decoration. The structure of this highlight will be:<div class="highlight <your-class>"> <!-- One region per row in the marked range. --> <div class="region"></div> </div> - overlay: Positions the view associated with the given item at the head
or tail of the given
DisplayMarker, depending on thepositionproperty. - gutter: Tracks a DisplayMarker in a Gutter. Gutter decorations are created
by calling Gutter#decorateMarker on the desired
Gutterinstance. - block: Positions the view associated with the given item before or
after the row of the given DisplayMarker, depending on the
positionproperty. Block decorations at the same screen row are ordered by theirorderproperty. A block item takes the editor’s selection background whenever its visual position before or after that row lies within a non-empty selection. - cursor: Render a cursor at the head of the DisplayMarker. If multiple cursor decorations are created for the same marker, their class strings and style objects are combined into a single cursor. This decoration type may be used to style existing cursors by passing in their markers or to render artificial cursors that don’t actually exist in the model by passing a marker that isn’t associated with a real cursor.
An overlay that can have neither side — the one it asked for is taken,
the other will not fit — is pushed clear of whatever is in its way
rather than drawn over it, and the wrapper is marked
data-overlay-displaced to say it is no longer touching its line.
| Argument | Type | Description |
|---|---|---|
marker | DisplayMarker|Marker | A DisplayMarker you want this decoration to follow. |
decorationParams | Object | An Object representing the decoration e.g. {type: 'line-number', class: 'linter-error'} |
type | String|Array<String> | Determines the behavior and appearance of this Decoration. Supported decoration types and their uses are listed above. |
classoptional | String | This CSS class will be applied to the decorated line number, line, text spans, highlight regions, cursors, or overlay. |
styleoptional | Object | An Object containing CSS style properties to apply to the relevant DOM node. Currently this only works with a type of cursor or text. |
itemoptional | HTMLElement|Object | An HTMLElement or a model Object with a corresponding view registered. Only applicable to the gutter, overlay and block decoration types. |
onlyHeadoptional | Boolean | If true, the decoration will only be applied to the head of the DisplayMarker. Only applicable to the line and line-number decoration types. |
onlyEmptyoptional | Boolean | If true, the decoration will only be applied if the associated DisplayMarker is empty. Only applicable to the gutter, line, and line-number decoration types. |
onlyNonEmptyoptional | Boolean | If true, the decoration will only be applied if the associated DisplayMarker is non-empty. Only applicable to the gutter, line, and line-number decoration types. |
omitEmptyLastRowoptional | Boolean | If false, the decoration will be applied to the last row of a non-empty range, even if it ends at column 0. Defaults to true. Only applicable to the gutter, line, and line-number decoration types. |
positionoptional | String | Only applicable to decorations of type overlay and block. Controls where the view is positioned relative to the DisplayMarker. Values can be 'head' (the default) or 'tail' for overlay decorations, and 'before' (the default) or 'after' for block decorations. |
orderoptional | Number | Only applicable to decorations of type block. Controls where the view is positioned relative to other block decorations at the same screen row. If unspecified, block decorations render oldest to newest. |
avoidOverflowoptional | Boolean | Only applicable to decorations of type overlay. Determines whether the decoration adjusts its horizontal or vertical position to remain fully visible when it would otherwise overflow the editor. Defaults to true. An overlay that opts out is neither moved by nor an obstacle to the placement described below. |
sideoptional | String | Only applicable to decorations of type overlay. The side of the line the overlay asks for, 'above' or 'below' (the default). It is a request, not a guarantee: an overlay takes the other side when the one it asked for will not fit the window or is already taken, and the side it ended up on is reported back on the wrapper as data-overlay-position. |
lockSideoptional | Boolean | Only applicable to decorations of type overlay with overflow avoidance enabled. If true, retains the side selected when the mounted overlay first has a nonzero width and height. Scrolling and resizing keep following its marker without switching sides, even if the overlay later overflows the window. A new decoration or remounted overlay chooses again. Defaults to false. |
priorityoptional | Number | Only applicable to decorations of type overlay. When several overlays want the same side of the same line, the higher priority chooses first and the others work around it; it also decides which one paints on top. Defaults to 0. The convention across the bundled packages is autocomplete 2, intentions 1, hover 0. |
Returns
Decoration — created Decoration object.
Add a decoration to every marker in the given marker layer. Can be used to decorate a large number of markers without having to create and manage many individual decorations.
| Argument | Type | Description |
|---|---|---|
markerLayer | DisplayMarkerLayer|MarkerLayer | A DisplayMarkerLayer or MarkerLayer to decorate. |
decorationParams | Object | The same parameters that are passed to TextEditor#decorateMarker, except the type cannot be overlay or gutter. |
Returns
Coalesce decoration and marker-layer update notifications for synchronous work. Does not open an undo transaction. Individual marker change and decoration add/remove events remain synchronous. Nested batches publish one final update, including applied changes when the callback throws. Promises are not awaited.
| Argument | Type | Description |
|---|---|---|
callback | Function | Work that creates, moves, updates or removes decorations and markers. |
Returns
* — The callback result.
Get all decorations.
| Argument | Type | Description |
|---|---|---|
propertyFilteroptional | Object | An Object containing key value pairs that the returned decorations’ properties must match. |
Returns
Array<Decoration> — The decorations matching the property filter.
Get all decorations of type ‘line’.
| Argument | Type | Description |
|---|---|---|
propertyFilteroptional | Object | An Object containing key value pairs that the returned decorations’ properties must match. |
Returns
Array<Decoration> — The decorations matching the property filter.
Get all decorations of type ‘line-number’.
| Argument | Type | Description |
|---|---|---|
propertyFilteroptional | Object | An Object containing key value pairs that the returned decorations’ properties must match. |
Returns
Array<Decoration> — The decorations matching the property filter.
Get all decorations of type ‘highlight’.
| Argument | Type | Description |
|---|---|---|
propertyFilteroptional | Object | An Object containing key value pairs that the returned decorations’ properties must match. |
Returns
Array<Decoration> — The decorations matching the property filter.
Get all decorations of type ‘overlay’.
| Argument | Type | Description |
|---|---|---|
propertyFilteroptional | Object | An Object containing key value pairs that the returned decorations’ properties must match. |
Returns
Array<Decoration> — The decorations matching the property filter.
Markers11
Create a marker on the default marker layer with the given range in buffer coordinates. This marker will maintain its logical location as the buffer is changed, so if you mark a particular word, the marker will remain over that word even if the word’s location in the buffer changes.
| Argument | Type | Description |
|---|---|---|
bufferRange | Range|Array|Object | A Range or range-compatible Array |
optionsoptional | Object | A hash of key-value pairs to associate with the marker. There are also reserved property names that have marker-specific meaning. |
maintainHistoryoptional | Boolean | Whether to store this marker’s range before and after each change in the undo history. This allows the marker’s position to be restored more accurately for certain undo/redo operations, but uses more time and memory. (default: false) |
reversedoptional | Boolean | Creates the marker in a reversed orientation. (default: false) |
invalidateoptional | String | Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility:
|
Returns
Create a marker on the default marker layer with the given range in screen coordinates. This marker will maintain its logical location as the buffer is changed, so if you mark a particular word, the marker will remain over that word even if the word’s location in the buffer changes.
| Argument | Type | Description |
|---|---|---|
screenRange | Range|Array|Object | A Range or range-compatible Array |
optionsoptional | Object | A hash of key-value pairs to associate with the marker. There are also reserved property names that have marker-specific meaning. |
maintainHistoryoptional | Boolean | Whether to store this marker’s range before and after each change in the undo history. This allows the marker’s position to be restored more accurately for certain undo/redo operations, but uses more time and memory. (default: false) |
reversedoptional | Boolean | Creates the marker in a reversed orientation. (default: false) |
invalidateoptional | String | Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility:
|
Returns
Create a marker on the default marker layer with the given buffer position and no tail. To group multiple markers together in their own private layer, see #addMarkerLayer.
| Argument | Type | Description |
|---|---|---|
bufferPosition | Point|Array<Number>|Object | A Point or point-compatible Array |
optionsoptional | Object | An Object with the following keys: |
invalidateoptional | String | Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility:
|
Returns
Create a marker on the default marker layer with the given screen position and no tail. To group multiple markers together in their own private layer, see #addMarkerLayer.
| Argument | Type | Description |
|---|---|---|
screenPosition | Point|Array<Number>|Object | A Point or point-compatible Array |
optionsoptional | Object | An Object with the following keys: |
invalidateoptional | String | Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility:
|
clipDirectionoptional | String | If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'. |
Returns
DisplayMarker — The new marker.
Find all DisplayMarkers on the default marker layer that match the given properties.
This method finds markers based on the given properties. Markers can be associated with custom properties that will be compared with basic equality. In addition, there are several special properties that will be compared with the range of the markers rather than their properties.
| Argument | Type | Description |
|---|---|---|
paramsoptional | Object | An Object containing properties that each returned marker must satisfy. Markers can be associated with custom properties, which are compared with basic equality. In addition, several reserved properties can be used to filter markers based on their current range: |
startBufferRowoptional | Number | Only include markers starting at this row in buffer coordinates. |
endBufferRowoptional | Number | Only include markers ending at this row in buffer coordinates. |
containsBufferRangeoptional | Range | Only include markers containing this Range or in range-compatible Array in buffer coordinates. |
containsBufferPositionoptional | Point |
Returns
Array<DisplayMarker> — The markers matching the query.
Get the DisplayMarker on the default layer for the given marker id.
| Argument | Type | Description |
|---|---|---|
id | Number | id of the marker |
Returns
DisplayMarker|undefined — The marker on the default layer, or undefined when the id is unknown.
Get all DisplayMarkers on the default marker layer. Consider using #findMarkers
Returns
Array<DisplayMarker> — The markers on the default layer.
Get the number of markers in the default marker layer.
Returns
Number
Create a marker layer to group related markers.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | An Object containing the following keys: |
maintainHistoryoptional | Boolean | A Boolean indicating whether marker state should be restored on undo/redo. Defaults to false. |
persistentoptional | Boolean | A Boolean indicating whether or not this marker layer should be serialized and deserialized along with the rest of the buffer. Defaults to false. If true, the marker layer’s id will be maintained across the serialization boundary, allowing you to retrieve it via #getMarkerLayer. |
trackRangesoptional | Function | A synchronous callback applying custom edit tracking to touched markers. See TextBuffer#addMarkerLayer for its arguments and return value. The callback is not serialized and can be replaced through DisplayMarkerLayer#setRangeTracker. |
Returns
Get a DisplayMarkerLayer by id.
| Argument | Type | Description |
|---|---|---|
id | String | The id of the marker layer to retrieve. |
Returns
DisplayMarkerLayer|undefined — The layer, or undefined when the id is unknown.
Get the default DisplayMarkerLayer.
All marker APIs not tied to an explicit layer interact with this default layer.
Returns
Cursors34
Get the position of the most recently added cursor in buffer coordinates.
Returns
Get the position of all the cursor positions in buffer coordinates.
Returns
Array<Point> — The cursor positions in creation order.
Move the cursor to the given position in buffer coordinates.
If there are multiple cursors, they will be consolidated to a single cursor.
| Argument | Type | Description |
|---|---|---|
position | Point|Array<Number>|Object | |
optionsoptional | Object | An Object containing the following keys: |
autoscrolloptional | Boolean | Determines whether the editor scrolls to the new cursor’s position. Defaults to true. |
modeoptional | String|Number|Array<Number> | The scroll mode when autoscrolling. See #scrollToScreenRange. |
Get the position of the most recently added cursor in screen coordinates.
Returns
Get the position of all the cursor positions in screen coordinates.
Returns
Array<Point> — The cursor positions in creation order.
Move the cursor to the given position in screen coordinates.
If there are multiple cursors, they will be consolidated to a single cursor.
| Argument | Type | Description |
|---|---|---|
position | Point|Array<Number>|Object | |
optionsoptional | Object | An Object combining options for #clipScreenPosition with: |
autoscrolloptional | Boolean | Determines whether the editor scrolls to the new cursor’s position. Defaults to true. |
modeoptional | String|Number|Array<Number> | The scroll mode when autoscrolling. See #scrollToScreenRange. |
Add a cursor at the given position in buffer coordinates.
| Argument | Type | Description |
|---|---|---|
bufferPosition | Point|Array<Number>|Object | |
optionsoptional | Object | Options for this operation. |
autoscrolloptional, default: true | Boolean | Scroll to the new cursor or selection. |
modeoptional | String|Number|Array<Number> | Scroll mode; see #scrollToScreenRange. |
Returns
Add a cursor at the position in screen coordinates.
| Argument | Type | Description |
|---|---|---|
screenPosition | Point|Array<Number>|Object | |
optionsoptional | Object | Options for this operation. |
autoscrolloptional, default: true | Boolean | Scroll to the new cursor or selection. |
modeoptional | String|Number|Array<Number> | Scroll mode; see #scrollToScreenRange. |
Returns
Determine whether this editor has more than one cursor.
Returns
Boolean — indicating whether or not there are multiple cursors.
Move every cursor up one row in screen coordinates.
| Argument | Type | Description |
|---|---|---|
lineCountoptional | Number | number of lines to move |
Move every cursor down one row in screen coordinates.
| Argument | Type | Description |
|---|---|---|
lineCountoptional | Number | number of lines to move |
Move every cursor left one column.
| Argument | Type | Description |
|---|---|---|
columnCountoptional | Number | number of columns to move (default: 1) |
Move every cursor right one column.
| Argument | Type | Description |
|---|---|---|
columnCountoptional | Number | number of columns to move (default: 1) |
Move every cursor to the beginning of its line in buffer coordinates.
Move every cursor to the beginning of its line in screen coordinates.
Move every cursor to the first non-whitespace character of its line.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | Cursor position options, including autoscroll and mode. |
Move every cursor to the end of its line in buffer coordinates.
Move every cursor to the end of its line in screen coordinates.
Move every cursor to the beginning of its surrounding word.
Move every cursor to the end of its surrounding word.
Move every cursor to the top of the buffer.
If there are multiple cursors, they will be merged into a single cursor.
Move every cursor to the bottom of the buffer.
If there are multiple cursors, they will be merged into a single cursor.
Move every cursor to the beginning of the next word.
Move every cursor to the previous word boundary.
Move every cursor to the next word boundary.
Move every cursor to the previous subword boundary.
Move every cursor to the next subword boundary.
Move every cursor to the beginning of the next paragraph.
Move every cursor to the beginning of the previous paragraph.
Get the word under the most recently added cursor.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object |
Returns
String — word surrounding the most recently added cursor.
Selections43
Get the selected text of the most recently added selection.
Returns
String
Set the selected range in buffer coordinates. If there are multiple selections, they are reduced to a single selection with the given range.
| Argument | Type | Description |
|---|---|---|
bufferRange | Range|Array|Object | A Range or range-compatible Array. |
optionsoptional | Object | An Object of options: |
reversedoptional | Boolean | A Boolean indicating whether to create the selection in a reversed orientation. |
preserveFoldsoptional | Boolean | A Boolean, which if true preserves the fold settings after the selection is set. |
Set the selected ranges in buffer coordinates. If there are multiple selections, they are replaced by new selections with the given ranges.
| Argument | Type | Description |
|---|---|---|
bufferRanges | Array<Range|Array|Object> | |
optionsoptional, default: {} | Object | An Object of options: |
reversedoptional | Boolean | A Boolean indicating whether to create the selection in a reversed orientation. |
preserveFoldsoptional | Boolean | A Boolean, which if true preserves the fold settings after the selection is set. |
Set the selected range in screen coordinates. If there are multiple selections, they are reduced to a single selection with the given range.
Set the selected ranges in screen coordinates. If there are multiple selections, they are replaced by new selections with the given ranges.
Add a selection for the given range in buffer coordinates.
| Argument | Type | Description |
|---|---|---|
bufferRange | Range|Array|Object | A Range |
optionsoptional, default: {} | Object | An Object of options: |
reversedoptional | Boolean | A Boolean indicating whether to create the selection in a reversed orientation. |
preserveFoldsoptional | Boolean | A Boolean, which if true preserves the fold settings after the selection is set. |
autoscrolloptional, default: true | Boolean | Scroll to the new cursor or selection. |
modeoptional | String|Number|Array<Number> | Scroll mode; see #scrollToScreenRange. |
Returns
Add a selection for the given range in screen coordinates.
| Argument | Type | Description |
|---|---|---|
screenRange | Range|Array|Object | A Range |
optionsoptional, default: {} | Object | An Object of options: |
reversedoptional | Boolean | A Boolean indicating whether to create the selection in a reversed orientation. |
preserveFoldsoptional | Boolean | A Boolean, which if true preserves the fold settings after the selection is set. |
autoscrolloptional, default: true | Boolean | Scroll to the new cursor or selection. |
modeoptional | String|Number|Array<Number> | Scroll mode; see #scrollToScreenRange. |
Returns
Select from the current cursor position to the given position in screen coordinates.
This method may merge selections that end up intersecting.
Move the cursor of each selection one character upward while preserving the selection’s tail position.
This method may merge selections that end up intersecting.
| Argument | Type | Description |
|---|---|---|
rowCountoptional | Number | number of rows to select (default: 1) |
Move the cursor of each selection one character downward while preserving the selection’s tail position.
This method may merge selections that end up intersecting.
| Argument | Type | Description |
|---|---|---|
rowCountoptional | Number | number of rows to select (default: 1) |
Move the cursor of each selection one character leftward while preserving the selection’s tail position.
This method may merge selections that end up intersecting.
| Argument | Type | Description |
|---|---|---|
columnCountoptional | Number | number of columns to select (default: 1) |
Move the cursor of each selection one character rightward while preserving the selection’s tail position.
This method may merge selections that end up intersecting.
| Argument | Type | Description |
|---|---|---|
columnCountoptional | Number | number of columns to select (default: 1) |
Select from the top of the buffer to the end of the last selection in the buffer.
This method merges multiple selections into a single selection.
Selects from the top of the first selection in the buffer to the end of the buffer.
This method merges multiple selections into a single selection.
Select all text in the buffer.
This method merges multiple selections into a single selection.
Move the cursor of each selection to the beginning of its line while preserving the selection’s tail position.
This method may merge selections that end up intersecting.
Move the cursor of each selection to the first non-whitespace character of its line while preserving the selection’s tail position. If the cursor is already on the first character of the line, move it to the beginning of the line.
This method may merge selections that end up intersecting.
Move the cursor of each selection to the end of its line while preserving the selection’s tail position.
This method may merge selections that end up intersecting.
Expand selections to the beginning of their containing word.
Operates on all selections. Moves the cursor to the beginning of the containing word while preserving the selection’s tail position.
Expand selections to the end of their containing word.
Operates on all selections. Moves the cursor to the end of the containing word while preserving the selection’s tail position.
For each selection, move its cursor to the preceding subword boundary while maintaining the selection’s tail position.
This method may merge selections that end up intersecting.
For each selection, move its cursor to the next subword boundary while maintaining the selection’s tail position.
This method may merge selections that end up intersecting.
For each cursor, select the containing line.
Intersecting selections may be merged.
Select the word surrounding each cursor.
Select the subword surrounding each cursor.
For each selection, move its cursor to the preceding word boundary while maintaining the selection’s tail position.
This method may merge selections that end up intersecting.
For each selection, move its cursor to the next word boundary while maintaining the selection’s tail position.
This method may merge selections that end up intersecting.
Expand selections to the beginning of the next word.
Operates on all selections. Moves the cursor to the beginning of the next word while preserving the selection’s tail position.
Expand selections to the beginning of the next paragraph.
Operates on all selections. Moves the cursor to the beginning of the next paragraph while preserving the selection’s tail position.
Expand selections to the beginning of the previous paragraph.
Operates on all selections. Moves the cursor to the beginning of the previous paragraph while preserving the selection’s tail position.
For each selection, select the syntax node that contains that selection.
Undo the effect of a preceding call to #selectLargerSyntaxNode.
Select the range of the given marker if it is valid.
| Argument | Type | Description |
|---|---|---|
marker | DisplayMarker |
Returns
Range|undefined — selected Range or undefined if the marker is invalid.
Get current Selections.
Returns
Array<Selection> — The current selections.
Get all Selections, ordered by their position in the buffer instead of the order in which they were added.
Returns
Array<Selection> — Selections ordered by their buffer positions.
Destroy the given Selections as one batch.
Emits did-remove-cursor and did-remove-selection once per selection, in
the order given, exactly as destroying each one in turn would. What changes
is the bookkeeping: the selection and cursor lists are compacted once for
the whole batch rather than rescanned and spliced once per selection, which
is what makes discarding thousands of selections linear rather than
quadratic.
Selections that are already destroyed are ignored.
| Argument | Type | Description |
|---|---|---|
selections | Array<Selection> | An Array of Selections. |
Searching and Replacing3
Scan regular expression matches in the entire buffer, calling the given iterator function on each match.
::scan functions as the replace method as well via the replace
If you’re programmatically modifying the results, you may want to try #backwardsScanInBufferRange to avoid tripping over your own changes.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
optionsoptional, default: {} | Object | |
iterator | Function | A Function that’s called on each match |
leadingContextLineCountoptional | Number | default 0; The number of lines before the matched line to include in the results object. |
trailingContextLineCountoptional | Number | default 0; The number of lines after the matched line to include in the results object. |
result | Object | Match information supplied as the callback’s only argument. |
object | Object | |
match | Array | The current regular expression match. |
matchText | String | A String with the text of the match. |
range | Range | The Range of the match. |
stop | Function | Call this Function to terminate the scan. |
replace | Function | Call this Function with a String to replace the match. |
Scan regular expression matches in a given range, calling the given iterator function on each match.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
range | Range|Array|Object | A Range in which to search. |
iterator | Function | A Function that’s called on each match with an Object containing the following keys: |
result | Object | Match information supplied as the callback’s only argument. |
match | Array | The current regular expression match. |
matchText | String | A String with the text of the match. |
range | Range | The Range of the match. |
stop | Function | Call this Function to terminate the scan. |
replace | Function | Call this Function with a String to replace the match. |
Scan regular expression matches in a given range in reverse order, calling the given iterator function on each match.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search for. |
range | Range|Array|Object | A Range in which to search. |
iterator | Function | A Function that’s called on each match with an Object containing the following keys: |
result | Object | Match information supplied as the callback’s only argument. |
match | Array | The current regular expression match. |
matchText | String | A String with the text of the match. |
range | Range | The Range of the match. |
stop | Function | Call this Function to terminate the scan. |
replace | Function | Call this Function with a String to replace the match. |
Tab Behavior7
Determine whether this editor inserts spaces for tabs.
Returns
Boolean — indicating whether softTabs are enabled for this editor.
Enable or disable soft tabs for this editor.
| Argument | Type | Description |
|---|---|---|
softTabs | Boolean | A Boolean |
Toggle soft tabs for this editor
Get the on-screen length of tab characters.
Returns
Number
Set the displayed width of tab characters, overriding editor.tabLength for this editor.
| Argument | Type | Description |
|---|---|---|
tabLength | Number|null | length of a single tab. Setting to null will fallback to using the editor.tabLength config setting |
Determine if the buffer uses hard or soft tabs.
Returns
Boolean|undefined — true for leading spaces, false for a leading hard tab (\t), or undefined when no non-comment line has leading whitespace.
Get the text representing a single level of indent.
If soft tabs are enabled, the text is composed of N spaces, where N is the
tab length. Otherwise the text is a tab character (\t).
Returns
String
Soft Wrap Behavior6
Determine whether lines in this editor are soft-wrapped.
Returns
Boolean
Enable or disable soft wrapping for this editor.
| Argument | Type | Description |
|---|---|---|
softWrapped | Boolean | A Boolean |
Returns
Boolean
Get the minimum wrapping column. Zero leaves the minimum unrestricted.
Returns
Number
Get the maximum wrapping column. Zero leaves the maximum unrestricted.
Returns
Number
Toggle soft wrapping for this editor
Returns
Boolean
Get the column at which screen lines soft wrap.
Returns
Number — The wrapping column, or the large-line safety limit when ordinary wrapping is disabled.
Overtype Behavior4
Determine whether overtype (overwrite) mode is enabled for this editor. In overtype mode, typing replaces the character following the cursor instead of inserting before it.
Returns
Boolean
Enable or disable overtype (overwrite) mode for this editor.
| Argument | Type | Description |
|---|---|---|
overtypeMode | Boolean | A Boolean. |
Returns
Boolean
Toggle overtype (overwrite) mode for this editor.
Returns
Boolean
When overtype mode is active, expand each empty selection one character to the right (except at the end of a line) so that the text about to be inserted overwrites the following character rather than being inserted before it. Non-empty selections are left untouched and replaced as usual.
Called by the editor component immediately before inserting genuinely typed
text; it has no effect unless #isOvertypeMode is true.
Indentation6
Get the indentation level of the given buffer row.
Determines how deeply the given row is indented based on the soft tabs and tab length settings of this editor. Note that if soft tabs are enabled and the tab length is 2, a row with 4 leading spaces would have an indentation level of 2.
| Argument | Type | Description |
|---|---|---|
bufferRow | Number | A Number indicating the buffer row. |
Returns
Number
Set the indentation level for the given buffer row.
Inserts or removes hard tabs or spaces based on the soft tabs and tab length settings of this editor in order to bring it to the given indentation level. Note that if soft tabs are enabled and the tab length is 2, a row with 4 leading spaces would have an indentation level of 2.
| Argument | Type | Description |
|---|---|---|
bufferRow | Number | A Number indicating the buffer row. |
newLevel | Number | A Number indicating the new indentation level. |
optionsoptional, default: {} | Object | Indentation options. |
preserveLeadingWhitespaceoptional, default: false | Boolean | Preserve whitespace already at the beginning of the line. |
Indent rows intersecting selections by one level. Large row sets prepare cooperatively and publish one undo operation.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. |
signaloptional | AbortSignal | Cancels asynchronous preparation. |
Returns
Array|undefined|Promise<Number> — Small edits return per-selection results; await large edits before reading changed text.
Outdent rows intersecting selections by one level. Large row sets prepare cooperatively and publish one undo operation.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. |
signaloptional | AbortSignal | Cancels asynchronous preparation. |
Returns
Array|undefined|Promise<Number> — Small edits return per-selection results; await large edits before reading changed text.
Get the indentation level of the given line of text.
Determines how deeply the given line is indented based on the soft tabs and tab length settings of this editor. Note that if soft tabs are enabled and the tab length is 2, a row with 4 leading spaces would have an indentation level of 2.
| Argument | Type | Description |
|---|---|---|
line | String | A String representing a line of text. |
Returns
Number
Indent rows intersecting selections based on the grammar’s suggested indent level. Large ranges consume bounded grammar batches and commit atomically.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. |
signaloptional | AbortSignal | Cancels asynchronous preparation. |
Returns
Object|undefined|Promise<Object|undefined> — The changed flag and resulting revision, or undefined when unavailable. Await asynchronous plans before reading changed text.
Grammars6
Get the current TreeSitterGrammar, or the null grammar sentinel.
Returns
TreeSitterGrammar|Object — The current Tree-sitter grammar or the null grammar sentinel.
Report whether syntax analysis is enabled, independently of parse readiness.
A disabled language reports reason none; a failed analysis reports reason
failure and a diagnostic object. The selected grammar is preserved on failure.
Returns
Object — Availability with an available boolean and optional reason and failure.
Observe syntax availability when the document’s language mode is replaced. Consumers should clear staged results and decorations when analysis becomes unavailable.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives the current availability object. |
Returns
Disposable — Subscription to language-mode availability changes.
Explicitly retry failed syntax analysis using the current document text.
Returns
Boolean — Whether a new analysis was started.
Get a notification when async tokenization is completed.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called when tokenization completes. |
Returns
Disposable — Subscription to tokenization completion.
Wait for the current grammar to finish its initial parse and any pending transaction, including injected language layers and requested automatic indentation. Indentation edits are parsed before this wait completes.
Returns false when the editor is destroyed, the grammar changes, the
optional signal is aborted, or parsing the current transaction fails. A
parser-loading or grammar-settlement failure rejects the returned promise.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
signaloptional | AbortSignal | Cancels this wait when aborted. |
Returns
Promise<Boolean> — Resolves to whether the current grammar settled successfully.
Managing Syntax Scopes9
Get the scope descriptor for this editor’s root grammar.
Returns
ScopeDescriptor — The root grammar scopes, suitable for language-specific Config#get settings.
Get the syntactic ScopeDescriptor for the given position in buffer coordinates. Useful with Config#get. With worker syntax this is a cached presentation read. Use #getScopeDescriptorsForBufferPositions for exact semantic decisions.
For example, if called with a position inside the parameter list of an
anonymous CoffeeScript function, this method returns a ScopeDescriptor with
the following scopes array:
["source.coffee", "meta.function.inline.coffee", "meta.parameters.coffee", "variable.parameter.function.coffee"]
Returns
Query exact current syntax scopes for several positions in one analysis. Returns null if the text or grammar changes before completion.
| Argument | Type | Description |
|---|---|---|
positions | Array<Point|Array<Number>|Object> | Buffer positions. |
optionsoptional | Object | Optional abort signal. |
Returns
Promise<Array<ScopeDescriptor>|null>
Query comment delimiters for several positions against one syntax revision.
| Argument | Type | Description |
|---|---|---|
positions | Array<Point|Array<Number>|Object> | Buffer positions. |
optionsoptional | Object | Optional abort signal. |
Returns
Promise<Array<Object|null>|null> — Null when the analysis was invalidated.
Get the syntactic tree ScopeDescriptor for the given position in buffer coordinates.
For example, if called with a position inside the parameter list of a
JavaScript class function, this method returns a ScopeDescriptor with
the following syntax nodes array:
["source.js", "program", "expression_statement", "assignment_expression", "class", "class_body", "method_definition", "formal_parameters", "identifier"]
Returns
ScopeDescriptor|Promise<ScopeDescriptor> — Worker syntax resolves asynchronously.
Get the range in buffer coordinates of all tokens surrounding the cursor that match the given scope selector.
For example, if you wanted to find the string surrounding the cursor, you
could call editor.bufferRangeForScopeAtCursor(".string.quoted").
| Argument | Type | Description |
|---|---|---|
scopeSelector | String | selector. e.g. '.source.ruby' |
Returns
Range|null|undefined — The matching buffer range, or null/undefined when no matching scope is found.
Get the range in buffer coordinates of all tokens surrounding the given position in buffer coordinates that match the given scope selector.
For example, if you wanted to find the string surrounding the cursor, you
could call editor.bufferRangeForScopeAtPosition(".string.quoted", this.getCursorBufferPosition()).
| Argument | Type | Description |
|---|---|---|
scopeSelector | String | selector. e.g. '.source.ruby' |
bufferPosition | Point|Array<Number>|Object | A Point or Array of [row, column] |
Returns
Range|null|undefined — The matching buffer range, or null/undefined when no matching scope is found.
Determine whether the first non-whitespace character on the given row has a comment scope.
| Argument | Type | Description |
|---|---|---|
bufferRow | Number | The zero-indexed buffer row. |
Returns
Boolean|undefined|Promise<Boolean|undefined> — Whether the first non-whitespace character has a comment scope, or undefined for a blank row. Worker syntax resolves asynchronously.
Get the comment delimiters at a given buffer position.
Lumine allows language bundles to define comment delimiters in several places. For instance, a grammar author can place delimiter metadata in the grammar definition file, or as scope-specific settings in the ordinary config system — or a combination of the two.
In some languages, comment delimiters vary based on position in the buffer. (For instance, line comments can’t always be used in JavaScript JSX blocks, so block comments are much safer.) This method will look for any such overrides and return what it thinks are the best delimiters to use at a given point.
Some languages don’t specify all their delimiters in their configuration, but this method will return all the information that it can discern.
line: If present, aStringrepresenting a line comment delimiter. (Ifundefined, there is no known line comment delimiter for the given buffer position.)block: If present, a two-itemArraycontainingStringsrepresenting the starting and ending block comment delimiters. (Ifundefined, there are no known block comment delimiters for the given buffer position.)
Returns
Object|null — The appropriate comment delimiters, or null when none are known.
Syntax Trees3
Get the smallest Tree-sitter syntax node at the given position in buffer coordinates across all language layers.
Node breadth decides between candidates first; the deeper language layer
wins only when candidates have equal breadth. An optional predicate
receives each candidate node and its grammar. Returns null when no syntax
tree is available, including before the grammar’s first parse and while
using the null grammar.
The returned node belongs to the current parse snapshot. Do not retain it after the buffer changes or the grammar reparses; request it again instead.
Available only to the inline parser backend. Worker syntax requires moving node access into #analyzeSyntax; direct calls throw.
| Argument | Type | Description |
|---|---|---|
bufferPosition | Point|Array<Number>|Object | |
whereoptional | Function | Optional predicate receiving a syntax node and its TreeSitterGrammar. |
Returns
Object|null — A Tree-sitter syntax node, or null.
Get the smallest Tree-sitter syntax node that contains the given range in buffer coordinates across all language layers shared by both endpoints.
Node breadth decides between candidates first; the deeper language layer
wins only when candidates have equal breadth. An optional predicate
receives each candidate node and its grammar. Returns null when no syntax
tree or shared containing layer is available.
The returned node belongs to the current parse snapshot. Do not retain it after the buffer changes or the grammar reparses; request it again instead.
Available only to the inline parser backend. Worker syntax requires moving node access into #analyzeSyntax; direct calls throw.
| Argument | Type | Description |
|---|---|---|
bufferRange | Range|Array|Object | |
whereoptional | Function | Optional predicate receiving a syntax node and its TreeSitterGrammar. |
Returns
Object|null — A Tree-sitter syntax node, or null.
Run a package’s syntax analysis beside the parser that owns this document.
The module exports a function receiving a read-only document context,
serializable parameters, and {signal, emit}. Only data may be returned;
syntax nodes must remain inside the analysis. Stream consumers should stage
their results until this promise resolves with a current revision.
| Argument | Type | Description |
|---|---|---|
modulePath | String | Absolute path to the package’s analysis module. |
method | String | Name of the exported analysis function. |
params | * | Serializable analysis parameters. |
optionsoptional, default: {} | Object | |
signaloptional | AbortSignal | Cancels the analysis. |
onChunkoptional | Function | Accepts one streamed data packet; may return a promise. |
Returns
Promise<*> — Analysis data, or null when analysis is unavailable, disabled by None, or the invocation becomes obsolete. Errors in package analysis code still reject.
Grammar Queries2
Determine whether the current root grammar or an active injected grammar declares a query of the given type.
This checks declarations only; it does not load or compile the query.
| Argument | Type | Description |
|---|---|---|
queryType | String | The grammar query property to inspect, such as tagsQuery. |
Returns
Boolean — Whether the query is declared by a current language layer.
Run a grammar query against the current root syntax tree and all active injected language layers.
The returned groups contain each matching grammar and its captures after Tree-sitter predicates and scope adjustments are applied. Returns an empty array when the query is absent, parsing is cancelled or unsuccessful, the grammar changes, or the editor is destroyed.
Captures contain syntax nodes from the current parse snapshot. Do not retain them after the buffer changes or the grammar reparses. Parser-loading and query-execution failures reject the returned promise.
Available only to the inline parser backend. Worker syntax requires moving node access into #analyzeSyntax; direct calls throw.
| Argument | Type | Description |
|---|---|---|
queryType | String | The grammar query property to run, such as tagsQuery. |
optionsoptional, default: {} | Object | |
signaloptional | AbortSignal | Cancels this query when aborted. |
Returns
Promise<Array<Object>> — Resolves to grammar/captures groups from the current language layers.
Clipboard Operations5
For each selection, copy the selected text.
| Argument | Type | Description |
|---|---|---|
clipboardoptional, default: this.constructor.clipboard | Clipboard|Object | A clipboard or compatible adapter; defaults to the editor’s clipboard. |
Returns
Promise|undefined — A promise when the clipboard adapter flushes asynchronously; otherwise completes synchronously.
For each selection, cut the selected text.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. |
clipboardoptional | Clipboard|Object | Clipboard adapter to write; defaults to the editor’s clipboard. |
Returns
Promise|undefined — A promise when the clipboard adapter flushes asynchronously; otherwise completes synchronously.
For each selection, replace the selected text with the contents of the clipboard.
If the clipboard contains the same number of selections as the current editor, each selection will be replaced with the content of the corresponding clipboard selection text. Worker-backed multiline pastes prepare their final indentation before changing live text or selections. Changing the document, selections, grammar or indentation settings cancels that preparation without an edit.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | See Selection#insertText. |
clipboardoptional | Clipboard|Object | Clipboard adapter to read; defaults to the editor’s clipboard. |
Returns
Promise|Boolean|undefined — A promise when clipboard reading or indentation is asynchronous, false when an observer cancels a synchronous paste, or undefined on synchronous completion or refusal.
For each selection, if the selection is empty, cut all characters of the containing screen line following the cursor. Otherwise cut the selected text.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. |
clipboardoptional | Clipboard|Object | Clipboard adapter to write; defaults to the editor’s clipboard. |
Returns
Promise|undefined — A promise when the clipboard adapter flushes asynchronously; otherwise completes synchronously.
For each selection, if the selection is empty, cut all characters of the containing buffer line following the cursor. Otherwise cut the selected text.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
bypassReadOnlyoptional | Boolean | Must be true to modify a read-only editor. |
clipboardoptional | Clipboard|Object | Clipboard adapter to write; defaults to the editor’s clipboard. |
Returns
Promise|undefined — A promise when the clipboard adapter flushes asynchronously; otherwise completes synchronously.
Folds15
Get the foldable range that starts at the given row in buffer coordinates without creating a fold.
Unlike #foldBufferRow, this method does not search preceding rows for a fold that contains the given row.
| Argument | Type | Description |
|---|---|---|
bufferRow | Number | A Number. |
Returns
Range|null|Promise<Range|null> — The exact foldable range, or null when the row does not start one. Worker syntax resolves asynchronously.
Fold the most recent cursor’s row based on its indentation level.
The fold will extend from the nearest preceding line with a lower indentation level up to the nearest following row with a lower indentation level.
Unfold the most recent cursor’s row by one level.
Fold the given row in buffer coordinates based on its indentation level.
If the given row is foldable, the fold will begin there. Otherwise, it will begin at the first foldable row preceding the given row.
| Argument | Type | Description |
|---|---|---|
bufferRow | Number | A Number. |
optionsoptional, default: {} | Object | Options for this operation. |
signaloptional | AbortSignal | Signal that cancels pending folding work. |
Unfold all folds containing the given row in buffer coordinates.
| Argument | Type | Description |
|---|---|---|
bufferRow | Number | A Number |
For each selection, fold the rows it intersects.
Fold all foldable lines.
Unfold all existing folds.
Fold all foldable lines at the given indent level.
| Argument | Type | Description |
|---|---|---|
level | Number | A Number starting at 0. |
Determine whether the given row in buffer coordinates is foldable.
A foldable row is a row that starts a row range that can be folded.
| Argument | Type | Description |
|---|---|---|
bufferRow | Number | A Number |
Returns
Boolean|undefined|Promise<Boolean|undefined> — Whether the row is foldable; undefined when the language mode supplies no foldability check.
Determine whether the given row in screen coordinates is foldable.
A foldable row is a row that starts a row range that can be folded.
| Argument | Type | Description |
|---|---|---|
screenRow | Number | A Number |
Returns
Boolean|undefined|Promise<Boolean|undefined> — Whether the row is foldable; undefined when the language mode supplies no foldability check.
Fold the given buffer row if it isn’t currently folded, and unfold it otherwise.
| Argument | Type | Description |
|---|---|---|
bufferRow | Number | The zero-indexed buffer row. |
Determine whether the most recently added cursor’s row is folded.
Returns
Boolean
Determine whether the given row in buffer coordinates is folded.
| Argument | Type | Description |
|---|---|---|
bufferRow | Number | A Number |
Returns
Boolean
Determine whether the given row in screen coordinates is folded.
| Argument | Type | Description |
|---|---|---|
screenRow | Number | A Number |
Returns
Boolean
Gutters3
Add a custom Gutter.
| Argument | Type | Description |
|---|---|---|
options | Object | An Object with the following fields: |
name | String | (required) A unique String to identify this gutter. |
priorityoptional | Number | A Number that determines stacking order between gutters. Lower priority items are forced closer to the edges of the window. (default: -100) |
visibleoptional | Boolean | specifying whether the gutter is visible initially after being created. (default: true) |
typeoptional | String | specifying the type of gutter to create. 'decorated' gutters are useful as a destination for decorations created with Gutter#decorateMarker. 'line-number' gutters. |
classoptional | String | added to the CSS classnames of the gutter’s root DOM element. |
labelFnoptional | Function | called by a 'line-number' gutter to generate the label for each line number element. Should return a String that will be used to label the corresponding line. |
lineData | Object | an Object containing information about each line to label. |
bufferRow | Number | indicating the zero-indexed buffer index of this line. |
screenRow | Number | indicating the zero-indexed screen index. |
foldable | Boolean | that is true if a fold may be created here. |
softWrapped | Boolean | if this screen row is the soft-wrapped continuation of the same buffer row. |
maxDigits | Number | the maximum number of digits necessary to represent any known screen row. |
onMouseDownoptional | Function | to be called when a mousedown event is received by a line-number element within this type: 'line-number' Gutter. If unspecified, the default behavior is to select the clicked buffer row. |
lineData | Object | an Object containing information about the line that’s being clicked. |
bufferRow | Number | of the originating line element |
screenRow | Number | |
onMouseMoveoptional | Function | to be called when a mousemove event occurs on a line-number element within within this type: 'line-number' Gutter. |
lineData | Object | an Object containing information about the line that’s being clicked. |
bufferRow | Number | of the originating line element |
screenRow | Number |
Returns
Get this editor’s gutters.
Returns
Array<Gutter> — The gutters in display order.
Get the gutter with the given name.
| Argument | Type | Description |
|---|---|---|
name | String | The gutter name to look up. |
Returns
Gutter|null — The named gutter, or null when no matching gutter exists.
Scrolling5
Scroll the editor to reveal the most recently added cursor if it is off-screen.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
modeoptional | String|Number|Array<Number> |
Reveal the most recently added cursor using editor.scrollZone for this editor.
Scrolls the editor to the given buffer position.
| Argument | Type | Description |
|---|---|---|
bufferPosition | Object | An object that represents a buffer position. It can be either an Object ({row, column}), Array ([row, column]), or Point |
optionsoptional | Object | |
modeoptional | String|Number|Array<Number> |
Scrolls the editor to the given screen position.
| Argument | Type | Description |
|---|---|---|
screenPosition | Object | An object that represents a screen position. It can be either an Object ({row, column}), Array ([row, column]), or Point |
optionsoptional | Object | |
modeoptional | String|Number|Array<Number> |
Scrolls the editor to the given screen range.
| Argument | Type | Description |
|---|---|---|
screenRange | Range|Array|Object | A Range or range-compatible Array. |
optionsoptional, default: {} | Object | |
modeoptional | String|Number|Array<Number> | nearest (default) scrolls only far enough to reveal the range with its margins. zone uses the current editor.scrollZone for this editor’s root grammar scope. center fixes the range at the middle. A Number explicitly fixes its position as a percentage of the travel between the vertical scroll margins: 0 rests its start against the top margin and 100 rests its end against the bottom margin. A pair of percentages defines a band in which nothing scrolls. Ordered ([0, 50]), the range lands on the edge it crossed; inverted ([50, 0]), it lands on the opposite edge. [0, 100] is nearest and 50 is center. Explicit numeric modes ignore the configuration. |
reversedoptional | Boolean | Scroll to the start of the range before its end when both are off-screen. (default: true) |
clipoptional | Boolean | Clip the range to the editor’s contents first. (default: true) |
Configuration14
Is auto-indentation enabled for this editor?
Returns
Boolean
Is auto-indentation on paste enabled for this editor?
Returns
Boolean
Does this editor allow scrolling past the last line?
Returns
Boolean
Get the current navigation scroll zone for this editor’s root grammar scope.
Returns
Array<Number> — The two landing percentages, preserving their order.
Multiplier applied to mouse wheel and trackpad scroll distances.
Returns
Number — positive distance multiplier.
Are mouse wheel and scroll command movements animated?
Returns
Boolean
Maximum animation duration in milliseconds for ordinary mouse wheel scrolling. Long movements and existing velocity can shorten the duration. A duration of zero scrolls without a glide.
Returns
Number — non-negative duration in milliseconds.
Maximum animation duration in milliseconds for editor:scroll-up and
editor:scroll-down. Long movements and existing velocity can shorten it.
A duration of zero scrolls without a glide.
Returns
Number — non-negative duration in milliseconds.
Additional distance multiplier applied to wheel scrolling while holding
alt. This gain does not change the ordinary wheel animation duration.
Returns
Number — positive distance multiplier.
Distance scrolled by editor:scroll-up and editor:scroll-down, measured
in editor heights. Seeded from config; the increase/decrease scroll
distance commands adjust it per editor.
Returns
Number — positive distance in editor heights.
How long (in milliseconds) to wait for the editor width to
settle before re-wrapping soft-wrapped lines. 0 re-wraps immediately.
Returns
Number — non-negative Number.
Are line numbers enabled for this editor?
Returns
Boolean
Get the time interval within which text editing operations are grouped together in the editor’s undo history.
Returns
Number — time interval Number in milliseconds.
Get the characters that are not considered part of words, for the purpose of word-based cursor movements.
| Argument | Type | Description |
|---|---|---|
positionoptional | Point|Array<Number>|Object | The buffer position whose language settings are used; defaults to [0, 0]. |
Returns
String — containing the non-word characters.
Rendering3
Get the DOM element displaying this editor, creating it on first access.
Returns
TextEditorElement — The editor’s view element.
Retrieves the greyed out placeholder of a mini editor.
Returns
String|undefined — The placeholder text, or undefined when none is configured.
Set the greyed out placeholder of a mini editor. Placeholder text will be displayed when the editor has no content.
| Argument | Type | Description |
|---|---|---|
placeholderText | String | text that is displayed when the editor has no content. |
Editor Rendering1
Return the buffer ranges needed to render the current viewport, including its overscan. Fold interiors and horizontally virtualized text are omitted. An unmeasured, detached or hidden editor returns an empty array.
Returns
Range[] — Ordered, non-overlapping buffer ranges with exclusive ends.
Language Mode Delegated Methods5
Whether this editor has requested indentation that has not finished yet.
Returns
Boolean
Wait for previously accepted text input and its indentation before acquiring coordinates for a completion or snippet. A newer input, independent edit, cursor movement, grammar change or cancellation invalidates this intent. Waiting does not cancel the edits themselves.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
signaloptional | AbortSignal | Cancels only this wait. |
Returns
Promise<Boolean> — Whether the existing input settled without superseding intent.
Whether an editor-owned indentation correction is being published. Buffer change observers can distinguish it from independent edits and keep input intents whose coordinates will be acquired after the correction.
Returns
Boolean
Plan sparse rows together, then apply their whitespace in one transaction. Call after related text edits so every row belongs to the same revision.
| Argument | Type | Description |
|---|---|---|
rows | Array<Number> | Buffer rows to indent; duplicates are ignored. |
optionsoptional, default: {} | Object | Indentation options. |
groupWithPreviousoptional, default: false | Boolean | Include the correction in the preceding undo entry if its captured revision is still current. |
Returns
Object|undefined|Promise<Object|undefined> — The changed flag and resulting revision, or undefined when obsolete.
Find paragraph ranges for several rows against one syntax revision.
| Argument | Type | Description |
|---|---|---|
rows | Array<Number> | Buffer rows; blank rows produce null entries. |
optionsoptional, default: {} | Object | Optional abort signal. |
Returns
Promise<Array<Range|null>|null> — Null when invalidated.
Essential API
TextEditorElementsrc/text-editor-element.js:11
The custom DOM element displaying a TextEditor. Retrieve it with TextEditor#getElement and access its model with #getModel.
Rendering3
Get a promise that resolves the next time the element’s DOM is updated in any way.
This can be useful when you’ve made a change to the model and need to be sure this change has been flushed to the DOM.
Returns
Promise
Observe changes to logical scroll extents, viewport size, track lengths or row geometry. Ordinary scroll-position changes do not emit this event.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives the changed geometry snapshot. |
Returns
Disposable — Subscription to geometry changes.
Get the width of an x character displayed in this element.
Returns
Number — of pixels.
Model1
Get the text editor model displayed by this element, creating it on first access.
Returns
TextEditor — The displayed editor.
Scrolling3
Scrolls the editor to the top.
Scrolls the editor to the bottom.
Holds the viewport against a block decoration while the user drags its size, instead of against the first visible row.
The measure pass holds the top of the viewport still whenever a block decoration’s height changes, which is right for content that resized itself and wrong for a hand on a resize handle: a decoration whose top sits above the viewport slides out from under the pointer by whatever the drag adds. An item owner that lets the user drag a block decoration’s size opens this for the length of the gesture and disposes it on release.
| Argument | Type | Description |
|---|---|---|
blockDecoration | Decoration | the decoration being interactively sized |
Returns
Disposable — ends the pin
Coordinates4
Converts a buffer position to a pixel position.
Be aware that calling this method with a column that does not translate to column 0 on screen could cause a synchronous DOM update in order to measure the requested horizontal pixel position if it isn’t already cached.
| Argument | Type | Description |
|---|---|---|
bufferPosition | Point|Array<Number>|Object | A Point-like object that represents a buffer position. |
Returns
Object — with two values: top and left, representing the pixel position.
Converts a screen position to a pixel position.
Be aware that calling this method with a non-zero column value could cause a synchronous DOM update in order to measure the requested horizontal pixel position if it isn’t already cached.
| Argument | Type | Description |
|---|---|---|
screenPosition | Point|Array<Number>|Object | A Point-like object that represents a screen position. |
Returns
Object — with two values: top and left, representing the pixel position.
Get the vertical pixel offset before block decorations on a screen row.
The row may be unrendered or the boundary immediately after the last row.
Geometry uses the current measured line and block heights, without forcing
a document-wide layout scan. With viewport, the offset is relative to the
scroll viewport and may be negative; render coordinate origins are internal.
| Argument | Type | Description |
|---|---|---|
row | Number | A non-negative screen-row index or end boundary. |
optionsoptional, default: {} | Object | |
viewportoptional, default: false | Boolean | Subtract the logical vertical scroll offset. |
Returns
Number — Vertical pixel offset before this row’s blocks.
Get the vertical pixel offset of a screen row’s text, after its block decorations. Uses measured vertical geometry without requesting horizontal measurement or rendering.
| Argument | Type | Description |
|---|---|---|
row | Number | A non-negative screen-row index or end boundary. |
optionsoptional, default: {} | Object | |
viewportoptional, default: false | Boolean | Subtract the logical vertical scroll offset. |
Returns
Number — Vertical pixel offset after this row’s blocks.
Decorations1
Invalidate the passed block Decoration’s dimensions, forcing them to be recalculated and the surrounding content to be adjusted on the next animation frame.
| Argument | Type | Description |
|---|---|---|
blockDecoration | Decoration | The block decoration whose dimensions should be recalculated. |
Public API
TextEditorRegistrysrc/text-editor-registry.js:47
The global registry of text editors that participate in the window, available
as lumine.textEditors.
Full description
Workspace owns pane items. This registry additionally reaches editor surfaces embedded in package interfaces, such as search fields, notebook cells, prompts, and previews. Registration is explicit because constructing a detached editor does not by itself make that editor part of the window.
Registering the same editor more than once with the same role creates another lease on one logical registration. Observers see the editor only when the first lease is acquired and see it removed only after the last lease is disposed. Registering one editor under conflicting roles is an error.
Roles#
"document"— a standalone document, normally a workspace pane item."fragment"— an editable part of a composite document, such as a notebook cell."input"— an editor-backed form control, search field, or prompt."viewer"— a rendered or read-only surface that must not become a document-content source.
const editor = lumine.workspace.buildTextEditor({ mini: true })
const registration = lumine.textEditors.add(editor, { role: 'input' })
// Release the lease when the surface goes away. Destroying the editor also
// releases every outstanding lease.
registration.dispose()
Registration1
Register a TextEditor as part of the window.
Repeated registration with the same role acquires an independent lease and
emits no duplicate add event. A conflicting role throws a TypeError.
Destroying the editor releases the registration automatically.
| Argument | Type | Description |
|---|---|---|
editor | TextEditor | The TextEditor to register. |
optionsoptional, default: {} | Object | Registration options. |
roleoptional | "document"|"fragment"|"input"|"viewer" | How the editor participates in the window. |
Returns
Disposable — A lease to dispose when this owner stops exposing the editor.
Event Subscription2
Invoke the callback with every editor registered now and in the future. Repeated leases for one editor do not invoke the callback again.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called with each TextEditor. |
Returns
Disposable — A subscription disposable.
Invoke the callback after the last lease for an editor is released.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called with the removed TextEditor. |
Returns
Disposable — A subscription disposable.
Extended API
ThemeManagersrc/theme-manager.js:94
Handles loading and activating available themes.
An instance of this class is always available as the lumine.themes global.
CSS Variables1
Get the immutable definitions of the editor’s public CSS variables. Each definition specifies its bare name, type, role, owner, scope, default, documentation group and description. Runtime variables have a null default.
Returns
Array<Object> — The public CSS variable definitions.
Event Subscription3
Observe changes to the CSS variable cascade, including theme switches, system accents, user styles and runtime editor typography. Synchronous stylesheet updates are combined into one notification in a microtask.
| Argument | Type | Description |
|---|---|---|
callback | Function | Function called after the cascade changes. |
Returns
Disposable — Dispose to stop observing variable changes.
Invoke callback when style sheet changes associated with
updating the list of active themes have completed.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke callback when a theme pack is registered or removed.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called with the current array of registered theme packs. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Theme Packs5
Register a named light/dark theme pack.
A pack groups the complete theme stacks for both appearance modes.
| Argument | Type | Description |
|---|---|---|
themePackoptional, default: {} | Object | The theme pack. |
name | String | Its user-facing name. |
light | Array<String> | Theme packages for light mode. |
dark | Array<String> | Theme packages for dark mode. |
Returns
Disposable — that removes the pack.
Get registered theme packs sorted by name.
Returns
Array<Object> — registered theme packs sorted by their user-facing names.
Check whether both configured appearance modes match a theme pack.
| Argument | Type | Description |
|---|---|---|
themePack | Object|null | The theme pack to compare. |
Returns
Boolean — whether both configured mode pairs match themePack.
Get the registered theme pack matching both configured appearance modes.
Returns
Object|null — The matching theme pack, or null when none is registered.
Configure both appearance modes from themePack.
| Argument | Type | Description |
|---|---|---|
themePack | Object | A pack containing light and dark theme-name arrays. |
Returns
Boolean — Whether the configured appearance modes changed.
Accessing Loaded Themes2
Get the names of all loaded themes.
Returns
Array<String> — of Strings of all the loaded theme names.
Get all loaded theme packages.
Returns
Array<Package> — of all the loaded themes.
Accessing Active Themes2
Get the names of all active themes.
Returns
Array<String> — of Strings of all the active theme names.
Get all active theme packages.
Returns
Array<Package> — of all the active themes.
Managing Enabled Themes1
Get the enabled theme names from the config.
Returns
Array<String> — array of theme names in the order that they should be activated.
Appearance1
Apply an appearance change that restyles the window without changing which themes are active — a theme package toggling a variant attribute on the document root, say.
Mutating the document directly would leave anything that caches resolved colors — every package that paints to a canvas — showing the old palette until something unrelated made it redraw. This runs the mutation inside the same cross-fade a theme switch uses and notifies those consumers from within it, so they repaint as part of the same transition.
| Argument | Type | Description |
|---|---|---|
mutate | Function | applying the change to the document. |
Returns
Promise<void> — that resolves once the change has been applied.
Essential API
TooltipManagersrc/tooltip-manager.js:71
Associates tooltips with HTML elements.
Full description
You can get the TooltipManager via lumine.tooltips.
Examples#
The essence of displaying a tooltip
// display it
const disposable = lumine.tooltips.add(div, {title: 'This is a tooltip'})
// remove it
disposable.dispose()
In practice there are usually multiple tooltips. So we add them to a CompositeDisposable
const {CompositeDisposable} = require('lumine')
const subscriptions = new CompositeDisposable()
const div1 = document.createElement('div')
const div2 = document.createElement('div')
subscriptions.add(lumine.tooltips.add(div1, {title: 'This is a tooltip'}))
subscriptions.add(lumine.tooltips.add(div2, {title: 'Another tooltip'}))
// remove them all
subscriptions.dispose()
You can display a key binding in the tooltip as well with the
keyBindingCommand option.
disposable = lumine.tooltips.add(this.caseOptionButton, {
title: 'Match Case',
keyBindingCommand: 'search-panel:toggle-case-option',
keyBindingTarget: this.findEditor.element
})
To display several tooltip entries together, use addComposite.
disposable = lumine.tooltips.addComposite(this.modeIndicator, [
{title: 'Column selection'},
{
title: 'Toggle sticky mode',
keyBindingExtra: 'LMB',
keyBindingCommand: 'column-selection:sticky'
},
{
title: 'Toggle picker mode',
keyBindingExtra: 'RMB',
keyBindingCommand: 'column-selection:picker'
}
])
Methods3
Add a tooltip to the given element.
| Argument | Type | Description |
|---|---|---|
target | HTMLElement | An HTMLElement |
optionsoptional | Object | An object with one or more of the following options: |
titleoptional | String|Function | A String or Function to use for the text in the tip. If a function is passed, this will be set to the target element. This option is mutually exclusive with the item option. |
htmloptional | Boolean | A Boolean affecting the interpretation of the title option. If true (the default), the title string will be interpreted as HTML. Otherwise it will be interpreted as plain text. |
itemoptional | Object|Element | A view (object with an .element property) or a DOM element containing custom content for the tooltip. This option is mutually exclusive with the title option. |
classoptional | String | A String with a class to apply to the tooltip element to enable custom styling. |
placementoptional | String|Function | A String or Function returning a string to indicate the position of the tooltip relative to element. Can be 'top', 'bottom', 'left', 'right', or 'auto'. When 'auto' is specified, it will dynamically reorient the tooltip. For example, if placement is 'auto left', the tooltip will display to the left when possible, otherwise it will display right. When a function is used to determine the placement, it is called with the tooltip DOM node as its first argument and the triggering element DOM node as its second. The this context is set to the tooltip instance. |
triggeroptional | String | A String indicating how the tooltip should be displayed. Use hover (default), click, focus, or manual. A manual tooltip appears immediately; a click hides it and disposal removes it. |
delayoptional | Object|Number | An object specifying the show and hide delay in milliseconds. Defaults to {show: 1000, hide: 100} if the trigger is hover and otherwise defaults to 0 for both values. |
keyBindingCommandoptional | String | A String containing a command name. If you specify this option and a key binding exists that matches the command, it will be appended to the title or rendered alone if no title is specified. |
keyBindingTargetoptional | HTMLElement|Function | An HTMLElement on which to look up the key binding, or a function evaluated when the tooltip opens with the triggering element as this and its first argument. An explicit null or a function returning null suppresses a scoped binding. If this option is not supplied, the first of all matching key bindings for the given command will be rendered. |
keyBindingExtraoptional | String | A String rendered as an additional key binding before the command’s resolved binding. Use this for interactions that are not represented in the keymap, such as LMB or RMB. The value accepts + separators and cmdorctrl, which is resolved for the current platform (for example, cmdorctrl+RMB). |
Returns
Disposable — on which .dispose() can be called to remove the tooltip.
Add several tooltip entries that are displayed together.
| Argument | Type | Description |
|---|---|---|
target | HTMLElement | An HTMLElement |
entries | Array<Object> | An Array of option objects accepted by #add. Entries are rendered on separate lines. Display options, such as placement and delay, are taken from the first entry. |
Returns
Disposable — on which .dispose() can be called to remove the composite tooltip.
Find the tooltips that have been applied to the given element.
| Argument | Type | Description |
|---|---|---|
target | HTMLElement | The HTMLElement to find tooltips on. |
Returns
Array<Object> — of Tooltip objects that match the target.
Extended API
TreeSitterGrammarsrc/tree-sitter-grammar.js:51
This class holds an instance of a Tree-sitter grammar.
Grammar Details1
Retrieve all known comment delimiters for this grammar.
Some grammars may have different delimiters for different parts of a file
(such as JSX within JavaScript). In these cases, you might want to call
TextEditor#getCommentDelimitersForBufferPosition with a {Point} in the
buffer.
line: If present, aStringrepresenting a line comment delimiter. (Ifundefined, there is no known line comment delimiter for the given buffer position.)block: If present, a two-itemArraycontainingStringsrepresenting the starting and ending block comment delimiters. (Ifundefined, there are no known block comment delimiters for the given buffer position.)
Returns
Object — with the following properties:
Language Loading2
Retrieves the Tree-sitter Language instance associated with
this grammar if it has already been loaded.
Language instances cannot be retrieved synchronously, so this will return
undefined if the instance has not yet been loaded. In that case, going
async will be unavoidable, and you’ll need to call #getLanguage.
Returns
Language|undefined — The loaded Tree-sitter language, or undefined before loading completes.
Retrieves the Tree-sitter language instance associated with this grammar.
Returns
Promise<Language> — Resolves to the loaded Tree-sitter language; rejects when loading fails or the grammar is deactivated.
Queries3
Given a kind of query, retrieves a Tree-sitter Query object
in async fashion.
| Argument | Type | Description |
|---|---|---|
queryType | String | A String describing the query type: typically one of highlightsQuery, injectionsQuery, foldsQuery, tagsQuery, or indentsQuery, but could be any other custom type. |
Returns
Promise<Query> — Resolves to a shared grammar-owned query; rejects on loading, compilation, or deactivation errors.
Creates an arbitrary query from this grammar. Package authors and end users can use queries for whatever purposes they like.
| Argument | Type | Description |
|---|---|---|
queryContents | String | A String representing the entire contents of a query file. Can contain any number of queries. |
Returns
Promise<Query> — A query whose parser resources follow its JavaScript lifetime.
Creates an arbitrary query from this grammar. Package authors and end users can use queries for whatever purposes they like.
Synchronous; use only when you can be certain that the tree-sitter language has already loaded.
| Argument | Type | Description |
|---|---|---|
queryContents | String | A String representing the entire contents of a query file. Can contain any number of queries. |
Returns
Query — A query whose parser resources follow its JavaScript lifetime.
Throws
Error — When the language has not been loaded, or the query cannot be compiled.
Event Subscription5
Calls callback when any of this grammar’s queries change.
A grammar’s queries typically will not change after initial load. When they do, it may mean:
- The user is editing query files in dev mode; Lumine will automatically reload queries in dev mode after changes.
- An installed package is altering a query file via an API like
setQueryForTest.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
data | Object | |
filePath | String | The query file’s path, or an empty string for an in-memory query change. |
queryType | String | The type of query file, as denoted by its configuration key in the grammar file. Usually one of highlightsQuery, indentsQuery, foldsQuery, or tagsQuery. |
Returns
Disposable — Dispose to unsubscribe.
Calls callback when any of this grammar’s queries change.
Alias of #onDidChangeQuery.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
data | Object | Query-change details, as in #onDidChangeQuery. |
Returns
Disposable — Dispose to unsubscribe.
Calls callback when this grammar first loads its query files.
Since a grammar may not load immediately on startup, this method makes it easier to hook into the query life cycle in order to modify or augment a grammar’s default queries.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
grammar | TreeSitterGrammar | The grammar whose query files finished loading. |
Returns
Disposable — Dispose to unsubscribe.
Calls callback when an injection point is added to this
grammar.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
injectionPoint | Object | The injection-point options. |
Returns
Disposable — Dispose to unsubscribe.
Calls callback when an injection point is removed from this
grammar.
| Argument | Type | Description |
|---|---|---|
callback | Function | |
injectionPoint | Object | The injection-point options. |
Returns
Disposable — Dispose to unsubscribe.
Language Injections1
Define a set of rules for when this grammar should delegate to a different grammar for certain regions of a buffer. Examples:
- embedding one language inside another (e.g., JavaScript in HTML)
- tokenizing certain structures with greater detail (e.g., regular expressions in most languages)
- highlighting non-standard augmentations to a language (e.g., JSDoc comments in JavaScript)
You should typically not call this method directly; instead, call GrammarRegistry#addInjectionPoint and pass a given grammar’s root language scope as the first argument.
NOTE: Packages will call #addInjectionPoint with a given scope name, and that call will be delegated to any Tree-sitter grammar matching that scope name.
| Argument | Type | Description |
|---|---|---|
injectionPoint | Object | The options for the injection point: |
type | String | A String describing the type of node to inject into. |
language | String|Function | A fixed language name declared by the target grammar in injectionNames, or a function returning one. Prefer a string for a fixed language so operations can skip irrelevant injections before scanning. Matching ignores surrounding whitespace and letter case. A function receives one parameter: |
node | SyntaxNode | A Tree-sitter node. |
content | Function | A Function that should return the node (or nodes) that will actually be injected into. Usually this will be the same node that was given, but could also be a specific child or descendant of that node. |
includeChildrenoptional, default: false | Boolean | controlling whether the injection range should include the ranges of the content node’s children. Defaults to false, meaning that the range of each of this node’s children will be “subtracted” from the injection range, and the remainder will be parsed as if those ranges of the buffer do not exist. |
includeAdjacentWhitespaceoptional, default: false | Boolean | controlling whether the injection range should include whitespace that occurs between content nodes. Defaults to false. When true, if two injection ranges are separated from one another by only whitespace, that whitespace will be added to the injection range, and the ranges will be consolidated. |
newlinesBetweenoptional, default: false | Boolean | controlling whether the injection range should include any newline characters that may exist in between injection ranges. Defaults to false. Grammars like ERB and EJS need this so that they do not interpret two different embedded code sections on different lines as occurring on the same line. |
combinedoptional, default: false | Boolean|Function | Share child language layers between matching owner nodes per injection point and resolved language name. Defaults to false. A function is called synchronously with the owner node after its language and content resolve; returning false keeps that owner in an independent layer. Owner and content ranges are tracked individually, so local edits rediscover only affected owners. By default the owners form one shared document. Independent contexts such as Markdown inline blocks should keep separate layers. |
combinedMaxMembersoptional | Number | An optional positive safe integer limiting the number of owner nodes in each combined child layer. Omit it to keep one unbounded combined document. Use a limit only when splitting the combined document preserves the meaning of its independent owners. An owner returning multiple content nodes counts as one member and is never split across layers. |
contentEditPolicyoptional | String | A named policy from the parent grammar’s treeSitter.contentEditPolicies. Every callback injection capable of indentation must opt in before cached ownership can bypass syntax preparation; all its policies must approve the edit. |
coverShallowerScopesoptional, default: false | Boolean | controlling whether the injection should prevent the parent grammar (and any of its ancestors) from applying scope boundaries within its injection range(s). Defaults to false. |
languageScopeoptional | String|null|Function | A value that determines what scope, if any, is added to the injection as its “base” scope name. Can be a String, null, or a Function that returns either of these values. The base language scope that should be used by this injection. Defaults to the grammar’s own scopeName property. Set this to a string to override the default scope name, or null to omit a base scope name altogether. Set this to a function if the scope name to be applied varies based on the grammar; the function will be called with a grammar instance as its only argument. |
excludeChildrenLinesoptional, default: false | Boolean | When children are excluded, subtract their complete physical rows from the injection range. |
node | SyntaxNode | The matching syntax node whose content is requested. |
Returns
void
Extended API
URIHandlerRegistrysrc/uri-handler-registry.js:71
Associates listener functions with URIs from outside the application.
Full description
An instance of this class is always available as the lumine.uriHandlers
global.
The global URI handler registry maps URIs to listener functions. URIs are mapped based on the hostname of the URI; the format is lumine://package/command?args. The “core” package name is reserved for URIs handled by Lumine Core (it is not possible to register a package with the name “core”).
Because URI handling can be triggered from outside the application (e.g. from the user’s browser), package authors should take great care to ensure that malicious activities cannot be performed by an attacker. A good rule to follow is that URI handlers should not take action on behalf of the user. For example, clicking a link to open a pane item that prompts the user to install a package is okay; automatically installing the package right away is not.
Packages can register their desire to handle URIs via a special key in their
package.json called “uriHandler”. The value of this key should be an object
that contains, at minimum, a key named “method”. This is the name of the method
on your package object that Lumine will call when it receives a URI your package
is responsible for handling. It will pass the parsed URI as the first argument (an
object with the same shape as the output of Node’s legacy url.parse(uri, true),
including a query object) and the raw URI string as the second argument.
URI handlers are registered by the package’s synchronous bootstrap. The package is therefore already active when a URI is delivered; expensive handler work may still be loaded lazily by the package itself.
If your package specifies a deprecated urlMain property, you cannot register URI handlers
via the uriHandler key.
Example#
Here is a sample package that will be activated and have its handleURI method called
when a URI beginning with lumine://my-package is triggered:
package.json:
{
"name": "my-package",
"main": "./lib/my-package.js",
"uriHandler": { "method": "handleURI" }
}
lib/my-package.js
module.exports = {
activate: function() {
// code to activate your package
},
handleURI(parsedUri, rawUri) {
// parse and handle uri
}
}
Essential API
ViewRegistrysrc/view-registry.js:33
ViewRegistry handles the association between model and view
types in Lumine. We call this association a View Provider. As in, for a given
model, this class can provide a view via #getView, as long as the
model/view association was registered via #addViewProvider
Full description
If you’re adding your own kind of pane item, a good strategy for all but the simplest items is to separate the model and the view. The model handles application logic and is the primary point of API interaction. The view just handles presentation.
Note: Models can be any object, but must implement a getTitle() function
if they are to be displayed in a Pane
View providers inform the workspace how your model objects should be presented in the DOM. A view provider must always return a DOM node, which makes HTML 5 custom elements an ideal tool for implementing views in Lumine.
You can access the ViewRegistry object via lumine.views.
Window Participants1
Register a presentation component that needs state preparation across documents. Disposing its registration allows the same DOM root to be registered again.
| Argument | Type | Description |
|---|---|---|
root | Element | The component’s DOM root within a pane item. |
participant | Object | prepareWindowChange, didAttachToWindow, didChangeWindow and cancelWindowChange callbacks. |
Returns
Disposable — Removes this component’s lifecycle participation.
Views2
Register a factory that creates DOM views for model objects.
Examples
class Message {
constructor(text) { this.text = text; }
}
const subscription = lumine.views.addViewProvider(Message, (model) => {
const element = document.createElement('div');
element.textContent = model.text;
return element;
});
const view = lumine.views.getView(new Message('Hello'));
| Argument | Type | Description |
|---|---|---|
modelConstructoroptional | Function | Constructor Function for your model. If a constructor is given, the createView function will only be used for model objects inheriting from that constructor. Otherwise, it will be called for any object. |
createView | Function | Factory Function that is passed an instance of your model and must return a DOM element or undefined. If it returns undefined, then the registry will continue to search for other view providers. |
Returns
Disposable — Dispose to remove the added provider.
Get the view associated with an object in the workspace.
If you’re just using the workspace, you shouldn’t need to access the view layer, but view layer access may be necessary if you want to perform DOM manipulation that isn’t supported via the model API.
View Resolution Algorithm
The view associated with the object is resolved using the following sequence
- Is the object an instance of
HTMLElement? If true, return the object. - Does the object have a method named
getElementthat returns an instance ofHTMLElement? If true, return that value. - Does the object have a property named
elementwith a value which is an instance ofHTMLElement? If true, return the property value. - Is the object a jQuery object, indicated by the presence of a
jqueryproperty? If true, return the root DOM element (i.e.object[0]). - Has a view provider been registered for the object? If true, use the provider to create a view associated with the object, and return the view.
If no associated view is returned by the sequence an error is thrown.
| Argument | Type | Description |
|---|---|---|
object | Object|Element|null|undefined | A model or DOM element whose view is requested. |
Returns
Element|undefined — The DOM element, or undefined for a null or undefined input.
Public API
WindowContributionRegistrysrc/window-contribution-registry.js:10
Owns window-local instances of service contributions. A registration targets the main window by default; all-window registrations include future windows.
Registering Contributions2
Register a factory for independent presentation instances.
| Argument | Type | Description |
|---|---|---|
options | Object | windows, create and service-specific mount options. |
windowsoptional, default: "main" | String | main (default) or all. |
create | Function | Returns an independent {element, dispose()} presentation instance. |
context | Object | Window-local factory context. |
window | EditorWindow | The presentation being mounted. |
document | Document | Its physical DOM document. |
workspace | Workspace | The shared workspace. |
editorContainer | PaneContainer | The window-local document container. |
Returns
Disposable — Removes all instances and future mounts.
Own the lifetime of a service client’s window-local controller.
| Argument | Type | Description |
|---|---|---|
options | Object | windows (main by default) and create(context). |
create | Function | Returns a Disposable owning that window’s UI. |
windowsoptional, default: "main" | String | Use main for the main window only, or all for current and future presentations. |
context | Object | The same window-local context passed to add factories. |
Returns
Disposable — Releases current clients and prevents future creation.
Lifecycle1
Release the service and all its current and future presentation instances.
Public API
WindowServicesrc/window-service.js:13
Operations on the Lumine window hosting the current renderer.
BrowserWindow objects never cross the process boundary. State is returned as plain objects and every operation which reaches the main process is async.
Window Information1
Get the native identity of the current window.
Returns
Number — stable numeric id of the current Lumine window.
Event Subscription8
Subscribe before the current editor window is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called before this window is destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Subscribe to named events broadcast by other Lumine windows.
| Argument | Type | Description |
|---|---|---|
eventName | String | The broadcast event name. |
callback | Function | Receives the broadcast arguments from another window. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke callback after entering full-screen mode.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called when the documented native window event occurs. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke callback after leaving full-screen mode.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called when the documented native window event occurs. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke callback after the window is maximized.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called when the documented native window event occurs. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke callback after a maximized window is restored.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called when the documented native window event occurs. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke callback when the window gains focus.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called when the documented native window event occurs. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke callback when the window loses focus.
| Argument | Type | Description |
|---|---|---|
callback | Function | Called when the documented native window event occurs. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Startup4
Wait until the current editor window has finished loading.
Returns
Promise<Number> — resolving to the load time in milliseconds.
Get the paths supplied when the current window was opened.
Returns
Array<String> — paths supplied when the current window was opened.
Get the time taken to load the current window.
Returns
Number|null — The completed window load time in milliseconds, or null before loading completes.
Get startup timing markers for the current window.
Returns
Array<Object> — Startup markers with label and elapsed time in milliseconds.
Native Presentation2
Set the filename represented by the native window.
| Argument | Type | Description |
|---|---|---|
filename | String | The current path, or an empty string. |
Returns
Promise<void> — Completes after the native property is set.
Move native macOS sheets below HTML window chrome.
This is a no-op on other platforms.
| Argument | Type | Description |
|---|---|---|
offsetY | Number | A non-negative integer number of pixels. |
Returns
Promise<void> — that resolves when the request is applied.
Window Modes5
Determine whether the current window is in development mode.
Returns
Boolean
Determine whether the current window is in safe mode.
Returns
Boolean
Determine whether the current window is running specs.
Returns
Boolean
Determine whether the current window is running headlessly.
Returns
Boolean
Determine whether this window has finished its final session save and is releasing its resources for closing or reloading. Automatic saves must stop once this phase starts.
Returns
Boolean — Whether the window is unloading.
Window State4
Get a snapshot of the current window’s native state.
Returns
Promise<Object> — A serializable state snapshot with id, position, size, maximized, fullScreen, and visible fields.
Determine whether the current window is maximized.
Returns
Promise<Boolean> — resolving to a Boolean.
Determine whether the current window is full screen.
Returns
Promise<Boolean> — resolving to a Boolean.
Determine whether the current window is visible.
Returns
Promise<Boolean> — resolving to a Boolean.
Window Geometry6
Get the current native window size.
Returns
Promise<Object> — The current native window size as {width, height}.
Set the native window size.
| Argument | Type | Description |
|---|---|---|
width | Number | A positive integer size in pixels. |
height | Number | A positive integer size in pixels. |
Returns
Promise<void> — that resolves when the request is applied.
Get the current screen position.
Returns
Promise<Object> — The current screen position as {x, y}.
Set the current screen position.
| Argument | Type | Description |
|---|---|---|
x | Number | An integer screen coordinate in pixels. |
y | Number | An integer screen coordinate in pixels. |
Returns
Promise<void> — that resolves when the request is applied.
Center the current window on its display.
Returns
Promise<void> — that resolves when the request is applied.
Get the primary display’s available work-area size.
Returns
Promise<Object> — The primary display’s available work-area size as {width, height}.
Window Management10
Focus the current window.
Returns
Promise<void> — that resolves when the request is applied.
Show the current window and restore its focus policy.
Returns
Promise<void> — that resolves when the request is applied.
Hide the current window.
Returns
Promise<void> — that resolves when the request is applied.
Close the current window.
Returns
Promise<void> — that resolves when the close request is accepted.
Reload the current window.
Returns
Promise<void> — that resolves after the reloaded renderer reports ready.
Minimize the current window.
Returns
Promise<void> — that resolves when the request is applied.
Maximize the current window.
Returns
Promise<void> — that resolves when the request is applied.
Restore a maximized window.
Returns
Promise<void> — that resolves when the request is applied.
Enter or leave full-screen mode.
| Argument | Type | Description |
|---|---|---|
fullScreenoptional, default: false | Boolean | A Boolean indicating the desired state. |
Returns
Promise<void> — that resolves when the request is applied.
Toggle full-screen mode.
Returns
Promise<void> — that resolves when the request is applied.
Dialogs4
Ask the user to select one or more folders.
Returns
Promise<Array<String>|null> — resolving to an Array of paths, or null on cancellation.
Show an open dialog owned by the current window.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Serializable Electron open-dialog options. |
Returns
Promise<Object> — resolving to Electron’s serializable open-dialog result.
Show a save dialog owned by the current window.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Serializable Electron save-dialog options. |
Returns
Promise<Object> — resolving to Electron’s serializable save-dialog result.
Show a non-blocking confirmation dialog owned by the current window.
| Argument | Type | Description |
|---|---|---|
options | Object | Serializable message-box options. |
buttons | Array<String> | Button labels in result-index order. |
Returns
Promise<Number> — resolving to the selected button index.
Downloads1
Start a download in the current window.
| Argument | Type | Description |
|---|---|---|
url | String | The String URL to download. |
Returns
Promise<void> — that resolves when the download is started.
Developer Tools4
Open the current window’s developer tools.
Returns
Promise<void> — that resolves when the request is applied.
Close the current window’s developer tools.
Returns
Promise<void> — that resolves when the request is applied.
Toggle the current window’s developer tools.
Returns
Promise<void> — that resolves when the request is applied.
Evaluate JavaScript in the current window’s developer tools.
| Argument | Type | Description |
|---|---|---|
code | String | JavaScript source to run if the developer tools are open. |
Returns
Promise<void> — Resolves after execution, or immediately if the developer tools are closed.
Window Messaging1
Send a serializable event to every other registered Lumine window.
| Argument | Type | Description |
|---|---|---|
eventName | String | A non-empty String event name. |
...args | ...* | Structured-cloneable values delivered to subscribers. |
Returns
Promise<void> — that resolves after the event is sent.
Essential API
Workspacesrc/workspace.js:375
Manages the shared workspace and its presentation windows.
An instance of this class is available via the lumine.workspace global.
Full description
Interact with this object to open files, be notified of current and future editors, and manipulate panes. To add panels, use Workspace#addTopPanel and friends.
Workspace Items#
The term “item” refers to anything that can be displayed in a pane within the workspace, either in the WorkspaceCenter or in one of the three Docks. The workspace expects items to conform to the following interface:
Required Methods#
getTitle()#
Returns a String containing the title of the item to display on its
associated tab.
Optional Methods#
copy({signal})#
Returns a fresh live item or a Promise for one, with an independent detached
view root. If omitted, copy and split-copy operations silently resolve to
null without changing panes, focus or preview state. Focus and move,
including split-move, remain available. Views may share
their underlying document, but own their subscriptions, selection and viewport.
Honor the AbortSignal before publishing a copy and release abandoned resources.
Serialization and URI openers are not substitutes for this copy contract.
Copy factories capture document and view state before awaiting initialization.
Retargeting items emit onDidChangeURI after every document publication, even
if its URI returns to an earlier value. Moving and copying promote previews
only after committing and invoke terminatePendingState() to cancel pending reuse.
canCopy()#
Returns a Boolean to restrict an item’s copy capability. Returning false
silently skips copy and split-copy without notifications or changes to panes,
focus or preview state. If omitted, a callable copy() method enables copying.
Returning true does not enable copying when the item has no copy() method.
getSingletonKey()#
Returns a namespaced non-empty String to allow one item per logical resource
in this workspace. A constant key identifies a workspace tool; a resource key
permits separate result sets. Omit it or return null when uniqueness is not
required. Resource uniqueness is independent of copy capability.
Changing a singleton key emits onDidChangeSingletonKey, or onDidChangeURI
when the key follows the URI. Reopening a key activates its existing item.
getPaneItemRevision()#
Returns a monotonic document revision so asynchronous copies detect document
replacement with an unchanged URI. Omit it when the item does not retarget its
document, or use onDidChangeURI when its URI always changes with the document.
Presentation window lifecycle#
didAttachToWindow({window, document}) synchronously binds presentation-only
listeners after first mounting or DOM adoption. Use that document and its
defaultView for UI, while retaining workspace-owned models and resources.
prepareWindowChange({sourceWindow, targetWindow}) may asynchronously capture
state that DOM adoption cannot retain, such as an iframe’s browsing context.
Its returned state is passed to didChangeWindow({...context, state}) after
movement. Rollback invokes that method with reversed windows and
rollback: true; a preparation cancelled before movement invokes
cancelWindowChange({...context, state}). A returned state may implement
dispose() to release temporary resources after commit or rollback.
These methods preserve the live document, terminal or kernel; they do not
reopen an item through its URI. Layout mutations in participating windows
remain locked while their presentation operation is pending.
getPaneItemDocument() may return a shared document object used by independent
views. Close batches confirm that document once, passing lastView to
shouldPromptToSave. Text editors use their buffer as the document identity.
getElement()#
If your item already is a DOM element, you do not need to implement this method. Otherwise it should return the element you want to display to represent this item.
destroy()#
Destroys the item. This will be called when the item is removed from its parent pane.
onDidDestroy(callback)#
Called by the workspace so it can be notified when the item is destroyed.
Must return a Disposable.
serialize()#
Serialize the state of the item. Must return an object that can be passed to
JSON.stringify. The state should include a field called deserializer,
which names a deserializer declared in your package.json. This method is
invoked on items when serializing the workspace so they can be restored to
the same location later.
getURI()#
Returns the URI associated with the item.
onDidChangeURI(callback)#
Notifies the workspace when the item begins representing a different URI.
Emit after committing the new document, and return a Disposable.
The workspace publishes Workspace#onDidChangePaneItemURI for consumers
whose context depends on the document rather than the item identity.
getLongTitle()#
Returns a String containing a longer version of the title to display in
places like the window title or on tabs their short titles are ambiguous.
onDidChangeTitle(callback)#
Called by the workspace so it can be notified when the item’s title changes.
Must return a Disposable.
getIconName()#
Return a String with the semantic name of an icon. The icon registry
resolves that name to a descriptor, so an icon provider may render it as
classes, an image, SVG, or a letter.
onDidChangeIcon(callback)#
Called by the icon binding so it can be notified when the item’s icon
changes. Must return a Disposable.
getDefaultLocation()#
Tells the workspace where your item should be opened in absence of a user override. Items can appear in the center or in a dock on the left, right, or bottom of the workspace.
Returns a String with one of the following values: 'center', 'left',
'right', 'bottom'. If this method is not defined, 'center' is the
default.
getAllowedLocations()#
Tells the workspace where this item can be moved. Returns an Array of one
or more of the following values: 'center', 'left', 'right', or
'bottom'. If this method is not defined, the item is allowed only in the
location returned by getDefaultLocation(), or in 'center' when that
method is not defined either.
getDefaultVisibility()#
Declares the initial visibility of a dock item registered with
Workspace#addDefaultDockItem. Returns "visible" to show it in a new
layout, or "project-or-empty" to show it when opening a project (including
a project with files) or starting without requested documents. Opening only
files does not show a "project-or-empty" item. An absent method, undefined, false
or "manual" leaves opening to the user.
Saved dock layouts take precedence, including hidden docks and closed items. Defaults never take focus or replace an existing dock item. They run once during initial startup, not after later file openings or package activation. Explicit Workspace#open calls do not consult this method.
isPersistentDockItem()#
Tells the workspace that this item should survive restoring a saved workspace layout into the current window. Persistent items are carried over to the restored layout instead of being destroyed along with the previous one. Unlike permanent dock items, the user can still close them at any time.
isPermanentDockItem()#
Tells the workspace whether or not this item can be closed by the user by
clicking an x on its tab. Use of this feature is discouraged unless there’s
a very good reason not to allow users to close your item. Items can be made
permanent only when they are contained in docks. Center pane items can
always be removed. Note that it is currently still possible to close dock
items via the Close Pane option in the context menu and via Lumine APIs, so
you should still be prepared to handle your dock items being destroyed by the
user even if you implement this method.
save()#
Saves the item.
saveAs(path)#
Saves the item to the specified path.
getPath()#
Returns the local path associated with this item. This is only used to set the initial location of the “save as” dialog.
getFileState()#
Returns one mutually exclusive state string: "unmodified" when the document
matches its saved base, "modified" when it has local changes, "conflicted"
when it has diverged from its backing file, or "removed" when its backing
file no longer exists.
onDidChangeFileState(callback)#
Called by the workspace so it can be notified when the item’s file state
changes. The callback receives the new state. Must return a Disposable.
getPreferredHeight()#
If this item is displayed in the bottom Dock, called by the workspace when initially displaying the dock to set its height. Once the dock has been resized by the user, their height will override this value.
Returns a Number.
getPreferredWidth()#
If this item is displayed in the left or right Dock, called by the workspace when initially displaying the dock to set its width. Once the dock has been resized by the user, their width will override this value.
Returns a Number.
onDidTerminatePendingState(callback)#
If the workspace is configured to use pending pane items, the workspace
will subscribe to this method to terminate the pending state of the item.
Must return a Disposable.
shouldPromptToSave()#
This method indicates whether Lumine should prompt the user to save this item when the user closes or reloads the window. Returns a boolean.
Windows9
Get this workspace’s main presentation window.
Returns
EditorWindow|null — The main window, or null before window initialization.
Get all presentation windows belonging to this workspace.
Returns
Array<EditorWindow> — The current windows.
Create an additional editor window sharing this workspace’s documents and packages. New calls are refused while the workspace windows prepare to unload.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | Optional native bounds and visibility. |
Returns
Promise<EditorWindow> — The ready presentation window.
Get the presentation window whose document currently has focus.
Returns
EditorWindow|null — The focused window, or null when the workspace lacks focus.
Get the presentation containing a DOM element, including embedded frames.
| Argument | Type | Description |
|---|---|---|
element | Element | An element belonging to a workspace presentation. |
Returns
EditorWindow|null — The owning presentation.
Close an auxiliary presentation after its document panes accept closing. For the main window, forward the native close request; its save prompts run through the native window lifecycle.
| Argument | Type | Description |
|---|---|---|
editorWindow | EditorWindow | A window belonging to this workspace. |
Returns
Promise<Boolean> — Whether the auxiliary window closed or the main-window close request was sent. False means the window was unavailable, busy, or refused closing.
Present an existing document pane in a new window without reopening its items.
| Argument | Type | Description |
|---|---|---|
pane | Pane | A document pane belonging to this workspace. |
Returns
Promise<EditorWindow> — The new presentation.
Move one exact document tab into a new editor window sharing this workspace.
| Argument | Type | Description |
|---|---|---|
item | Object | A live center pane item. |
Returns
Promise<EditorWindow> — The additional presentation.
Reattach an additional window’s complete pane layout to the main window.
| Argument | Type | Description |
|---|---|---|
editorWindow | EditorWindow | An additional window of this workspace. |
Returns
Promise<EditorWindow> — The main presentation after reattachment.
Event Subscription25
Observe current and future presentation windows of this workspace.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives each EditorWindow once. |
Returns
Disposable — Removes the observation.
Invoke the given callback with all current and future text editors in the workspace.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with current and future text editors. |
editor | TextEditor | A TextEditor that is present in #getTextEditors at the time of subscription or that is added at some later time. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with all current and future panes items in the workspace.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with current and future pane items. |
item | * | An item that is present in #getPaneItems at the time of subscription or that is added at some later time. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the callback when an existing pane item changes its document URI. The item and pane identities are unchanged. This includes preview reuse and navigation performed by the item itself.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives {item, pane, oldURI, newURI}. |
Returns
Disposable — Subscription to the URI changes.
Invoke the given callback when the active pane item changes.
Because observers are invoked synchronously, it’s important not to perform any expensive operations via this method. Consider #onDidStopChangingActivePaneItem to delay operations until after changes stop occurring.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active pane item changes. |
item | * | The active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the active pane item stops changing.
Observers are called asynchronously 100ms after the last active pane item change. Handling changes here rather than in the synchronous #onDidChangeActivePaneItem prevents unneeded work if the user is quickly changing or closing tabs and ensures critical UI feedback, like changing the highlighted tab, gets priority over work that can be done asynchronously.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active pane item stops changing. |
item | * | The active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a text editor becomes the active text editor and when there is no longer an active text editor.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active text editor changes. |
editor | TextEditor|undefined | The active TextEditor or undefined if there is no longer an active text editor. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with the current active pane item and with all future active pane items in the workspace.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active pane item changes. |
item | * | The current active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with the current active text editor (if any), with all future active text editors, and when there is no longer an active text editor.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active text editor changes. |
editor | TextEditor|undefined | The active TextEditor or undefined if there is not an active text editor. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the editor holding the active item’s file content changes. See #getActiveFileTextEditor.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the resolved editor changes. |
editor | TextEditor|undefined | The resolved TextEditor or undefined. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with the current and all future editors holding the active item’s file content. See #getActiveFileTextEditor.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the resolved editor changes. |
editor | TextEditor|undefined | The resolved TextEditor or undefined. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the editor being edited inside the active item changes. See #getActiveEmbeddedTextEditor.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the resolved editor changes. |
editor | TextEditor|undefined | The resolved TextEditor or undefined. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with the current and all future editors being edited inside the active item. See #getActiveEmbeddedTextEditor.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the resolved editor changes. |
editor | TextEditor|undefined | The resolved TextEditor or undefined. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback whenever an item is opened. Unlike #onDidAddPaneItem, observers will be notified for items that are already present in the workspace when they are reopened.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called whenever an item is opened. |
event | Object | with the following keys: |
uri | String | representing the opened URI. Could be undefined. |
item | * | The opened item. |
pane | Pane | The pane in which the item was opened. |
index | Number | The index of the opened item on its pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a pane is added to the workspace.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when panes are added. |
event | Object | with the following keys: |
pane | Pane | The added pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback before a pane is destroyed in the workspace.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called before panes are destroyed. |
event | Object | with the following keys: |
pane | Pane | The pane to be destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a pane is destroyed in the workspace.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when panes are destroyed. |
event | Object | with the following keys: |
pane | Pane | The destroyed pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with all current and future panes in the workspace.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with current and future panes. |
pane | Pane |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the active pane changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active pane changes. |
pane | Pane | A Pane that is the current return value of #getActivePane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with the current active pane and when the active pane changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with the current and future active panes. |
pane | Pane | A Pane that is the current return value of #getActivePane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a pane item is added to the workspace.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when pane items are added. |
event | Object | with the following keys: |
item | * | The added pane item. |
pane | Pane | containing the added item. |
index | Number | indicating the index of the added item in its pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a pane item is about to be destroyed, before the user is prompted to save it.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called before pane items are destroyed. If this function returns a Promise, then the item will not be destroyed until the promise resolves. |
event | Object | with the following keys: |
item | * | The item to be destroyed. |
pane | Pane | containing the item to be destroyed. |
index | Number | indicating the index of the item to be destroyed in its pane. |
Returns
Disposable — on which .dispose can be called to unsubscribe.
Invoke the given callback when a pane item is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when pane items are destroyed. |
event | Object | with the following keys: |
item | * | The destroyed item. |
pane | Pane | containing the destroyed item. |
index | Number | indicating the index of the destroyed item in its pane. |
Returns
Disposable — on which .dispose can be called to unsubscribe.
Invoke the given callback when a text editor is added to the workspace.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when text editors are added. |
event | Object | with the following keys: |
textEditor | TextEditor | that was added. |
pane | Pane | containing the added text editor. |
index | Number | indicating the index of the added text editor in its pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback whenever the modal breadcrumb trail changes — a step is entered, the flow goes back, or the trail ends.
| Argument | Type | Description |
|---|---|---|
callback | Function | receiving the trail as #getModalTrail reports it. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Command Context1
Capture a command’s presentation and document targets before asynchronous work.
| Argument | Type | Description |
|---|---|---|
eventOrElement | Event|Element | The dispatch event or original DOM target. |
Returns
Object — window, pane, item, editor, fileEditor and embeddedEditor.
File Operations2
Register a shared document for explicit filesystem moves in this workspace.
| Argument | Type | Description |
|---|---|---|
descriptor | Object | The document adapter. |
owner | Object | The shared document identity. |
getPath | Function | Return the current path. |
setPath | Function | Retarget without resetting document state. |
beginFileOperation | Function | Defer filesystem reactions. |
endFileOperation | Function | Resume and reconcile reactions. |
Returns
Disposable — The document registration.
Suspend affected documents and defer repository discovery before moving files. Complete the returned transaction with confirmed moves, including partial results on failure.
| Argument | Type | Description |
|---|---|---|
plannedRenames | Array<Object> | Entries with oldPath, newPath and isDirectory. |
Returns
Object — A transaction with a ready promise and an asynchronous complete(confirmedRenames) method.
Dock Items1
Register a dock item’s initial visibility declaration without constructing it during package activation. Call this from the package’s synchronous bootstrap and dispose the registration when the package deactivates.
After the synchronous package bootstraps, the workspace calls getItem
and reads the item’s getDefaultVisibility(). It reserves the dock’s space
before the first workspace frame, then opens its content after layout
restoration. A saved dock layout takes precedence over defaults.
Registrations made after this initial preparation do not open automatically.
Disposing cancels an unfinished default opening. The package retains ownership of the item and is responsible for destroying it on deactivation.
| Argument | Type | Description |
|---|---|---|
getItem | Function | Return the package’s current dock item synchronously. |
Returns
Disposable — The registration to dispose when the package deactivates.
Layout3
Destroy every item in the given pane container locations, leaving each of them with a single empty pane.
Nothing is prompted for — the caller decides whether the items may go, which is why this is not Pane#destroyItems on every pane.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | An optional Object that may contain the following key: |
assertCurrentoptional, default: () => {} | Function | Throws if the caller-owned layout operation was superseded. |
locationsoptional | Array<String> | Locations to empty: center, left, right, or bottom; defaults to all four. |
Returns
Promise<void> — that resolves once they are empty.
Declare continuous layout resizing, such as an animated pane transition. Soft wrap honors editor.softWrapDebounceInterval while any resize session remains active and settles synchronously at the final width when it ends. Start before changing geometry, retain the session across interrupted or retargeted animation frames, and dispose after restoring the final layout. One-shot layout changes need no session. This API leaves pointer input enabled.
Returns
Disposable — Ends this resize session; repeated disposal is safe.
Declare that a drag which resizes editors has begun — a pane divider, a dock handle, a panel’s own resize grip, a gutter’s width handle.
Such a drag moves editor widths once per animation frame for as long as the
button is held, and work derived from those widths is worth deferring until
it stops. Soft wrap is the one that ships: it re-wraps on every width
change except while a resize session is live, when it waits for the width
to settle
rather than reflowing a frame the next one abandons. Anything that resizes
an editor from a mousemove should declare it; a one-shot layout change
should not, since it is already the final width.
Embedded surfaces in the focused presentation temporarily stop taking mouse events until the drag ends. Resize handles should also prevent the primary mousedown’s default focus change so the current editor or frame keeps focus.
Returns
Disposable — on which .dispose() ends the drag. It is safe to call more than once, which these gestures usually need: a mouseup, a mousemove that finds no button held any more, a teardown mid-drag.
Opening10
Opens the given URI in Lumine asynchronously.
If the URI is already open, the existing item for that URI will be
activated. If no URI is given, or no registered opener can open
the URI, a new empty TextEditor will be created.
The destination pane is captured before asynchronous opening begins, so
later focus changes do not redirect the result into another window.
Replacing the project session cancels pending opens and refuses new ones
until restoration or rollback completes.
Resetting or destroying the workspace, or closing the chosen destination
pane, cancels an unfinished open and resolves it to undefined. A late
opener-owned item is disposed if it remains unattached; an item supplied
by the caller stays caller-owned.
| Argument | Type | Description |
|---|---|---|
itemOrURIoptional | String|Object | An item to open or a String containing a URI. |
optionsoptional, default: {} | Object | |
openeroptional | String | The registered path opener ID to use, ‘text-editor’ for files, or ‘project-folder’ for directories. An explicit choice bypasses automatic opener preferences and only reuses an item of that opener’s type. |
destinationoptional, default: 'current' | String | The requested destination; a detached opening uses ‘detached-window’ and supplies its pane. |
uriFragmentoptional | String | The fragment of a local file URL, forwarded to the selected path opener after its path is normalized. |
signaloptional | AbortSignal | Cancels an unfinished opening and disposes an unpresented opener-owned result. |
initialLineoptional, default: 0 | Number | A Number indicating which row to move the cursor to initially. Defaults to 0. |
initialColumnoptional, default: 0 | Number | A Number indicating which column to move the cursor to initially. Defaults to 0. |
splitoptional | String | Either ‘left’, ‘right’, ‘up’ or ‘down’. If ‘left’, the item will be opened in leftmost pane of the current active pane’s row. If ‘right’, the item will be opened in the rightmost pane of the current active pane’s row. If only one pane exists in the row, a new pane will be created. If ‘up’, the item will be opened in topmost pane of the current active pane’s column. If ‘down’, the item will be opened in the bottommost pane of the current active pane’s column. If only one pane exists in the column, a new pane will be created. |
activatePaneoptional, default: true | Boolean | |
activateItemoptional, default: true | Boolean | |
pendingoptional | Boolean | A Boolean indicating whether or not the item should be opened in a pending state. Existing pending items in a pane are replaced with new pending items when they are opened. |
transferredoptional, default: false | Boolean | A Boolean marking a staged cross-window item whose requested placement should be preserved by tab surfaces. |
paneoptional | Pane | A Pane in which to open the item. File openings with searchAllPanes reuse a matching item before using this pane as their destination. When combined with split, the new pane is created directly beside this pane after the item is ready. |
searchAllPanesoptional, default: false | Boolean | A Boolean. If true, the workspace will attempt to activate an existing item for the given URI on any pane. If false, only the active pane will be searched for an existing item for the same URI. Defaults to false. |
locationoptional | String | A String containing the name of the location in which this item should be opened (one of “left”, “right”, “bottom”, or “center”). If omitted, Lumine will fall back to the last location in which a user has placed an item with the same URI or, if this is a new URI, the default location specified by the item. NOTE: This option should almost always be omitted to honor user preference. |
Returns
Promise<Object|undefined> — that resolves to the opened item, or undefined when cancelled or refused.
Search the workspace for items matching the given URI and hide them. Center items are closed asynchronously and can remain open if closing is prevented or cancelled. Use #toggle to await the closing result.
| Argument | Type | Description |
|---|---|---|
itemOrURI | String|Object | The item to hide or a String containing the URI of the item to hide. |
Returns
Boolean — indicating whether any visible matching items were found and hiding or closing was requested.
Search the workspace for items matching the given URI. If any are found, hide them. Otherwise, open the URL.
| Argument | Type | Description |
|---|---|---|
itemOrURIoptional | String|Object | The item to toggle or a String containing the URI of the item to toggle. |
Returns
Promise — that resolves when the item is shown or hidden, or to false if closing a center item is prevented or cancelled. Rejects if closing fails.
Creates a new item that corresponds to the provided URI.
If no URI is given, or no registered opener can open the URI, a new empty TextEditor will be created.
| Argument | Type | Description |
|---|---|---|
urioptional | String | A String containing a URI. |
optionsoptional | Object | Options supplied to URI openers. |
reuseRequestoptional | Object | A pending-item reuse request owned by the workspace open lifecycle. |
openRequestoptional, default: reuseRequest | Object | The current workspace open request used to reject obsolete results. |
Returns
Promise<Object|undefined> — that resolves to the TextEditor (or other item) for the given URI.
Asynchronously reopens the last-closed item’s URI if it hasn’t already been reopened.
Returns
Promise — that is resolved when the item is opened
Register an opener for an internal workspace URI.
When a URI is opened via Workspace#open, Lumine loops through its registered opener functions until one returns a value for the given uri. Openers are expected to return an object that inherits from HTMLElement or a model which has an associated view in the ViewRegistry. A TextEditor will be used if no opener returns a value.
Examples
lumine.workspace.addOpener((uri) => {
if (uri === 'lumine://my-package/panel') return new PackagePanel()
})
The opener is called only when its URI is not already open in the searched pane. The searchAllPanes flag expands that search. File viewers use Workspace#addPathOpener, which distinguishes existing item types for the same path and makes alternative views available through Launcher Open.
| Argument | Type | Description |
|---|---|---|
opener | Function | A Function to be called when an internal URI is being opened. Register named file viewers with Workspace#addPathOpener. |
optionsoptional, default: {} | Object | Optional preview reuse capabilities. |
canReusePendingItemoptional | Function | Synchronously checks (item, uri, openOptions) without changing the item. It is checked at this opener’s position in the opener order, before constructing a new item. |
reusePendingItemoptional | Function | Asynchronously replaces the document with (item, uri, openOptions, {signal}). Return false to decline and construct normally. Any other resolved value accepts the reuse. Throw AbortError to cancel an open superseded by item-owned navigation or reload. Keep the previous document intact on failure, honor the abort signal before committing, and emit the item’s onDidChangeURI event after committing. Reuse applies only to unmodified pending items in the same destination, without splitting or background opening. |
Returns
Disposable — on which .dispose() can be called to remove the opener.
Prepare path opener descriptors synchronously before resolving a local path. Use cheap path checks before discovering optional installed integrations. The callback may register openers; their canOpen predicates remain side-effect free. A reentrant query skips callbacks already running, and errors propagate to the caller. Internal and remote URIs do not invoke these callbacks.
| Argument | Type | Description |
|---|---|---|
callback | Function | Receives {uri, options} with the normalized local path, URI fragment and detected pathKind. It must finish synchronously without returning a Promise. |
Returns
Disposable — Removes this callback; opener registrations remain separately owned.
Register a named path opener for automatic opening and Launcher Open. Availability is checked without constructing a view or opening a path.
| Argument | Type | Description |
|---|---|---|
descriptor | Object | The path opener descriptor. |
id | String | A unique stable opener ID. |
label | String | The name shown in Launcher Open. |
canOpen | Function | Synchronously return a boolean for (uri, options) without side effects. |
open | Function | Create an item for (uri, options), or perform an action and return an empty string. May return a Promise. |
pathKindsoptional, default: ['file' | Array<String> | ] - Supported local path kinds: ‘file’ and/or ‘directory’. |
destinationsoptional, default: ['current','new-window','detached-window' | Array<String> | ] - Supported opening destinations. Side-effect actions declare only ‘current’. |
isDefaultEligibleoptional | Function | Synchronously return whether this opener participates in automatic opening; defaults to true. Explicit selection bypasses this preference. |
handlesItemoptional | Function | Recognize an existing or restored item for (item, uri, options), including this opener’s type and any fragment-specific identity. |
canReusePendingItemoptional | Function | Check whether an unmodified pending item can be reused. |
reusePendingItemoptional | Function | Replace a pending document with (item, uri, options, {signal}). |
Returns
Disposable — Removes this opener and its preview capabilities.
List path openers without invoking their opening callbacks. The automatic default is first, followed by the other available openers. Text Editor is always included for file paths. Project Folder is included for directory paths.
| Argument | Type | Description |
|---|---|---|
uri | String | The local file or directory path, or file URI. |
optionsoptional, default: {} | Object | Opening context supplied to the predicates. |
pathKindoptional | String | An already known ‘file’ or ‘directory’ kind; otherwise detected from the filesystem. |
Returns
Array<Object> — Descriptors containing id, label, isDefault and destinations.
Open a local path in a new independent project window with the selected opener. The opener is resolved and validated before requesting any window. File openings retain the current project roots; directory openings use that directory.
| Argument | Type | Description |
|---|---|---|
uri | String | The local file or directory path, or file URI. |
optionsoptional, default: {} | Object | Opening context. |
openeroptional | String | A registered path opener ID; defaults to the automatic opener. |
pathKindoptional | String | An already known ‘file’ or ‘directory’ kind. |
initialLineoptional | Number | Zero-based row for the target file. |
initialColumnoptional | Number | Zero-based column for the target file. |
uriFragmentoptional | String | A fragment forwarded to the selected file opener in the new window. |
signaloptional | AbortSignal | An aborted signal prevents the window request. |
Returns
Promise<void> — Resolves after requesting the new window.
Text Editors8
Determine whether a value is a TextEditor instance.
| Argument | Type | Description |
|---|---|---|
object | * | An Object you want to perform the check against. |
Returns
Boolean — that is true if object is a TextEditor.
Create a new text editor.
| Argument | Type | Description |
|---|---|---|
paramsoptional | Object | TextEditor construction and sizing options. |
Returns
Get all text editors in the workspace, if they are pane items.
Returns
Array<TextEditor> — of TextEditors.
Get the workspace center’s active item if it is a TextEditor.
Returns
TextEditor|undefined — or undefined if the workspace center’s current active item is not a TextEditor.
Resolve the innermost text editor containing a DOM target.
Unlike the registry, this is a structural lookup: an editor element is enough, even when its owner has not registered the model for observation. It never scans or materializes any other editor views.
| Argument | Type | Description |
|---|---|---|
target | Element | An element inside a text editor. |
optionsoptional, default: {} | Object | |
includeMinioptional, default: true | Boolean | Whether mini editors qualify. |
Returns
TextEditor|null — The containing editor, or null.
Get the text editor containing DOM focus, including embedded editors.
This differs from #getActiveTextEditor, which returns the active workspace-center pane item and deliberately ignores focus in package UI.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | |
includeMinioptional, default: true | Boolean | Whether mini editors qualify. |
Returns
TextEditor|null — The focused editor, or null.
Get the TextEditor holding the active item’s file content.
The workspace center’s active item itself when it is a text editor;
otherwise the editor the item names through its getFileTextEditor()
method — a notebook names its backing source editor. File-identity status
tiles (encoding, line ending) describe this editor, so they stay truthful
while a richer view of the file is open.
Returns
TextEditor — or undefined when the active item holds no file content.
Get the TextEditor being edited inside the active item.
The workspace center’s active item itself when it is a text editor;
otherwise the editor the item names through its
getActiveEmbeddedTextEditor() method — a notebook names its active
cell’s editor. Editing-state status tiles (the grammar tile) describe
this editor. An item reporting embedded editors emits its
onDidChangeActiveTextEditors signal whenever either resolution may have
changed; the workspace dedupes and re-emits through
#onDidChangeActiveEmbeddedTextEditor.
Returns
TextEditor — or undefined when nothing editable is active.
Dialogs4
Create a detached fuzzy-searchable SelectList model.
Like #buildTextEditor, this returns the complete model rather than
a UI facade. It creates its mini TextEditor model immediately, but lazily
creates its private renderer and detached element on the first
getElement() call. The query editor is registered with the window only
while that element is connected to the DOM.
The model owns data and behavior: items, sections, selection, query, source, actions, recents, pagination and confirmation. It has no panel or modal lifecycle. Pass it to #addSelectList, or let that method build an owned model, when it should appear as a modal.
The list shows one message at a time above the rows, from three props in
precedence order — loadingMessage (rendered with a spinner, and with
loadingBadge beside it), then status, then infoMessage. A status is
{type, message, duration, sticky}: type is 'info', 'warning' or
'error', duration clears it after that many milliseconds, and it is
cleared on the next query change unless sticky. It covers the resting
infoMessage rather than replacing it, so clearing it needs nothing put
back. emptyMessage stands in for the rows when there are none, and stands
down while a loading or status message is showing.
Data may be supplied as items, explicit sections, or an asynchronous
source. getItemId defines stable identity, search defines matching and
query parsing, and renderItem(item, context) returns an HTMLElement, a
managed row view, or a standard row descriptor. commands and actions
declare the operations available through Enter, Shift-F10 and right click.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | The initial SelectList options. |
Returns
Create a lazy SelectListHost. Passing model options creates a model owned by the host; passing a model from #buildSelectList borrows it. Destroying an owned host destroys its model, while a borrowed model remains available and may be hosted again. A model can have only one live host.
Construction creates neither a Panel nor DOM. host.show() creates and
opens the modal; host.getPanel() explicitly materializes it. The default
panel item is the model. A custom item must expose a view containing the
model element.
Every fresh show clears the query unless one is supplied and reapplies the
list’s selection.initial, defaulting to the first result unless empty
selection is enabled. Returning from a modal-flow step is a resume and
preserves both query and selection.
| Argument | Type | Description |
|---|---|---|
modelOrOptionsoptional | SelectList|Object | A detached model or its construction options. |
hostOptionsoptional | Object | Options belonging to the modal host only. |
windowoptional | EditorWindow | The presentation to host in, captured when the host is created; defaults to the focused or main window. |
itemoptional | * | Panel item; defaults to the model. |
crumboptional | String | Declared modal-flow label. |
visibleoptional, default: false | Boolean | Show when the host is first materialized. |
restoreFocusoptional, default: true | Boolean | Restore focus after hiding. |
priorityoptional, default: 100 | Number | Panel ordering priority. |
classNameoptional | String | Class names for the panel element. |
Returns
Create a detached InputDialog model whose query editor is the value.
This is the base of #buildSelectList without list semantics, for
prompts and save dialogs where the typed text is the answer. Extra DOM goes
above the editor through headerElement and below it through
contentElement. Its renderer and detached element are created lazily by
getElement(); it has no panel or modal lifecycle.
The message line works exactly as in #buildSelectList, minus
emptyMessage: a validation failure is status: {type: 'error', message},
and the dialog clears it on the next keystroke by itself.
The model publishes query and confirmation events and supports the same declared commands, actions, messages and asynchronous source contract as SelectList. Confirmation is normally a primary action.
| Argument | Type | Description |
|---|---|---|
optionsoptional | Object | The initial InputDialog options. |
Returns
Create a lazy InputDialogHost. Passing options creates an owned model; passing a model from #buildInputDialog borrows it. Ownership, one-host enforcement and lazy Panel/DOM materialization match #addSelectList.
| Argument | Type | Description |
|---|---|---|
modelOrOptionsoptional | InputDialog|Object | A detached model or its construction options. |
hostOptionsoptional | Object | Options belonging to the modal host only. |
itemoptional | * | Panel item; defaults to the model. |
crumboptional | String | Declared modal-flow label. |
visibleoptional, default: false | Boolean | Show when the host is first materialized. |
restoreFocusoptional, default: true | Boolean | Restore focus after hiding. |
priorityoptional, default: 100 | Number | Panel ordering priority. |
classNameoptional | String | Class names for the panel element. |
Returns
Modal Flow3
Go back one step in the modal breadcrumb trail.
A trail exists while a modal shown with Panel#show’s crumb option is
on screen. Going back hides the current step — without cancelling it —
and re-shows the previous panel with its state intact. Bound to
Shift-Escape as modal:go-back; Escape still cancels the visible modal,
which ends the whole trail.
| Argument | Type | Description |
|---|---|---|
windowoptional | EditorWindow | The presentation whose modal trail should go back; defaults to the main window. |
Returns
Boolean — — false when there is no step to go back to.
Jump back to an earlier step of the modal breadcrumb trail.
| Argument | Type | Description |
|---|---|---|
index | Number | The zero-based trail position to return to, as reported by #getModalTrail. The breadcrumb strip wires its crumbs to this. |
Returns
Boolean — — false when the index is not an earlier step.
The current modal breadcrumb trail.
Returns
Array — of String labels, root first; empty when no flow is active.
Pane Items8
Get all pane items in the workspace.
Returns
Array<Object> — of items.
Get the active Pane’s active item.
Returns
Object|undefined — The active item, or undefined when the active pane is empty.
Save the workspace center’s active pane item.
If the item has a URI according to its .getURI method, calls .save on
it; otherwise #saveActivePaneItemAs is called instead. Does nothing when
the item implements no .save method.
Targets the center rather than the focused pane container, for the reason given on #destroyActivePaneItem.
| Argument | Type | Description |
|---|---|---|
contextoptional | Object | A captured command context with documentPane and documentItem; otherwise uses the active document pane. |
Returns
Promise<*>|undefined
Prompt for a path and save the workspace center’s active pane item to it.
Opens a native dialog where the user selects a path on disk, then calls
.saveAs on the item with the selected path. Does nothing when the item
implements no .saveAs method.
Targets the center rather than the focused pane container, for the reason given on #destroyActivePaneItem.
| Argument | Type | Description |
|---|---|---|
contextoptional | Object | A captured command context with documentPane and documentItem; otherwise uses the active document pane. |
Returns
Promise<*>|undefined
Destroy (close) the active pane item.
Removes the active pane item and calls its .destroy method if it has one.
This one resolves through the active pane container, so it closes the focused dock’s item while a dock has focus. That pairs it with #getActivePaneItem and #getActivePane, which resolve the same way, and is what a package wants when it has already inspected the active item and decided to close it.
Its neighbours here deliberately differ: #saveActivePaneItem,
#saveActivePaneItemAs and #closeActivePaneItemOrEmptyPaneOrWindow are
pinned to the workspace center. They back core:save, core:save-as and
core:close. These commands act on the document being edited even when
focus is in a dock or an input field. Closing a dock item is a separate
action performed through its tab or package-owned commands.
Returns
Promise<Boolean> — Whether the active item was closed.
Move an exact item to an existing pane or a new split, preserving its live view.
| Argument | Type | Description |
|---|---|---|
item | Object | The item to move. |
optionsoptional, default: {} | Object | sourcePane, targetPane or splitDirection, index and activatePane. |
Returns
Promise<Object> — The final {pane, item}.
Copy an exact item before creating its destination, if the item supports copying.
| Argument | Type | Description |
|---|---|---|
item | Object | The item whose document and view state should be copied. |
optionsoptional, default: {} | Object | sourcePane, targetPane or splitDirection, index, activatePane and signal. |
Returns
Promise<Object|null> — The final {pane, item}, or null when copy() is absent or canCopy() returns false; cancellation rejects with ABORT_ERR.
Close the workspace center’s active pane item, or its active pane if that pane is empty, or the window if only the empty root pane is left.
Targets the center rather than the focused pane container, for the reason given on #destroyActivePaneItem.
| Argument | Type | Description |
|---|---|---|
contextoptional | Object | A captured documentPane/documentItem context; otherwise uses the active document pane. |
Returns
Promise<*>|undefined — The selected close operation, or undefined when closing an empty window is disabled.
Panes9
Get the most recently focused pane container.
Returns
Dock|WorkspaceCenter — or the WorkspaceCenter.
Get panes available to visual navigation, including visible docks. A temporary pane presentation exposes only its representative pane; getPanes() continues to return every pane in the original layout.
Returns
Array<Pane> — The panes available in the current presentation.
Make the next pane active.
Make the previous pane active.
Pane Locations6
Get the first pane container that contains an item with the given URI.
| Argument | Type | Description |
|---|---|---|
uri | String | uri |
Returns
Dock|WorkspaceCenter|undefined — the WorkspaceCenter, or undefined if no item exists with the given URI.
Get the first pane container that contains the given item.
| Argument | Type | Description |
|---|---|---|
item | Object | the Item that the returned pane container must contain. |
Returns
Dock|WorkspaceCenter|undefined — the WorkspaceCenter, or undefined if no pane container contains the given item.
Get the WorkspaceCenter aggregating the document panes of all workspace windows.
Returns
WorkspaceCenter — The document-pane aggregate for this workspace.
Panels15
Get an Array of all the panel items at the bottom of the editor window.
Returns
Array<Panel> — The panels in this main-window location.
Adds a panel item to the bottom of the editor window.
| Argument | Type | Description |
|---|---|---|
options | Object | |
item | * | Your panel content. It can be DOM element, a jQuery element, or a model with a view registered via ViewRegistry#addViewProvider. We recommend the latter. See ViewRegistry#addViewProvider for more information. |
visibleoptional | Boolean | false if you want the panel to initially be hidden (default: true) |
priorityoptional | Number | Determines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100) |
Returns
Get an Array of all the panel items to the left of the editor window.
Returns
Array<Panel> — The panels in this main-window location.
Adds a panel item to the left of the editor window.
| Argument | Type | Description |
|---|---|---|
options | Object | |
item | * | Your panel content. It can be DOM element, a jQuery element, or a model with a view registered via ViewRegistry#addViewProvider. We recommend the latter. See ViewRegistry#addViewProvider for more information. |
visibleoptional | Boolean | false if you want the panel to initially be hidden (default: true) |
priorityoptional | Number | Determines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100) |
Returns
Get an Array of all the panel items to the right of the editor window.
Returns
Array<Panel> — The panels in this main-window location.
Adds a panel item to the right of the editor window.
| Argument | Type | Description |
|---|---|---|
options | Object | |
item | * | Your panel content. It can be DOM element, a jQuery element, or a model with a view registered via ViewRegistry#addViewProvider. We recommend the latter. See ViewRegistry#addViewProvider for more information. |
visibleoptional | Boolean | false if you want the panel to initially be hidden (default: true) |
priorityoptional | Number | Determines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100) |
Returns
Get an Array of all the panel items at the top of the editor window.
Returns
Array<Panel> — The panels in this main-window location.
Adds a panel item to the top of the editor window above the tabs.
| Argument | Type | Description |
|---|---|---|
options | Object | |
item | * | Your panel content. It can be DOM element, a jQuery element, or a model with a view registered via ViewRegistry#addViewProvider. We recommend the latter. See ViewRegistry#addViewProvider for more information. |
visibleoptional | Boolean | false if you want the panel to initially be hidden (default: true) |
priorityoptional | Number | Determines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100) |
Returns
Get an Array of all the panel items in the header.
Returns
Array<Panel> — The panels in this main-window location.
Adds a panel item to the header.
| Argument | Type | Description |
|---|---|---|
options | Object | |
item | * | Your panel content. It can be DOM element, a jQuery element, or a model with a view registered via ViewRegistry#addViewProvider. We recommend the latter. See ViewRegistry#addViewProvider for more information. |
visibleoptional | Boolean | false if you want the panel to initially be hidden (default: true) |
priorityoptional | Number | Determines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100) |
Returns
Get an Array of all the modal panel items
Returns
Array<Panel> — The panels in this main-window location.
Adds a panel item as a modal dialog.
| Argument | Type | Description |
|---|---|---|
optionsoptional, default: {} | Object | |
item | * | Your panel content. It can be a DOM element, a jQuery element, or a model with a view registered via ViewRegistry#addViewProvider. We recommend the model option. See ViewRegistry#addViewProvider for more information. |
windowoptional | EditorWindow | The explicit presentation; defaults to the main window. |
visibleoptional | Boolean | false if you want the panel to initially be hidden (default: true) |
priorityoptional | Number | Determines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100) |
autoFocusoptional | Boolean|Element | true if you want modal focus managed for you by Lumine. Lumine will automatically focus on this element or your modal panel’s first tabbable element when the modal opens and will restore the previously selected element when the modal closes. Lumine will also automatically restrict user tab focus within your modal while it is open. (default: false) |
restoreFocusoptional | Boolean | false if you want to manage focus restoration yourself. By default, when a modal panel is hidden, focus returns to the element that was focused before the modal opened — or, for chained modals, before the first modal in the chain opened. (default: true) |
dismissOnBluroptional, default: false | Boolean|Function | Hide after an outside click or same-document focus departure. A synchronous predicate must return true to permit dismissal. Window blur and owned menus preserve the panel. Enabling this option defaults autoFocus to true unless explicitly disabled. |
crumboptional | String | the label this panel carries on the modal breadcrumb trail. Used when the panel is shown as a flow step without an explicit label — panel.show({crumb: true}) — and when a step shown on top of this panel adopts it as the trail root. See Panel#show. |
Returns
Find the panel displaying a given item.
| Argument | Type | Description |
|---|---|---|
item | * | Item the panel contains |
Returns
Panel|null — associated with the given item. Returns null when the item has no panel.
Searching and Replacing2
Performs a search across all files in the workspace as they exist on disk. Open text buffers are not searched.
Caveats
When a project has multiple roots, the patterns in options.paths may opt
into or out of specific roots.
For instance: when only one root is present, 'foo/bar.js' is construed
as a glob meant to match <root>/foo/bar.js; when multiple roots are
present and at least one project root has a base directory name of foo,
then foo/bar.js is construed as a glob meant only for root foo and
meant to match bar.js.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | to search with. |
optionsoptional, default: {} | Object | |
iterator | Function | callback on each file found. |
pathsoptional | Array<String> | An Array of glob patterns to search within. (See note below for multi-root projects.) |
ignoredNamesoptional | Array<String> | an Array of additional String globs to exclude. |
useCoreIgnoredNames | Boolean | whether to include core.ignoredNames; defaults to true. |
excludeVcsIgnoredPaths | Boolean | whether to honor VCS ignore files. Defaults to core.excludeVcsIgnoredPaths. |
onPathsSearchedoptional | Function | to be periodically called with number of paths searched. |
leadingContextLineCount | Number | default 0; The number of lines before the matched line to include in the results object. |
trailingContextLineCount | Number | default 0; The number of lines after the matched line to include in the results object. |
Returns
Promise — with a cancel() method that will cancel all of the underlying searches that were started as part of this scan.
Performs a replace across all the specified files in the project on disk. Open text buffers receive the disk edits and retain nonoverlapping unsaved changes. Different overlapping edits leave the buffer conflicted. Buffer-only matches are not replaced, and unsaved changes are not written to disk.
| Argument | Type | Description |
|---|---|---|
regex | RegExp | A RegExp to search with. |
replacementText | String | to replace all matches of regex with. |
filePaths | Array<String> | An Array of file path strings to run the replace on. |
iterator | Function | A Function callback on each file with replacements: |
options | Object | with keys filePath and replacements. |
Returns
Promise<void>
Essential API
WorkspaceCentersrc/workspace-center.js:14
Aggregates the document panes presented by all windows of one workspace.
Pane Containers1
Get all document containers in this center.
Returns
Array<PaneContainer> — The document containers in this workspace center.
Event Subscription16
Observe current and future document containers.
| Argument | Type | Description |
|---|---|---|
callback | Function |
Returns
Disposable — Dispose to stop observing added containers.
Invoke the given callback with all current and future text editors in the workspace center.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with current and future text editors. |
editor | TextEditor | An TextEditor that is present in #getTextEditors at the time of subscription or that is added at some later time. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with all current and future panes items in the workspace center.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with current and future pane items. |
item | * | An item that is present in #getPaneItems at the time of subscription or that is added at some later time. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the active pane item changes.
Because observers are invoked synchronously, it’s important not to perform any expensive operations via this method. Consider #onDidStopChangingActivePaneItem to delay operations until after changes stop occurring.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active pane item changes. |
item | * | The active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the active pane item stops changing.
Observers are called asynchronously 100ms after the last active pane item change. Handling changes here rather than in the synchronous #onDidChangeActivePaneItem prevents unneeded work if the user is quickly changing or closing tabs and ensures critical UI feedback, like changing the highlighted tab, gets priority over work that can be done asynchronously.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active pane item stops changing. |
item | * | The active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with the current active pane item and with all future active pane items in the workspace center.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active pane item changes. |
item | * | The current active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a pane is added to the workspace center.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when panes are added. |
event | Object | with the following keys: |
pane | Pane | The added pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback before a pane is destroyed in the workspace center.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called before panes are destroyed. |
event | Object | with the following keys: |
pane | Pane | The pane to be destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a pane is destroyed in the workspace center.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when panes are destroyed. |
event | Object | with the following keys: |
pane | Pane | The destroyed pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with all current and future panes in the workspace center.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with current and future panes. |
pane | Pane |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when the active pane changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when the active pane changes. |
pane | Pane | A Pane that is the current return value of #getActivePane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback with the current active pane and when the active pane changes.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called with the current and future active panes. |
pane | Pane | A Pane that is the current return value of #getActivePane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a pane item is added to the workspace center.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when pane items are added. |
event | Object | with the following keys: |
item | * | The added pane item. |
pane | Pane | containing the added item. |
index | Number | indicating the index of the added item in its pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Invoke the given callback when a pane item is about to be destroyed, before the user is prompted to save it.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called before pane items are destroyed. |
event | Object | with the following keys: |
item | * | The item to be destroyed. |
pane | Pane | containing the item to be destroyed. |
index | Number | indicating the index of the item to be destroyed in its pane. |
Returns
Disposable — on which .dispose can be called to unsubscribe.
Invoke the given callback when a pane item is destroyed.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when pane items are destroyed. |
event | Object | with the following keys: |
item | * | The destroyed item. |
pane | Pane | containing the destroyed item. |
index | Number | indicating the index of the destroyed item in its pane. |
Returns
Disposable — on which .dispose can be called to unsubscribe.
Invoke the given callback when a text editor is added to the workspace center.
| Argument | Type | Description |
|---|---|---|
callback | Function | to be called when panes are added. |
event | Object | with the following keys: |
textEditor | TextEditor | that was added. |
pane | Pane | containing the added text editor. |
index | Number | indicating the index of the added text editor in its pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Pane Items4
Get all pane items in the workspace center.
Returns
Array — of items.
Get the active Pane’s active item.
Returns
Object — pane item Object.
Get all text editors in the workspace center.
Returns
Array — of TextEditors.
Get the active item if it is an TextEditor.
Returns
TextEditor — or undefined if the current active item is not an TextEditor.
Panes4
Extended API
WorkspaceDropManagersrc/workspace-drop-manager.js:31
Routes workspace drag-and-drop through one capture lifecycle. Providers own source semantics; targets own surface-specific context and visuals.
Providers and Targets2
Register a provider for a serializable workspace drag kind.
Providers are consulted by descending priority; ties preserve registration order. A provider exposes a synchronous propose(context) for protected drag events, then optional prepareDrop(context) and perform(context, prepared) methods for the drop itself.
| Argument | Type | Description |
|---|---|---|
provider | Object | An Object implementing propose(context) or canHandle(context). |
optionsoptional, default: {} | Object | Registration options. |
priorityoptional, default: 0 | Number | Provider priority. |
Returns
Disposable — A disposable that unregisters the provider.
Register a workspace drop surface and its visual/placement adapter.
The deepest registered element in the event path wins. The adapter can provide getPane, getContext, getIndex, canDrop, and drag lifecycle callbacks.
| Argument | Type | Description |
|---|---|---|
element | Element | The target Element. |
adapteroptional, default: {} | Object | An adapter describing the target surface. |
optionsoptional, default: {} | Object | Registration options. |
priorityoptional, default: 0 | Number | Priority among targets at the same depth. |
Returns
Disposable — A disposable that unregisters the target.
Drag Sessions4
Create an exact, expiring source session for a move between windows.
| Argument | Type | Description |
|---|---|---|
value | * | The source value retained only in its owning window. |
callbacksoptional, default: {} | Object | Settlement callbacks. |
commitoptional | Function | Called after a target accepts the move; return or resolve to false to reject it. |
rollbackoptional | Function | Called when the move is abandoned or rejected. |
Returns
Object — An object containing the serializable session token.
Return the exact local value retained for a drag session token.
| Argument | Type | Description |
|---|---|---|
token | String|Object | A session token. |
Returns
* — the retained value, or undefined outside its source window.
Commit a local or cross-window drag session.
| Argument | Type | Description |
|---|---|---|
token | String|Object | A session token. |
resultoptional, default: {} | Object | Structured-cloneable result details. Cross-window callers include sourceWindowId. |
Returns
Promise<Boolean> — resolving to whether the source accepted the move.
Roll back a local or cross-window drag session.
| Argument | Type | Description |
|---|---|---|
token | String|Object | A session token. |
reason | * | A serializable reason for abandoning the move. |
optionsoptional, default: {} | Object | Cross-window routing when no drag descriptor was read locally. |
sourceWindowIdoptional | Number | The source window of a programmatic transfer. |
Returns
Promise<Boolean> — resolving to whether the rollback was delivered.
Data Transfer3
Write one versioned Lumine descriptor to a DataTransfer.
| Argument | Type | Description |
|---|---|---|
dataTransfer | DataTransfer | The drag’s DataTransfer. |
descriptor | Object | A descriptor containing kind, items, source metadata, effect, and allowed locations. |
Returns
Object — the normalized descriptor written to the transfer.
Inspect a drag offer using only types visible in protected drag mode.
| Argument | Type | Description |
|---|---|---|
dataTransfer | DataTransfer | The drag’s DataTransfer. |
Returns
Object|null — an offer object, or null when the drag is unsupported.
Read and validate a complete Lumine descriptor during drop.
| Argument | Type | Description |
|---|---|---|
dataTransfer | DataTransfer | The drop’s readable DataTransfer. |
Returns
Object|null — a normalized descriptor, or null when it is malformed or unavailable.
Essential API · Object
fuzzyMatchersrc/fuzzy-matcher.js:157
lumine.tools.fuzzyMatcher
Fuzzy matching utilities used by symbol lists, file search and the command
palette. Available as lumine.tools.fuzzyMatcher.
Use .setCandidates to create a reusable Matcher for an array of candidates. .match and .score match one candidate without creating a matcher yourself.
Candidate Sets1
Create a matcher for string candidates, or replace the candidates of an existing Matcher. The replacement preserves its construction options.
const matcher = lumine.tools.fuzzyMatcher.setCandidates(['hello', 'world'])
matcher.match('he')
lumine.tools.fuzzyMatcher.setCandidates(matcher, ['hello', 'hope'])
| Argument | Type | Description |
|---|---|---|
matcherOrCandidates | Matcher|Array<String> | An existing matcher or candidates for a new one. |
candidatesoptional | Array<String>|Object | Replacement candidates when the first argument is a matcher; construction options when it is an array. Set ignoreDiacritics: true in those options for accent-insensitive matching. |
_optionsoptional | Object | Retained for compatibility; ignored. |
ignoreDiacriticsoptional, default: false | Boolean | Construction option when candidates is an options object; fixed for the lifetime of the Matcher. |
Returns
Matcher — The created or updated matcher.
Matching2
Score a single candidate against a query.
| Argument | Type | Description |
|---|---|---|
candidate | String | The candidate to match. |
query | String | The search query. |
optsoptional, default: {} | Object | The options accepted by Matcher#match, plus ignoreDiacritics for accent-insensitive matching. |
ignoreDiacriticsoptional, default: false | Boolean | Enable accent-insensitive matching; match indexes refer to the original candidate. |
Returns
Number — The score from 0 to 1, or 0 when there is no match.
Match a single candidate against a query. Accent-insensitive matching reports character indexes against the original candidate.
| Argument | Type | Description |
|---|---|---|
candidate | String | The candidate to match. |
query | String | The search query. |
optsoptional, default: {} | Object | The options accepted by Matcher#match, plus ignoreDiacritics for accent-insensitive matching. |
ignoreDiacriticsoptional, default: false | Boolean | Enable accent-insensitive matching; match indexes refer to the original candidate. |
Returns
Object|undefined — The match with id, value, score and optional character indexes, or undefined when there is no match.
Public API · Object
Iconsrc/icon-descriptor.js:61
require('lumine').Icon
Factories and helpers for the frozen icon descriptors consumed by
IconRegistry. Available as require('lumine').Icon.
Full description
A descriptor contains a render discriminator (classes, image, svg,
letter or none), a frozen classes array, and nullable source, svg,
viewBox, letter, color, title and providerId fields. Always use these
factories: a plain object with the same fields is not a descriptor.
Providers return a descriptor when they claim an icon, .none when
they intentionally suppress one, and null to let the next provider answer.
Construction5
Create a glyph-font icon. The provider supplies the CSS for the given classes; the editor applies them unchanged.
| Argument | Type | Description |
|---|---|---|
value | String|Array<String> | A whitespace-separated class string or an array of class names. Empty input returns .none; non-string array entries are ignored. |
optionsoptional, default: {} | Object | Presentation options. |
coloroptional, default: null | String|null | The glyph color. |
titleoptional, default: null | String|null | The tooltip title. |
Returns
Object — A frozen icon descriptor.
Create an image icon addressed by URL, such as a data: URL from the OS
or a file: URL from an icon theme. The editor paints it in its icon box.
| Argument | Type | Description |
|---|---|---|
source | String | The image URL. Empty input returns .none. |
optionsoptional, default: {} | Object | Presentation options. |
titleoptional, default: null | String|null | The tooltip title. |
Returns
Object — A frozen icon descriptor.
Create an inline SVG icon rendered into a child element. Markup is supplied by the provider and is not sanitized.
| Argument | Type | Description |
|---|---|---|
markup | String | SVG markup. Empty input returns .none. |
optionsoptional, default: {} | Object | Presentation options. |
viewBoxoptional, default: null | String|null | The SVG view box. |
coloroptional, default: null | String|null | The icon color. |
titleoptional, default: null | String|null | The tooltip title. |
Returns
Object — A frozen icon descriptor.
Create a badge from the first Unicode code point of a string.
| Argument | Type | Description |
|---|---|---|
character | String | Badge text. Empty input returns .none. |
optionsoptional, default: {} | Object | Presentation options. |
coloroptional, default: null | String|null | The badge color. |
titleoptional, default: null | String|null | The tooltip title. |
Returns
Object — A frozen icon descriptor.
Explicitly suppress an icon. This stops provider resolution; returning
null instead lets the next provider answer.
Returns
Object — The shared frozen descriptor with render: 'none'.
Descriptor Helpers3
Test whether a value was created by these descriptor factories.
| Argument | Type | Description |
|---|---|---|
value | * | The value to inspect. |
Returns
Boolean — Whether the value is an icon descriptor.
Compare descriptors by their rendered fields. Provider identity is ignored; two identical absent values also compare equal.
| Argument | Type | Description |
|---|---|---|
left | Object|null|undefined | An icon descriptor or an absent value. |
right | Object|null|undefined | An icon descriptor or an absent value. |
Returns
Boolean — Whether the descriptors would render identically.
Rebuild a provider’s descriptor with its structural classes and provider
identity. Throws a TypeError for values that are not descriptors.
| Argument | Type | Description |
|---|---|---|
value | Object|null|undefined | An icon descriptor, or an absent value that passes through as null. |
optionsoptional, default: {} | Object | Provider metadata. |
providerIdoptional, default: null | String|null | The provider identity. A non-null value overrides the descriptor’s existing identity. |
Returns
Object|null — A rebuilt frozen descriptor, or null for absent input.
Public API
Functions
Public functions with their callable access paths.
Functions9
Uses Lumine’s built-in Syntax Highlighting system to apply the same syntax highlighting to code blocks within markdown. Modifies the existing object passed.
| Argument | Type | Description |
|---|---|---|
content | Element|DocumentFragment | The HTML Node/Fragment to apply syntax highlighting on. Will modify the original object. |
givenOptsoptional, default: {} | Object | Optional Arguments: |
syntaxScopeNameFuncoptional, default: null | Function|null | A function that can be called with any given language ID from a code block scope, and returns the grammar source id that should be used to perform syntax highlighting. |
renderModeoptional, default: "full" | String | Whether we are rendering a document fragment or a full document. Valid values: “full”, “fragment”. |
grammaroptional, default: null | Object|null | The grammar of the source file. Carryover from original markdown-preview functionality. |
autoWidthoptional, default: false | Boolean | Whether the editors standing in for code blocks size themselves to their longest line (“fragment” mode only). A code block otherwise takes the width its container gives it, which is nothing at all when the container is sized by its content — a tooltip, a popover. Pass true there. |
Parse an HTML string into a detached DocumentFragment. This should be done if you need access to APIs available on the DOM itself.
| Argument | Type | Description |
|---|---|---|
content | String | The HTML String. |
Returns
DocumentFragment — The parsed fragment. This function does not sanitize HTML.
Prepare one completion query. Results keep their score and lazily computed UTF-16 match indices together. This scorer does not apply path bonuses. Matches also expose exact, prefix, caseSensitivePrefix and firstCharacterMatches flags using the same normalization as scoring. Queries longer than 256 UTF-16 units produce no matches. Cached candidate text is bounded to 2048 entries and 262144 UTF-16 units per query.
| Argument | Type | Description |
|---|---|---|
query | String | Typed text, matched case-insensitively. |
Returns
Object — A query with match(text) and isRefinementOf(previousQuery).
Determine whether a save stopped because the user cancelled it.
| Argument | Type | Description |
|---|---|---|
error | * | The error returned by a save operation. |
Returns
Boolean — Whether the error represents save cancellation.
Removes diacritical marks from a string, so that “café” can be matched by typing “cafe”.
| Argument | Type | Description |
|---|---|---|
text | String | The string to fold. |
Returns
String — The same string with its diacritics removed.
Takes a Markdown document and renders it as HTML.
| Argument | Type | Description |
|---|---|---|
content | String | The Markdown source material. |
givenOptsoptional, default: {} | Object | The optional arguments: |
renderModeoptional, default: "full" | String | Determines how the page is rendered. Valid values “full” or “fragment”. |
htmloptional, default: true | Boolean | Whether HTML tags should be allowed. |
allowFileProtocoloptional, default: false | Boolean | Allow file URLs in Markdown links. The sanitizer’s protocol policy still applies. |
sanitizeoptional, default: true | Boolean | If the page content should be sanitized via DOMPurify. |
sanitizeAllowUnknownProtocolsoptional, default: true | Boolean | Controls DOMPurify’s own option of ‘ALLOW_UNKNOWN_PROTOCOLS’. |
sanitizeAllowSelfCloseoptional, default: true | Boolean | Controls DOMPurify’s own option of ‘ALLOW_SELF_CLOSE’ |
breaksoptional, default: false | Boolean | If newlines should always be converted into breaklines. |
handleFrontMatteroptional, default: true | Boolean | Whether YAML or JSON frontmatter data should be processed and displayed. Other language headers remain Markdown. |
useDefaultEmojioptional, default: false | Boolean | Whether markdown-it-emoji should be enabled. |
useGitHubHeadingsoptional, default: false | Boolean | Whether markdown-it-github-headings should be enabled. False by default. |
useTaskCheckboxoptional, default: true | Boolean | Whether markdown-it-task-checkbox should be enabled. True by default. |
taskCheckboxDisabledoptional, default: true | Boolean | Controls markdown-it-task-checkbox disabled option. True by default. |
taskCheckboxDivWrapoptional, default: false | Boolean | Controls markdown-it-task-checkbox divWrap option. False by default. |
transformImageLinksoptional, default: true | Boolean | Attempt to resolve image URLs. True by default. |
transformNonFqdnLinksoptional, default: true | Boolean | Attempt to resolve links that are not fully qualified domain names. True by default. |
rootDomainoptional, default: "" | String | The root URL of the online resource. Useful when attempting to resolve any links on the page. Only works for online resources. |
filePathoptional, default: "" | String | The local alternative to rootDomain. Used to resolve incomplete paths, but locally on the file system. |
disableModeoptional, default: "none" | String | The level of disabling of markdown features. none by default. But supports: “none”, “strict” |
Returns
String — Parsed HTML content.
Apply a select list’s recent-item change to the latest stored IDs. Use this pure reducer inside a scoped state’s atomic mutate() callback so concurrent lists preserve each other’s records without reviving removed entries.
| Argument | Type | Description |
|---|---|---|
currentIdsoptional, default: [ | Array<*> | ] - Latest stored IDs in most-recent-first order. |
recentIdsoptional, default: [ | Array<*> | ] - The list’s proposed IDs, used for explicit replacement. |
changeoptional, default: {} | Object | The change metadata supplied to recents.adapter.save(). |
typeoptional, default: "replace" | String | record, remove, clear, limit, or replace. |
idoptional | * | Stable primitive ID for a record or removal. |
limitoptional, default: Infinity | Number | Maximum number of IDs to retain. |
Returns
Array<*> — Detached, deduplicated IDs after applying the change.
Observe a fixed directory and its direct children, or its entire tree. Missing directories remain observed through their nearest existing ancestor.
| Argument | Type | Description |
|---|---|---|
directoryPath | String | The directory path to observe. |
optionsoptional | Object | Observation options; omit for direct children only. |
recursiveoptional, default: false | Boolean | Whether to include descendants. |
Returns
FileWatchHandle — A synchronous handle with ready and closed promises.
Observe a fixed file path, including deletion and recreation. External renames never change the observed path. Changes are hints to reread the file; an invalidation requires a reread after observation has recovered.
| Argument | Type | Description |
|---|---|---|
filePath | String | The path to observe, resolved to an absolute path. |
Returns
FileWatchHandle — A synchronous handle with ready and closed promises.