Public API
LumineEnvironmentsrc/lumine-environment.js:83
Lumine global for dealing with packages, themes, menus, and the window.
An instance of this class is always available as the lumine global.
Properties29
#::applicationApplicationService
An ApplicationService instance
A Clipboard instance
#::commandsCommandRegistry
A CommandRegistry instance
A Config instance
#::contextMenuContextMenuManager
A ContextMenuManager instance
#::deserializersDeserializerManager
A DeserializerManager instance
#::deserializeTimingsObject<string, number>
How long each deserialized top-level object took to restore, in
milliseconds, keyed by name (project, workspace). The timecop
package reads this to report window load cost, and resets it to {}.
#::grammarsGrammarRegistry
A GrammarRegistry instance
#::historyHistoryManager
A HistoryManager instance
#::iconsIconRegistry
An IconRegistry instance
#::keymapsKeymapManager
A KeymapManager instance
#::menuMenuManager
A MenuManager instance
#::notificationsNotificationManager
A NotificationManager instance
#::packagesPackageManager
A PackageManager instance
#::pasteProvidersPasteProviderRegistry
A PasteProviderRegistry instance
A Project instance
#::repositoriesRepositoryRegistry
A RepositoryRegistry instance
#::runtimeRuntimeService
A RuntimeService instance
#::secretsSecretStore
A SecretStore instance
#::shellShellService
A ShellService instance
#::stylesStyleManager
A StyleManager instance
#::textEditorsTextEditorRegistry
A TextEditorRegistry instance
#::themesThemeManager
A ThemeManager instance
#::toolsObject
Editor utilities a package can reuse instead of vendoring its own:
markdown, fuzzyMatcher, and removeDiacritics.
#::tooltipsTooltipManager
A TooltipManager instance
#::uriHandlersURIHandlerRegistry
A URIHandlerRegistry instance
#::viewsViewRegistry
A ViewRegistry instance
#::windowWindowService
A WindowService instance
A Workspace instance
Public API
ApplicationServicesrc/application-service.js:11
Main-process application services exposed as serializable values.
Methods16
#::getPath(name)
Return an Electron application path captured during bootstrap.
| Argument | Description |
|---|---|
name | StringA supported Electron application-path name. |
Returns
String — The cached path synchronously.
#::getLocale()
Return the application locale captured during bootstrap.
Returns
String — The cached locale synchronously.
#::getResourcePath()
Return the editor resource directory captured during bootstrap.
Returns
String — The absolute resource path synchronously.
#::getName()
Return the full name of this Lumine application.
Returns
String — The application name synchronously.
#::getVersion()
Return the Lumine application version.
Returns
String — The version synchronously.
#::versionSatisfies(range)
Determine whether the current application version satisfies a semantic-version range.
| Argument | Description |
|---|---|
range | StringA semantic-version range. |
Returns
Boolean — Whether the current version satisfies the range.
#::getReleaseChannel()
Return the current release channel.
Returns
String — The release channel.
#::isReleasedVersion()
Determine whether this build came from the release pipeline.
Returns
Boolean — Whether this is a released build.
#::openWindow(params)
Open paths in a new or reusable Lumine window.
The call returns immediately after sending the request to the main process.
| Argument | Description |
|---|---|
params | ObjectPaths and window options to open. |
#::getUserDefault(key, type)
Read an operating-system user default.
Returns
Promise — resolving to a serializable preference value.
#::getAccentColor()
Read the operating system’s accent color.
Returns
Promise — resolving to a #rrggbb string, or null where the platform has no accent color to report.
#::printToPDF(html, outputPath, options = {})
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 | Description |
|---|---|
html | StringA complete HTML document. Reference assets by data URI: nothing relative to the calling document resolves. |
outputPath | StringWhere to write the PDF. |
optionsoptional | ObjectElectron printToPDF options. printBackground defaults to true. |
Returns
Promise — resolving to {outcome: 'success', result: outputPath}, or {outcome: 'failure', error} when the document could not be printed.
#::isDefaultProtocolClient(protocol, path, args)
Determine whether Lumine is the default handler for a protocol.
Returns
Promise — resolving to a Boolean.
#::setAsDefaultProtocolClient(protocol, path, args)
Register Lumine as the default handler for a protocol.
Returns
Promise — resolving to a Boolean.
#::getFileIcon(filePath, options = {})
Load an operating-system file icon as a data URL.
| Argument | Description |
|---|---|
optionsoptional, default: {} | No description. |
Returns
Promise — resolving to a data-URL String, or null.
#::restart()
Restart Lumine with the current launch options.
Returns
Promise — that resolves when restart is scheduled.
Extended API
BufferedNodeProcesssrc/buffered-node-process.js:18
Like BufferedProcess, but accepts a Node script as the command to run.
This is necessary on Windows since it doesn’t support shebang #! lines.
Examples
const {BufferedNodeProcess} = require('lumine')
Methods1
#new BufferedNodeProcess({ command, args, options = {}, stdout, stderr, exit })
Runs the given Node script by spawning a new child process.
| Argument | Description |
|---|---|
options | ObjectProcess options. |
command | StringPath to the JavaScript script. |
argsoptional | Array<String>Arguments passed to the script. |
optionsoptional | ObjectOptions passed to Node’s ChildProcess.spawn. |
stdoutoptional | FunctionReceives buffered, complete lines of standard output and any remaining data when the stream closes. |
data | StringStandard-output data. |
stderroptional | FunctionReceives buffered, complete lines of standard error and any remaining data when the stream closes. |
data | StringStandard-error data. |
exitoptional | FunctionReceives the process exit status. |
code | NumberThe exit status. |
Extended API
BufferedProcesssrc/buffered-process.js:25
A wrapper which provides standard error/output line buffering for Node’s ChildProcess.
Examples
{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
#new BufferedProcess({ command, args, options = {}, stdout, stderr, exit, autoStart = true } = {})
Runs the given command by spawning a new child process.
| Argument | Description |
|---|---|
optionsoptional | ObjectProcess options. |
command | StringThe command to execute. |
argsoptional | Array<String>Arguments passed to the command. |
optionsoptional | ObjectOptions passed to Node’s ChildProcess.spawn. |
stdoutoptional | FunctionReceives buffered, complete lines of standard output and any remaining data when the stream closes. |
data | StringStandard-output data. |
stderroptional | FunctionReceives buffered, complete lines of standard error and any remaining data when the stream closes. |
data | StringStandard-error data. |
exitoptional | FunctionReceives the process exit status. |
code | NumberThe exit status. |
autoStartoptional, default: true | BooleanWhether to start immediately. |
Event Subscription1
#::onWillThrowError(callback)
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 | Description |
|---|---|
callback | Functioncallback |
errorObject | Object |
error | Objectthe error object |
handle | Functioncall this to indicate you have handled the error. The error will not be thrown if this function is called. |
Returns
Disposable
Helper Methods1
#::kill()
Terminate the process.
Extended API
Clipboardsrc/clipboard.js:34
Represents the clipboard used for copying and pasting in Lumine.
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 deprecated require('electron').clipboard in a renderer, so every
read and write here goes to the main process instead (see
src/clipboard-bridge.js).
Examples
lumine.clipboard.write('hello')
console.log(lumine.clipboard.read()) // 'hello'
Methods11
#::write(text, metadata)
Write the given text to the clipboard.
The metadata associated with the text is available by calling #readWithMetadata.
| Argument | Description |
|---|---|
text | The String to store. |
metadataoptional | The additional info to associate with the text. |
#::writeNativeData(text, format, data)
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 | Description |
|---|---|
text | The plain-text String to store alongside the payload. |
format | The MIME-style format String, without the web prefix. |
data | The JSON-serializable payload. |
Returns
Promise — that resolves to true when the payload was written, or false when only the plain text could be written.
#::readNativeData(format)
Read a JSON payload written by #writeNativeData in this or any other window.
| Argument | Description |
|---|---|
format | The MIME-style format String, without the web prefix. |
Returns
Promise — that resolves to the parsed payload Object, or null when the clipboard holds no valid payload for the format.
#::read()
Read the text from the clipboard.
Returns
String
#::writeFindText(text)
Write the given text to the macOS find pasteboard
#::readFindText()
Read the text from the macOS find pasteboard.
Returns
String
#::readImage()
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
NativeImage — empty when the clipboard holds no image.
#::writeImage(image)
Write an image to the clipboard, replacing whatever it held.
| Argument | Description |
|---|---|
image | A NativeImage, or the PNG bytes of one as a Buffer. |
#::readSelectionText()
Read the text from the Linux primary selection.
Returns
String — always empty on the platforms that have no primary selection.
#::writeSelectionText(text)
Write the given text to the Linux primary selection.
Unlike every other method here this one does not wait for the main process: it runs on each selection change, and a drag cannot afford a round trip per mouse move.
| Argument | Description |
|---|---|
text | The String to store. |
#::readWithMetadata()
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
Object — with the following keys:
Essential API
Colorsrc/color.js:10
A simple color class returned from Config#get when the value at the key path is of type ‘color’.
Methods3
#.parse(value)
Parse a String or Object into a Color.
| Argument | Description |
|---|---|
value | A String such as 'white', #ff00ff, or 'rgba(255, 15, 60, .75)' or an Object with red, green, blue, and alpha properties. |
Returns
Color — or null if it cannot be parsed.
#::toHexString()
Returns
String — in the form '#abcdef'.
#::toRGBAString()
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.
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())
}
})
Methods5
#::add(target, commandName, listener, throwOnInvalidSelector = true)
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 | Description |
|---|---|
target | String|ElementA CSS selector or DOM element. Selectors associate the command with all matching elements; the , combinator is not supported. |
commandName | String|ObjectA command name such as user:insert-date, or a map of command names to listeners. |
listeneroptional | Function|ObjectA function, or an object whose didDispatch property handles the command. |
throwOnInvalidSelectoroptional, default: true | BooleanThrow when target is an invalid selector. |
event | EventThe dispatched DOM event. Call stopPropagation() or stopImmediatePropagation() to stop bubbling. |
displayNameoptional | StringOverrides the generated display name. |
descriptionoptional | StringDetailed command information. |
hiddenInCommandPaletteoptional | BooleanHide the command from the bundled command palette by default. |
modaloptional | Boolean|StringDeclares that the command opens a modal, optionally naming its breadcrumb label. |
Returns
Disposable — on which .dispose() can be called to remove the added command handler(s).
#::findCommands({ target })
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 | Description |
|---|---|
params | ObjectQuery parameters. |
target | ElementThe hypothetical command target. |
Returns
Array<Object> — Command descriptors containing the documented keys.
#::dispatch(target, commandName, detail)
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 | Description |
|---|---|
target | The DOM node at which to start bubbling the command event. |
commandName | Stringindicating the name of the command to dispatch. |
detail | Any value that will be assigned to the event’s .detail property. Pass an object with multiple properties if you need multiple command arguments. |
#::onWillDispatch(callback)
Invoke the given callback before dispatching a command event.
| Argument | Description |
|---|---|
callback | Functionto be called before dispatching each command |
event | The Event that will be dispatched |
#::onDidDispatch(callback)
Invoke the given callback after dispatching a command event.
| Argument | Description |
|---|---|
callback | Functionto be called after dispatching each command |
event | The Event that was dispatched |
Essential API
Configsrc/config.js:430
Used to access all of Lumine’s configuration details.
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'
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
#::observe(...args)
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 | Description |
|---|---|
keyPath | StringThe configuration key to observe. |
optionsoptional | ObjectObservation options. |
scopeoptional | ScopeDescriptorA 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 | FunctionCalled when the value changes. |
value | *The new value. |
Returns
Disposable — A disposable on which .dispose() can be called to unsubscribe.
#::onDidChange(...args)
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 | Description |
|---|---|
keyPathoptional | StringThe key to observe. Required when options.scope is specified. |
optionsoptional | ObjectObservation options. |
scopeoptional | ScopeDescriptorA 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 | FunctionCalled when the value changes. |
event | ObjectThe change event. |
newValue | *The new value. |
oldValue | *The previous value. |
Returns
Disposable — A disposable on which .dispose() can be called to unsubscribe.
Managing Settings7
#::get(...args)
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 language.tabLength for ruby
files.
lumine.config.get('language.tabLength', { scope: ['source.ruby'] }) // => 2
This setting in ruby files might be different than the global tabLength setting
lumine.config.get('language.tabLength') // => 4
lumine.config.get('language.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('language.tabLength', { scope: editor.getRootScopeDescriptor() }) // => 2
Additionally, you can get the setting at the specific cursor position.
const scopeDescriptor = editor.getLastCursor().getScopeDescriptor()
lumine.config.get('language.tabLength', { scope: scopeDescriptor }) // => 2
| Argument | Description |
|---|---|
keyPath | StringThe key to retrieve. |
optionsoptional | ObjectLookup 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 | ScopeDescriptorA 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 value from Lumine’s defaults or the user’s configuration, in the type specified by the configuration schema.
#::getAll(keyPath, options)
Get all of the values for the given key-path, along with their associated scope selector.
| Argument | Description |
|---|---|
keyPath | The String name of the key to retrieve |
optionsoptional | Objectsee the options argument to #get |
scopeDescriptor | The ScopeDescriptor with which the value is associated |
value | The value for the key-path |
Returns
Array — of Objects with the following keys:
#::set(...args)
Sets the value for a configuration setting.
This value is stored in Lumine’s internal configuration file.
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
language.tabLength only for ruby files.
lumine.config.get('language.tabLength') // => 4
lumine.config.get('language.tabLength', { scope: ['source.ruby'] }) // => 4
lumine.config.get('language.tabLength', { scope: ['source.js'] }) // => 4
// Set ruby to 2
lumine.config.set('language.tabLength', 2, { scopeSelector: '.source.ruby' }) // => true
// Notice it's only set to 2 in the case of ruby
lumine.config.get('language.tabLength') // => 4
lumine.config.get('language.tabLength', { scope: ['source.ruby'] }) // => 2
lumine.config.get('language.tabLength', { scope: ['source.js'] }) // => 4
| Argument | Description |
|---|---|
keyPath | StringThe configuration key. |
value | *The setting value. Passing undefined reverts it to the default value. |
optionsoptional | ObjectWrite options. |
scopeSelectoroptional | StringA scope such as .source.ruby. See the scopes docs for more information. |
sourceoptional | StringThe 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.
#::unset(keyPath, options)
Restore the setting at keyPath to its default value.
#::getSources()
Get an Array of all of the source Strings with which
settings have been added via #set.
#::getSchema(keyPath)
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 | Description |
|---|---|
keyPath | 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.
#::transact(callback)
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 | Description |
|---|---|
callback | Functionto execute while suppressing calls to handlers. |
Extended API
Cursorsrc/cursor.js:18
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
#::onDidChangePosition(callback)
Calls your callback when the cursor has been moved.
| Argument | Description |
|---|---|
callback | Function |
event | Object |
oldBufferPosition | |
oldScreenPosition | |
newBufferPosition | |
newScreenPosition | |
textChanged | Boolean |
cursor | Cursorthat triggered the event |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDestroy(callback)
Calls your callback when the cursor is destroyed
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Managing Cursor Position11
#::setScreenPosition(screenPosition, options = {})
Moves a cursor to a given screen position.
| Argument | Description |
|---|---|
screenPosition | Arrayof two numbers: the screen row, and the screen column. |
optionsoptional | Objectwith the following keys: |
autoscroll | A Boolean which, if true, scrolls the TextEditor to wherever the cursor moves to. |
#::getScreenPosition()
Returns
#::setBufferPosition(bufferPosition, options = {})
Moves a cursor to a given buffer position.
| Argument | Description |
|---|---|
bufferPosition | Arrayof two numbers: the buffer row, and the buffer column. |
optionsoptional | Objectwith the following keys: |
autoscroll | Booleanindicating whether to autoscroll to the new position. Defaults to true if this is the most recently added cursor, false otherwise. |
#::getBufferPosition()
Returns
Array — current buffer position as an Array.
#::getScreenRow()
Returns
Number — cursor’s current screen row.
#::getScreenColumn()
Returns
Number — cursor’s current screen column.
#::getBufferRow()
Retrieves the cursor’s current buffer row.
#::getBufferColumn()
Returns
Number — cursor’s current buffer column.
#::getCurrentBufferLine()
Returns
Number — cursor’s current buffer row of text excluding its line ending.
#::isAtBeginningOfLine()
Returns
Boolean — whether the cursor is at the start of a line.
#::isAtEndOfLine()
Returns
Boolean — whether the cursor is on the line return character.
Cursor Position Details9
#::getMarker()
Returns
DisplayMarker — underlying DisplayMarker for the cursor. Useful with overlay Decorations.
#::isSurroundedByWhitespace()
Identifies if the cursor is surrounded by whitespace.
“Surrounded” here means that the character directly before and after the cursor are both whitespace.
Returns
Boolean
#::isBetweenWordAndNonWord()
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 language.nonWordCharacters setting.
#::isInsideWord(options)
| Argument | Description |
|---|---|
optionsoptional | Object |
wordRegex | A RegExp indicating what constitutes a “word” (default: #wordRegExp). |
Returns
Boolean — whether this cursor is between a word’s start and end.
#::getIndentLevel()
Returns
Number — indentation level of the current line.
#::getScopeDescriptor()
Retrieves the scope descriptor for the cursor’s current position.
Returns
#::getSyntaxTreeScopeDescriptor()
Retrieves the syntax tree scope descriptor for the cursor’s current position.
Returns
#::hasPrecedingCharactersOnLine()
Returns
Boolean — true if this cursor has no non-whitespace characters before its current position.
#::isLastCursor()
Identifies if this cursor is the last in the TextEditor.
“Last” is defined as the most recently added cursor.
Returns
Boolean
Moving the Cursor21
#::moveUp(rowCount = 1, { moveToEndOfSelection } = {})
Moves the cursor up one screen row.
| Argument | Description |
|---|---|
rowCountoptional | Numbernumber of rows to move (default: 1) |
optionsoptional | ObjectMovement options. |
moveToEndOfSelectionoptional | BooleanMove to the start of an existing selection. |
#::moveDown(rowCount = 1, { moveToEndOfSelection } = {})
Moves the cursor down one screen row.
| Argument | Description |
|---|---|
rowCountoptional | Numbernumber of rows to move (default: 1) |
optionsoptional | ObjectMovement options. |
moveToEndOfSelectionoptional | BooleanMove to the end of an existing selection. |
#::moveLeft(columnCount = 1, { moveToEndOfSelection } = {})
Moves the cursor left one screen column.
| Argument | Description |
|---|---|
columnCountoptional | Numbernumber of columns to move (default: 1) |
optionsoptional | ObjectMovement options. |
moveToEndOfSelectionoptional | BooleanMove to the start of an existing selection. |
#::moveRight(columnCount = 1, { moveToEndOfSelection } = {})
Moves the cursor right one screen column.
| Argument | Description |
|---|---|
columnCountoptional | Numbernumber of columns to move (default: 1) |
optionsoptional | ObjectMovement options. |
moveToEndOfSelectionoptional | BooleanMove to the end of an existing selection. |
#::moveToTop()
Moves the cursor to the top of the buffer.
#::moveToBottom()
Moves the cursor to the bottom of the buffer.
#::moveToBeginningOfScreenLine()
Moves the cursor to the beginning of the line.
#::moveToBeginningOfLine()
Moves the cursor to the beginning of the buffer line.
#::moveToFirstCharacterOfLine()
Moves the cursor to the beginning of the first character in the line.
#::moveToEndOfScreenLine()
Moves the cursor to the end of the line.
#::moveToEndOfLine()
Moves the cursor to the end of the buffer line.
#::moveToBeginningOfWord()
Moves the cursor to the beginning of the word.
#::moveToEndOfWord()
Moves the cursor to the end of the word.
#::moveToBeginningOfNextWord()
Moves the cursor to the beginning of the next word.
#::moveToPreviousWordBoundary()
Moves the cursor to the previous word boundary.
#::moveToNextWordBoundary()
Moves the cursor to the next word boundary.
#::moveToPreviousSubwordBoundary()
Moves the cursor to the previous subword boundary.
#::moveToNextSubwordBoundary()
Moves the cursor to the next subword boundary.
#::skipLeadingWhitespace()
Moves the cursor to the beginning of the buffer line, skipping all whitespace.
#::moveToBeginningOfNextParagraph()
Moves the cursor to the beginning of the next paragraph
#::moveToBeginningOfPreviousParagraph()
Moves the cursor to the beginning of the previous paragraph
Local Positions and Ranges9
#::getPreviousWordBoundaryBufferPosition(options = {})
| Argument | Description |
|---|---|
optionsoptional | Objectwith the following keys: |
wordRegex | 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.
#::getNextWordBoundaryBufferPosition(options = {})
| Argument | Description |
|---|---|
optionsoptional | Objectwith the following keys: |
wordRegex | A RegExp indicating what constitutes a “word” (default: #wordRegExp) |
Returns
Point — buffer position of the next word boundary. It might be on the current word, or the previous word.
#::getBeginningOfCurrentWordBufferPosition(options = {})
Retrieves the buffer position of where the current word starts.
| Argument | Description |
|---|---|
optionsoptional | An Object with the following keys: |
wordRegex | A RegExp indicating what constitutes a “word” (default: #wordRegExp). |
includeNonWordCharacters | A Boolean indicating whether to include non-word characters in the default word regex. Has no effect if wordRegex is set. |
allowPrevious | A Boolean indicating whether the beginning of the previous word can be returned. |
Returns
#::getEndOfCurrentWordBufferPosition(options = {})
Retrieves the buffer position of where the current word ends.
| Argument | Description |
|---|---|
optionsoptional | Objectwith the following keys: |
wordRegex | A RegExp indicating what constitutes a “word” (default: #wordRegExp) |
includeNonWordCharacters | A Boolean indicating whether to include non-word characters in the default word regex. Has no effect if wordRegex is set. |
Returns
#::getBeginningOfNextWordBufferPosition(options = {})
Retrieves the buffer position of where the next word starts.
| Argument | Description |
|---|---|
optionsoptional | Object |
wordRegex | A RegExp indicating what constitutes a “word” (default: #wordRegExp). |
Returns
#::getCurrentWordBufferRange(options = {})
| Argument | Description |
|---|---|
optionsoptional | Object |
wordRegex | A RegExp indicating what constitutes a “word” (default: #wordRegExp). |
Returns
Range — buffer Range occupied by the word located under the cursor.
#::getCurrentLineBufferRange(options)
| Argument | Description |
|---|---|
optionsoptional | Object |
includeNewline | A Boolean which controls whether the Range should include the newline. |
Returns
Range — buffer Range for the current line.
#::getCurrentParagraphBufferRange()
Retrieves the range for the current paragraph.
A paragraph is defined as a block of text surrounded by empty lines or comments.
Returns
#::getCurrentWordPrefix()
Returns
String — characters preceding the cursor in the current word.
Comparing to another cursor1
#::compare(otherCursor)
Compare this cursor’s buffer position to another cursor’s buffer position.
See Point#compare for more details.
| Argument | Description |
|---|---|
otherCursor | Cursorto compare against |
Utilities3
#::clearSelection(options)
Deselects the current selection.
#::wordRegExp(options)
Get the RegExp used by the cursor to determine what a “word” is.
| Argument | Description |
|---|---|
optionsoptional | Objectwith the following keys: |
includeNonWordCharacters | A Boolean indicating whether to include non-word characters in the regex. (default: true) |
Returns
RegExp
#::subwordRegExp(options = {})
Get the RegExp used by the cursor to determine what a “subword” is.
| Argument | Description |
|---|---|
optionsoptional | Objectwith the following keys: |
backwards | 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.
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.
Construction and Destruction1
#::destroy()
Destroy this marker decoration.
You can also destroy the marker if you own it, which will destroy this decoration.
Event Subscription2
#::onDidChangeProperties(callback)
When the Decoration is updated via Decoration#setProperties.
| Argument | Description |
|---|---|
callback | Function |
event | Object |
oldProperties | Objectthe decoration’s previous properties |
newProperties | Objectthe decoration’s new properties |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDestroy(callback)
Invoke the given callback when the Decoration is destroyed
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Decoration Details3
#::getId()
An id unique across all Decoration objects
#::getMarker()
Returns
DisplayMarker — marker associated with this Decoration
#::isType(type)
Check if this decoration is of type type
| Argument | Description |
|---|---|
type | Stringtype like 'line-number', 'line', etc. type can also be an Array of Strings, where it will return true if the decoration’s type matches any in the array. |
Returns
Boolean
Properties2
#::getProperties()
Returns
Object — The decoration’s properties.
#::setProperties(newProperties)
Update the marker with new Properties. Allows you to change the decoration’s class.
Examples
decoration.setProperties({ type: 'line-number', class: 'my-new-class' })
| Argument | Description |
|---|---|
newProperties | Objecteg. {type: 'line-number', class: 'my-new-class'} |
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.
Methods3
#::directoryForURISync(uri)
Create a Directory that corresponds to the specified URI.
| Argument | Description |
|---|---|
uri | StringThe path to the directory to add. This is guaranteed not to be contained by a Directory in lumine.project. |
Returns
Directory|null — A directory when the URI is compatible, or null otherwise.
#::directoryForURI(uri)
Create a Directory that corresponds to the specified URI.
| Argument | Description |
|---|---|
uri | StringThe path to the directory to add. This is guaranteed not to be contained by a Directory in lumine.project. |
Returns
Promise<Directory|null> — A promise resolving to a directory when the URI is compatible, or null otherwise.
#::normalizePath(uri)
Normalizes path.
| Argument | Description |
|---|---|
uri | StringThe path that should be normalized. |
Returns
String — with normalized path.
Extended API
DeserializerManagersrc/deserializer-manager.js:36
Manages the deserializers used for serialized state
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
#::add(...deserializers)
Register the given class(es) as deserializers.
| Argument | Description |
|---|---|
...deserializers | 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 LumineEnvironment object as the second argument, which is useful if you wish to avoid referencing the lumine global. |
#::deserialize(state)
Deserialize the state and params.
| Argument | Description |
|---|---|
state | The state Object to deserialize. |
Essential API
DisplayMarkersrc/display-marker.js:47
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.
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.
Construction and Destruction2
#::destroy()
Destroys the marker, causing it to emit the ‘destroyed’ event. Once destroyed, a marker cannot be restored by undo/redo operations.
#::copy(params)
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 a null value will be
returned.
| Argument | Description |
|---|---|
paramsoptional | Objectproperties to associate with the new marker. The new marker’s properties are computed by extending this marker’s properties with params. |
Returns
Event Subscription2
#::onDidChange(callback)
Invoke the given callback when the state of the marker changes.
| Argument | Description |
|---|---|
callback | Functionto be called when the marker changes. |
event | Objectwith the following keys: |
oldHeadBufferPosition | Pointrepresenting the former head buffer position |
newHeadBufferPosition | Pointrepresenting the new head buffer position |
oldTailBufferPosition | Pointrepresenting the former tail buffer position |
newTailBufferPosition | Pointrepresenting the new tail buffer position |
oldHeadScreenPosition | Pointrepresenting the former head screen position |
newHeadScreenPosition | Pointrepresenting the new head screen position |
oldTailScreenPosition | Pointrepresenting the former tail screen position |
newTailScreenPosition | Pointrepresenting the new tail screen position |
wasValid | Booleanindicating whether the marker was valid before the change |
isValid | Booleanindicating whether the marker is now valid |
hadTail | Booleanindicating whether the marker had a tail before the change |
hasTail | Booleanindicating whether the marker now has a tail |
oldProperties | Objectcontaining the marker’s custom properties before the change. |
newProperties | Objectcontaining the marker’s custom properties after the change. |
textChanged | Booleanindicating whether this change was caused by a textual change to the buffer or whether the marker was manipulated directly via its public API. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDestroy(callback)
Invoke the given callback when the marker is destroyed.
| Argument | Description |
|---|---|
callback | Functionto be called when the marker is destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
TextEditorMarker Details8
#::isValid()
Returns
Boolean — indicating whether the marker is valid. Markers can be invalidated when a region surrounding them in the buffer is changed.
#::isDestroyed()
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.
#::isReversed()
Returns
Boolean — indicating whether the head precedes the tail.
#::isExclusive()
Returns
Boolean — indicating whether changes that occur exactly at the marker’s head or tail cause it to move.
#::getInvalidationStrategy()
Get the invalidation strategy for this marker.
Valid values include: never, surround, overlap, inside, and touch.
Returns
String
#::getProperties()
Returns
Object — containing any custom properties associated with the marker.
#::setProperties(properties)
Merges an Object containing new properties into the marker’s
existing properties.
| Argument | Description |
|---|---|
properties | Object |
#::matchesProperties(attributes)
Returns
Boolean — whether this marker matches the given parameters. The parameters are the same as DisplayMarkerLayer#findMarkers.
Comparing to other markers2
#::compare(otherMarker)
Compares this marker to another based on their ranges.
| Argument | Description |
|---|---|
otherMarker | DisplayMarkerThe marker to compare. |
Returns
Number — The ordering of this marker relative to otherMarker.
#::isEqual(other)
| Argument | Description |
|---|---|
other | DisplayMarkerother marker |
Returns
Boolean — indicating whether this marker is equivalent to another marker, meaning they have the same range and options.
Managing the marker's range19
#::getBufferRange()
Gets the buffer range of this marker.
Returns
#::getScreenRange()
Gets the screen range of this marker.
Returns
#::setBufferRange(bufferRange, properties)
Modifies the buffer range of this marker.
| Argument | Description |
|---|---|
bufferRange | The new Range to use |
propertiesoptional | Objectproperties to associate with the marker. |
reversed | BooleanIf true, the marker will to be in a reversed orientation. |
#::setScreenRange(screenRange, options)
Modifies the screen range of this marker.
| Argument | Description |
|---|---|
screenRange | The new Range to use |
optionsoptional | An Object with the following keys: |
reversed | BooleanIf true, the marker will to be in a reversed orientation. |
clipDirection | StringIf '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. |
#::getHeadBufferPosition()
Retrieves the buffer position of the marker’s head.
Returns
#::setHeadBufferPosition(bufferPosition)
Sets the buffer position of the marker’s head.
| Argument | Description |
|---|---|
bufferPosition | The new Point to use |
#::getHeadScreenPosition(options)
Retrieves the screen position of the marker’s head.
| Argument | Description |
|---|---|
optionsoptional | An Object with the following keys: |
clipDirection | StringIf '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.
#::setHeadScreenPosition(screenPosition, options)
Sets the screen position of the marker’s head.
| Argument | Description |
|---|---|
screenPosition | The new Point to use |
optionsoptional | An Object with the following keys: |
clipDirection | StringIf 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'. |
#::getTailBufferPosition()
Retrieves the buffer position of the marker’s tail.
Returns
#::setTailBufferPosition(bufferPosition)
Sets the buffer position of the marker’s tail.
| Argument | Description |
|---|---|
bufferPosition | The new Point to use |
#::getTailScreenPosition(options)
Retrieves the screen position of the marker’s tail.
| Argument | Description |
|---|---|
optionsoptional | An Object with the following keys: |
clipDirection | StringIf '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.
#::setTailScreenPosition(screenPosition, options)
Sets the screen position of the marker’s tail.
| Argument | Description |
|---|---|
screenPosition | The new Point to use |
optionsoptional | An Object with the following keys: |
clipDirection | StringIf 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'. |
#::getStartBufferPosition()
Retrieves the buffer position of the marker’s start. This will always be less than or equal to the result of DisplayMarker#getEndBufferPosition.
Returns
#::getStartScreenPosition(options)
Retrieves the screen position of the marker’s start. This will always be less than or equal to the result of DisplayMarker#getEndScreenPosition.
| Argument | Description |
|---|---|
optionsoptional | An Object with the following keys: |
clipDirection | StringIf '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.
#::getEndBufferPosition()
Retrieves the buffer position of the marker’s end. This will always be greater than or equal to the result of DisplayMarker#getStartBufferPosition.
Returns
#::getEndScreenPosition(options)
Retrieves the screen position of the marker’s end. This will always be greater than or equal to the result of DisplayMarker#getStartScreenPosition.
| Argument | Description |
|---|---|
optionsoptional | An Object with the following keys: |
clipDirection | StringIf '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.
#::hasTail()
Returns
Boolean — indicating whether the marker has a tail.
#::plantTail()
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.
#::clearTail()
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.
Experimental API
DisplayMarkerLayersrc/display-marker-layer.js:15
A container for a related set of markers at the DisplayLayer level. Wraps
an underlying MarkerLayer on the TextBuffer.
This API is experimental and subject to change on any release.
Lifecycle3
Event Subscription3
#::onDidDestroy(callback)
Subscribe to be notified synchronously when this layer is destroyed.
Returns
Disposable
#::onDidUpdate(callback)
Subscribe to be notified asynchronously 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.
Subscribers are notified once, asynchronously when any number of changes occur in a given tick of the event loop. 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 | Description |
|---|---|
callback | A Function that will be called with no arguments when changes occur on this layer. |
Returns
Disposable
#::onDidCreateMarker(callback)
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 | Description |
|---|---|
callback | A Function that will be called with a TextEditorMarker whenever a new marker is created. |
Returns
Disposable
Marker creation4
#::markScreenRange(screenRange, options)
Create a marker with the given screen range.
| Argument | Description |
|---|---|
screenRange | A Range or range-compatible Array |
options | A hash of key-value pairs to associate with the marker. There are also reserved property names that have marker-specific meaning. |
reversedoptional | BooleanCreates the marker in a reversed orientation. (default: false) |
invalidateoptional | StringDetermines 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: * 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. |
exclusive | Booleanindicating 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 behavior in all circumstances. |
clipDirection | StringIf '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. |
Returns
DisplayMarker — The new marker.
#::markScreenPosition(screenPosition, options)
Create a marker on this layer with its head at the given screen position and no tail.
| Argument | Description |
|---|---|
screenPosition | A Point or point-compatible Array |
optionsoptional | An Object with the following keys: |
invalidateoptional | StringDetermines 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: * 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. |
exclusive | Booleanindicating 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 behavior in all circumstances. |
clipDirection | StringIf '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.
#::markBufferRange(bufferRange, options)
Create a marker with the given buffer range.
| Argument | Description |
|---|---|
bufferRange | A Range or range-compatible Array |
options | A hash of key-value pairs to associate with the marker. There are also reserved property names that have marker-specific meaning. |
reversedoptional | BooleanCreates the marker in a reversed orientation. (default: false) |
invalidateoptional | StringDetermines 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: * 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. |
exclusive | Booleanindicating 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 behavior in all circumstances. |
Returns
#::markBufferPosition(bufferPosition, options)
Create a marker on this layer with its head at the given buffer position and no tail.
| Argument | Description |
|---|---|
bufferPosition | A Point or point-compatible Array |
optionsoptional | An Object with the following keys: |
invalidateoptional | StringDetermines 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: * 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. |
exclusive | Booleanindicating 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 behavior in all circumstances. |
Returns
Extended API
Docksrc/dock.js:24
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.
Methods5
#::activate()
Show the dock and focus its active Pane.
#::show()
Show the dock without focusing it.
#::hide()
Hide the dock and activate the WorkspaceCenter if the dock was was previously focused.
#::toggle()
Toggle the dock’s visibility without changing the Workspace's active pane container.
#::isVisible()
Check if the dock is visible.
Returns
Boolean
Event Subscription16
#::onDidChangeVisible(callback)
Invoke the given callback when the visibility of the dock changes.
| Argument | Description |
|---|---|
callback | Functionto be called when the visibility changes. |
visible | BooleanIs the dock now visible? |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeVisible(callback)
Invoke the given callback with the current and all future visibilities of the dock.
| Argument | Description |
|---|---|
callback | Functionto be called when the visibility changes. |
visible | BooleanIs the dock now visible? |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observePaneItems(callback)
Invoke the given callback with all current and future panes items in the dock.
| Argument | Description |
|---|---|
callback | Functionto 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.
#::onDidChangeActivePaneItem(callback)
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 | Description |
|---|---|
callback | Functionto be called when the active pane item changes. |
item | The active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidStopChangingActivePaneItem(callback)
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 | Description |
|---|---|
callback | Functionto be called when the active pane item stops changing. |
item | The active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeActivePaneItem(callback)
Invoke the given callback with the current active pane item and with all future active pane items in the dock.
| Argument | Description |
|---|---|
callback | Functionto be called when the active pane item changes. |
item | The current active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidAddPane(callback)
Invoke the given callback when a pane is added to the dock.
| Argument | Description |
|---|---|
callback | Functionto be called when panes are added. |
event | Objectwith the following keys: |
pane | The added pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onWillDestroyPane(callback)
Invoke the given callback before a pane is destroyed in the dock.
| Argument | Description |
|---|---|
callback | Functionto be called before panes are destroyed. |
event | Objectwith the following keys: |
pane | The pane to be destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDestroyPane(callback)
Invoke the given callback when a pane is destroyed in the dock.
| Argument | Description |
|---|---|
callback | Functionto be called when panes are destroyed. |
event | Objectwith the following keys: |
pane | The destroyed pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observePanes(callback)
Invoke the given callback with all current and future panes in the dock.
| Argument | Description |
|---|---|
callback | Functionto be called with current and future panes. |
pane |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeActivePane(callback)
Invoke the given callback when the active pane changes.
| Argument | Description |
|---|---|
callback | Functionto be called when the active pane changes. |
pane | A Pane that is the current return value of #getActivePane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeActivePane(callback)
Invoke the given callback with the current active pane and when the active pane changes.
| Argument | Description |
|---|---|
callback | Functionto be called with the current and future active panes. |
pane | A Pane that is the current return value of #getActivePane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidAddPaneItem(callback)
Invoke the given callback when a pane item is added to the dock.
| Argument | Description |
|---|---|
callback | Functionto be called when pane items are added. |
event | Objectwith the following keys: |
item | The added pane item. |
pane | Panecontaining the added item. |
index | Numberindicating the index of the added item in its pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onWillDestroyPaneItem(callback)
Invoke the given callback when a pane item is about to be destroyed, before the user is prompted to save it.
| Argument | Description |
|---|---|
callback | Functionto be called before pane items are destroyed. |
event | Objectwith the following keys: |
item | The item to be destroyed. |
pane | Panecontaining the item to be destroyed. |
index | Numberindicating the index of the item to be destroyed in its pane. |
Returns
Disposable — on which .dispose can be called to unsubscribe.
#::onDidDestroyPaneItem(callback)
Invoke the given callback when a pane item is destroyed.
| Argument | Description |
|---|---|
callback | Functionto be called when pane items are destroyed. |
event | Objectwith the following keys: |
item | The destroyed item. |
pane | Panecontaining the destroyed item. |
index | Numberindicating the index of the destroyed item in its pane. |
Returns
Disposable — on which .dispose can be called to unsubscribe.
#::onDidChangeHovered(callback)
Invoke the given callback when the hovered state of the dock changes.
| Argument | Description |
|---|---|
callback | Functionto be called when the hovered state changes. |
hovered | BooleanIs the dock now hovered? |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Pane Items2
Panes4
Extended API
GitRepositorysrc/git-repository.js:85
Represents the underlying git operations performed by Lumine.
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.
This class handles submodules automatically by taking a path argument to many
of the methods. This path argument will determine which underlying
repository is used.
For a repository with submodules this would have the following outcome:
const repo = lumine.repositories.getRepositories()[0]
repo.getShortHead() // 'master'
repo.getShortHead('vendor/path/to/a/submodule') // 'dead1234'
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 Destruction6
#.open(path, options)
Creates a new GitRepository instance.
| Argument | Description |
|---|---|
path | The String path to the Git repository to open. |
options | An optional Object with the following keys: |
refreshOnWindowFocus | A Boolean, true to refresh the index and statuses when the window is focused. |
Returns
GitRepository — instance or null if the repository could not be opened.
#::destroy()
Destroy this GitRepository object.
This destroys any tasks and subscriptions and releases the underlying libgit2 repository handle. This method is idempotent.
#::isDestroyed()
Returns
Boolean — indicating if this repository has been destroyed.
#::isPresent()
Returns
Boolean — whether this repository’s Git directory still exists.
#::getOperations()
Returns
Object — stable write facade assigned by lumine.repositories. Its methods are enabled by repositories.operations-provider services.
#::onDidDestroy(callback)
Invoke the given callback when this GitRepository’s destroy() method is invoked.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Event Subscription4
#::onDidChangeStatus(callback)
Invoke the given callback when a specific file’s status has changed. When a file is updated, reloaded, etc, and the status changes, this will be fired.
Note: prefer #onDidChangeStatusSnapshot, which fires for every status change; this legacy per-path event is retained for API compatibility.
| Argument | Description |
|---|---|
callback | Function |
event | Object |
path | Stringthe path whose status changed |
pathStatus | Numberrepresenting the status. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeStatuses(callback)
Invoke the given callback when multiple files’ statuses have changed. Prefer #onDidChangeStatusSnapshot; this legacy event is retained for API compatibility.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeStatusSnapshot(callback)
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 | Description |
|---|---|
callback | Functioncalled with an immutable status snapshot. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeRefsSnapshot(callback)
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 | Description |
|---|---|
callback | Functioncalled with an immutable refs snapshot. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Repository Details15
#::getType()
A String indicating the type of version control system used by
this repository.
Returns
"git"
#::getPath()
Returns
String — path of the repository.
#::getWorkingDirectory()
Returns
String — working directory path of the repository.
#::isProjectAtRoot()
Returns
Boolean — true if at the root, false if in a subfolder of the repository.
#::relativize(path)
Makes a path relative to the repository’s working directory.
#::hasBranch(branch)
Returns
Boolean — true if the given branch exists.
#::getShortHead()
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 SHA-1 of a detached HEAD to 7
characters.
Returns
String — The shortened HEAD reference.
#::isSubmodule(filePath)
Is the given path a submodule in the repository?
| Argument | Description |
|---|---|
filePath | The String path to check. |
Returns
Boolean
#::getAheadBehindCount(reference)
| Argument | Description |
|---|---|
reference | The String branch reference name. |
Returns
Object — The ahead and behind commit counts.
#::getCachedUpstreamAheadBehindCount()
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:
#::getConfigValueAsync(key)
Asynchronously read a git configuration value via the git-host
worker (git config --get), the off-thread replacement for the synchronous
libgit2 config lookup. Resolves to the value or null when unset.
| Argument | Description |
|---|---|
key | StringThe configuration key to look up. |
Returns
Promise<String|null> — The configured value.
#::getOriginURL()
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.
#::getUpstreamBranch()
Returns
String|null — The upstream branch, such as refs/remotes/origin/master, or null when HEAD has no upstream.
#::getReferences()
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:
#::getReferenceTarget(reference)
| Argument | Description |
|---|---|
reference | The String reference to get the target of. |
Returns
String|null — The current SHA for the reference, or null when it is unavailable.
Reading Status23
#::isPathModified(path)
| Argument | Description |
|---|---|
path | The String path to check. |
Returns
Boolean — Whether the path is modified in the detailed status snapshot. Returns false until the snapshot loads.
#::isPathNew(path)
| Argument | Description |
|---|---|
path | The String path to check. |
Returns
Boolean — Whether the path is new in the detailed status snapshot. Returns false until the snapshot loads.
#::isPathIgnored(path)
Is the given path ignored? Resolved from the detailed status snapshot’s ignored entries; returns false until the snapshot has loaded.
| Argument | Description |
|---|---|
path | The String path to check. |
Returns
Boolean — that’s true if the path is ignored.
#::isPathIgnoredCached(filePath)
Whether the given path is ignored, resolved synchronously from the Git status snapshot’s ignored entries. Returns false until the first snapshot loads.
| Argument | Description |
|---|---|
filePath | The String path to check. |
Returns
Boolean — that’s true if the filePath is ignored.
#::getStatusSnapshot()
Returns
Object — latest immutable detailed status snapshot. It contains head, upstream, 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.
#::ensureStatusSnapshot(options = {})
Resolve with an initialized status snapshot, loading it on first call. Concurrent callers share one in-flight refresh.
| Argument | Description |
|---|---|
optionsoptional, default: {} | No description. |
Returns
Promise — that resolves to the snapshot.
#::getStatusEntry(filePath)
Returns
Object|null — detailed cached status for a repository path, or null.
#::refreshStatusSnapshot(options = {})
Refresh the detailed branch and file status snapshot with Git.
Concurrent calls coalesce into at most one in-flight and one trailing
subprocess; see coalesceSnapshotRefresh.
| Argument | Description |
|---|---|
optionsoptional, default: {} | No description. |
#::getPathStatusSummary(filePath)
Classified status for one path, read from the detailed status snapshot.
| Argument | Description |
|---|---|
filePath | A String path, absolute or repository-relative. |
Returns
Object|null — frozen {source, conflicted, modified, added, renamed} object (source is always "snapshot"), or null for clean, ignored, unknown, and pre-snapshot paths.
#::getDirectoryStatusSummary(directoryPath)
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.
#::getRefsSnapshot()
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.
#::ensureRefsSnapshot(options = {})
Resolve with an initialized refs snapshot, loading it on first call. Concurrent callers share one in-flight refresh.
| Argument | Description |
|---|---|
optionsoptional, default: {} | No description. |
Returns
Promise — that resolves to the snapshot.
#::refreshRefsSnapshot(options = {})
Refresh the refs snapshot with Git. Concurrent calls coalesce into
at most one in-flight and one trailing refresh; see
coalesceSnapshotRefresh.
| Argument | Description |
|---|---|
optionsoptional, default: {} | No description. |
#::getDiff({
from = { type: "index" },
to = { type: "worktree" },
paths = [],
context = 3,
ignoreWhitespace = false,
detectRenames = true,
diffFilter = null,
maxBytes = 10 * 1024 * 1024,
signal,
} = {})
Compute a structured diff between two endpoints.
| Argument | Description |
|---|---|
optionsoptional | ObjectDiff options. |
fromoptional | ObjectThe starting endpoint. |
tooptional | ObjectThe ending endpoint. Endpoints may be commit, index, worktree, file, or empty descriptors. |
pathsoptional | Array<String>Pathspecs limiting the diff. |
contextoptional, default: 3 | NumberContext lines. |
ignoreWhitespaceoptional, default: false | BooleanIgnore all whitespace. |
detectRenamesoptional, default: true | BooleanDetect renames. |
diffFilteroptional | StringA Git diff-filter value. |
maxBytesoptional, default: 10485760 | NumberOutput limit. Exceeding it rejects with ERR_GIT_DIFF_TOO_LARGE. |
signaloptional | AbortSignalCancellation signal. |
Returns
Promise — resolving to a frozen {schemaVersion, files, rawPatch} object; each file carries paths, status, similarity, binary flag, modes, and hunks with classified lines.
#::getCommits({
revision = "HEAD",
path: pathOption = null,
limit = 50,
cursor = null,
signal,
} = {})
Read paginated commit history.
| Argument | Description |
|---|---|
optionsoptional | ObjectHistory options. |
revisionoptional, default: "HEAD" | StringStarting revision. |
pathoptional | StringLimit history to one path and follow renames. |
limitoptional, default: 50 | NumberPage size. |
cursoroptional | ObjectThe nextCursor from a previous page. |
signaloptional | AbortSignalCancellation signal. |
Returns
Promise — 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.
#::getCommit(sha, { signal } = {})
Read one commit with its changed-file summary.
| Argument | Description |
|---|---|
sha | The String commit id or any revision expression. |
Returns
Promise — resolving to the commit object extended with changedFiles: [{path, originalPath, status, similarity}].
#::getFileAtRevision(filePath, revision, { encoding = "utf8", signal } = {})
Read a file’s contents at a revision.
| Argument | Description |
|---|---|
filePath | A String path, absolute or repository-relative. |
revision | A String revision expression. |
optionsoptional | ObjectRead options. |
encodingoptional, default: "utf8" | StringText encoding, or "buffer" for a Buffer. |
signaloptional | AbortSignalCancellation signal. |
Returns
Promise — resolving to the contents, or null when the path does not exist at that revision.
#::getBlob(oid, { encoding = "utf8", signal } = {})
Read a blob’s contents by object id (git cat-file -p <oid>).
| Argument | Description |
|---|---|
oid | A String blob object id. |
optionsoptional | ObjectRead options. |
encodingoptional, default: "utf8" | StringText encoding, or "buffer" for a Buffer. |
signaloptional | AbortSignalCancellation signal. |
Returns
Promise — resolving to the contents, or null when the oid does not name an object.
#::getDescription()
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.
#::getBranchesContaining(commit, { showLocal = false, showRemote = false, pattern = null } = {})
The fully-qualified refnames of branches that contain a commit
(git branch --contains).
| Argument | Description |
|---|---|
commit | A String commit id or revision. |
optionsoptional | ObjectBranch filtering options. |
showLocaloptional, default: false | BooleanInclude local branches. |
showRemoteoptional, default: false | BooleanInclude remote branches. |
patternoptional | StringLimit branch names by pattern. |
Returns
Promise — resolving to an Array of refname Strings.
#::getFileMode(filePath)
The index mode of a path (git ls-files --stage).
| Argument | Description |
|---|---|
filePath | A String path, absolute or repository-relative. |
Returns
Promise — resolving to the String mode (e.g. "100644"), or null when the path is not tracked.
#::getSubmodulePaths()
The repository-relative paths of the repository’s submodules
(git submodule status).
Returns
Promise — resolving to an Array of path Strings.
#::getBlame(filePath, { revision = null, ignoreWhitespace = false, signal } = {})
Read line-by-line blame for a file.
| Argument | Description |
|---|---|
filePath | A String path, absolute or repository-relative. |
optionsoptional | ObjectBlame options. |
revisionoptional | StringRevision to blame. |
ignoreWhitespaceoptional | BooleanIgnore whitespace-only changes when attributing a line, so a reindent does not reassign every line it touched. |
signaloptional | AbortSignalCancellation signal. |
Returns
Promise — resolving to a frozen {revision, lines} object where each line has line, originalLine, sha, author, summary.
Retrieving Diffs1
#::getLineDiffsAsync(filePath, text)
Computes gutter line diffs off the renderer thread via the git-host worker (fetching and caching the HEAD blob, diffing in JS) instead of synchronously via libgit2.
| Argument | Description |
|---|---|
filePath | The String path relative to the repository. |
text | The String to compare against the HEAD contents. |
Returns
Promise — resolving to an Array of hunk Objects, each with oldStart, newStart, oldLines, and newLines.
Checking Out2
#::checkoutHead(filePath)
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 | Description |
|---|---|
filePath | The String path to checkout. |
Returns
Promise — resolving to a Boolean that’s true on success.
#::checkoutReference(reference, create)
Checks out a branch in your repository via the repository operation provider.
| Argument | Description |
|---|---|
reference | The String reference to checkout. |
create | A Boolean value which, if true creates the new reference if it doesn’t exist. |
Returns
Promise — resolving to a Boolean that’s true on success.
Extended API
GrammarRegistrysrc/grammar-registry.js:23
This class holds the grammars used for tokenizing.
An instance of this class is always available as the lumine.grammars global.
Methods16
#::maintainLanguageMode(buffer)
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.
| Argument | Description |
|---|---|
buffer | The TextBuffer whose language mode will be maintained. |
Returns
Disposable — that can be used to stop updating the buffer’s language mode.
#::assignLanguageMode(buffer, languageId)
Force a TextBuffer to use a different grammar than the one that would otherwise be selected for it.
| Argument | Description |
|---|---|
buffer | The TextBuffer whose grammar will be set. |
languageId | The String id of the desired language. |
Returns
Boolean — that indicates whether the language was successfully found.
#::assignGrammar(buffer, grammar)
Force a TextBuffer to use a different grammar than the one that would otherwise be selected for it.
| Argument | Description |
|---|---|
buffer | The TextBuffer whose grammar will be set. |
grammar | The desired Grammar. |
Returns
Boolean — that indicates whether the assignment was successful
#::getAssignedLanguageId(buffer)
Get the languageId that has been explicitly assigned to
the given buffer, if any.
Returns
String — id of the language
#::autoAssignLanguageMode(buffer)
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 | Description |
|---|---|
buffer | The TextBuffer. |
#::selectGrammar(filePath, fileContents)
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 | Description |
|---|---|
filePath | A String file path. |
fileContents | A String of text for the file path. |
Returns
Grammar — never null.
#::getGrammarScore(grammar, filePath, contents)
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 | Description |
|---|---|
grammar | A given Grammar. |
filePath | A String path to the file. |
contents | The String contents of the file. |
Returns
Number
#::onDidAddGrammar(callback)
Invoke the given callback when a grammar is added to the registry.
| Argument | Description |
|---|---|
callback | Functionto call when a grammar is added. |
grammar | Grammarthat was added. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidUpdateGrammar(callback)
Invoke the given callback when a grammar is updated due to a grammar it depends on being added or removed from the registry.
| Argument | Description |
|---|---|
callback | Functionto call when a grammar is updated. |
grammar | Grammarthat was updated. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidRemoveGrammar(callback)
Invoke the given callback when a grammar is removed from the registry, which happens whenever the package that provides it deactivates.
| Argument | Description |
|---|---|
callback | Functionto call when a grammar is removed. |
grammar | Grammarthat was removed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::addInjectionPoint(grammarId, injectionPoint)
Specify a type of syntax node that may embed other languages.
| Argument | Description |
|---|---|
grammarId | StringThe id of the parent language. |
injectionPoint | ObjectInjection behavior. |
type | StringThe syntax-node type that may embed other languages. |
language | FunctionCalled with a matching syntax node and returns the language name tested against other grammars’ injectionRegex values. |
content | FunctionCalled with a matching syntax node and returns the node or nodes containing embedded source. The nodes become visible buffer ranges for the injected parser. |
includeChildren | 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. |
newlinesBetween | 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. |
languageScope | 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. |
coverShallowerScopes | 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. |
includeAdjacentWhitespace | 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. |
Returns
Disposable — A disposable that removes the injection point.
#::loadGrammar(grammarPath, callback)
Read a grammar asynchronously and add it to the registry.
| Argument | Description |
|---|---|
grammarPath | A String absolute file path to a grammar file. |
callback | A Function to call when loaded with the following arguments: |
error | An Error, may be null. |
grammar | A Grammar or null if an error occurred. |
#::loadGrammarSync(grammarPath)
Read a grammar synchronously and add it to this registry.
| Argument | Description |
|---|---|
grammarPath | A String absolute file path to a grammar file. |
Returns
Grammar
#::readGrammar(grammarPath, callback)
Read a grammar asynchronously but don’t add it to the registry.
| Argument | Description |
|---|---|
grammarPath | A String absolute file path to a grammar file. |
callback | A Function to call when read with the following arguments: |
error | An Error, may be null. |
grammar | A Grammar or null if an error occurred. |
Returns
undefined — undefined.
#::readGrammarSync(grammarPath)
Read a grammar synchronously but don’t add it to the registry.
| Argument | Description |
|---|---|
grammarPath | A String absolute file path to a grammar file. |
Returns
Grammar
#::getGrammars(params)
Get all the grammars in this registry.
| Argument | Description |
|---|---|
paramsoptional | Object |
includeTreeSitteroptional | BooleanSet to include Tree-sitter grammars |
Returns
Array — non-empty Array of Grammar instances.
Extended API
Guttersrc/gutter.js:13
Represents a gutter within a TextEditor.
See TextEditor#addGutter for information on creating a gutter.
Gutter Destruction1
#::destroy()
Destroys the gutter.
Event Subscription2
#::onDidChangeVisible(callback)
Calls your callback when the gutter’s visibility changes.
| Argument | Description |
|---|---|
callback | Function |
gutter | The gutter whose visibility changed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDestroy(callback)
Calls your callback when the gutter is destroyed.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Visibility4
#::hide()
Hide the gutter.
#::show()
Show the gutter.
#::isVisible()
Determine whether the gutter is visible.
Returns
Boolean
#::decorateMarker(marker, options)
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 | Description |
|---|---|
marker | A DisplayMarker you want this decoration to follow. |
options | An Object representing the decoration. It is passed to TextEditor#decorateMarker as its options argument and so supports all options documented there. |
type | 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.
Methods3
#::getProjects()
Obtain a list of previously opened projects.
Returns
Array — of HistoryProject objects, most recent first.
#::clearProjects()
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.
#::onDidChangeProjects(callback)
Invoke the given callback when the list of projects changes.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Essential API
IconRegistrysrc/icon-registry.js:211
The single source of every icon the editor renders — file-type
icons, the semantic names pane items return from getIconName(), and LSP
symbol kinds.
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.
Methods7
#::addProvider(provider, { priority = 0, id = null, core = false } = {})
Register an icon provider. Returns a Disposable.
Providers are consulted highest priority first, and equal priorities keep
registration order. iconFor(target) returns an icon descriptor, a class
string or array, or null to defer to the next provider.
#::iconFor(target, options = {})
Resolve target to an icon descriptor. Never returns null — a
target nothing answers for resolves to Icon.none().
target is an object: {path}, {name}, {kind}, or {item} for a pane
item. It may also carry a context string naming the caller and a hints
object describing what the caller already knows about the path — see
src/icon-target.js.
| Argument | Description |
|---|---|
optionsoptional, default: {} | No description. |
#::applyTo(element, target, options = {})
Render target’s icon into element and keep it current.
| Argument | Description |
|---|---|
element | ElementThe element that receives the icon. |
target | ObjectThe icon target. |
optionsoptional | ObjectRendering options. |
classesoptional | Array<String>Extra classes to add. |
nameoptional | StringAn explicit data-name. |
setDataoptional, default: true | BooleanSet data-name and data-path. |
liveoptional, default: true | BooleanRe-render when the icon changes. |
renderoptional, default: true | BooleanRender children and styles in addition to applying classes. |
skipFallbackoptional, default: false | BooleanRender nothing unless a provider above the built-in answers. |
Returns
Disposable — that removes everything the call added.
#::invalidate(scope)
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}, {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.
#::defineNames(entries)
Override the icon for one or more semantic names. Returns a
Disposable that restores the previous mapping. A null value means the
name renders no icon.
#::defineKinds(entries)
Override the icon for one or more kinds. Returns a Disposable.
#::onDidChange(callback)
Invoke callback when any icon may have changed.
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.
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
#.buildKeydownEvent(key, options)
Create a keydown DOM event for testing purposes.
| Argument | Description |
|---|---|
key | The key or keyIdentifier of the event. For example, 'a', '1', 'escape', 'backspace', etc. |
optionsoptional | An Object containing any of the following: |
ctrl | A Boolean indicating the ctrl modifier key |
alt | A Boolean indicating the alt modifier key |
shift | A Boolean indicating the shift modifier key |
cmd | A Boolean indicating the cmd modifier key |
which | A Number indicating which value of the event. See the docs for KeyboardEvent for more information. |
target | The target element of the event. |
Construction and Destruction3
#new KeymapManager(options)
Create a new KeymapManager.
| Argument | Description |
|---|---|
options | 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: |
defaultTarget | 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()
Clear all registered key bindings and enqueued keystrokes. For use in tests.
#::destroy()
Unwatch all watched paths.
Event Subscription4
#::onDidMatchBinding(callback)
Invoke the given callback when one or more keystrokes completely match a key binding.
| Argument | Description |
|---|---|
callback | Functionto be called when keystrokes match a binding. |
event | Objectwith the following keys: |
keystrokes | Stringof keystrokes that matched the binding. |
binding | KeyBindingthat the keystrokes matched. |
keyboardEventTarget | DOM element that was the target of the most recent keyboard event. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidPartiallyMatchBindings(callback)
Invoke the given callback when one or more keystrokes partially match a binding.
| Argument | Description |
|---|---|
callback | Functionto be called when keystrokes partially match a binding. |
event | Objectwith the following keys: |
keystrokes | Stringof keystrokes that matched the binding. |
partiallyMatchedBindings | KeyBindings that the keystrokes partially matched. |
keyboardEventTarget | DOM element that was the target of the most recent keyboard event. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidFailToMatchBinding(callback)
Invoke the given callback when one or more keystrokes fail to match any bindings.
| Argument | Description |
|---|---|
callback | Functionto be called when keystrokes fail to match any bindings. |
event | Objectwith the following keys: |
keystrokes | Stringof keystrokes that matched the binding. |
keyboardEventTarget | DOM element that was the target of the most recent keyboard event. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidFailToReadFile(callback)
Invoke the given callback when a keymap file not able to be loaded.
| Argument | Description |
|---|---|
callback | Functionto be called when a keymap file is unloaded. |
error | Objectwith the following keys: |
message | Stringthe error message. |
stack | Stringthe error stack trace. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Adding and Removing Bindings2
#::build(source, keyBindingsBySelector, priority, throwOnInvalidSelector)
Construct KeyBindings from an object grouping them by CSS selector.
| Argument | Description |
|---|---|
source | A String (usually a path) uniquely identifying the given bindings so they can be removed later. |
keyBindingsBySelector | ObjectBindings grouped by CSS selector, with each value mapping keystroke patterns to commands. |
priority | A Number used to sort keybindings which have the same specificity. Defaults to 0. |
throwOnInvalidSelectoroptional, default: true | BooleanWhether invalid selectors should throw. |
Returns
Array<KeyBinding> — The constructed bindings.
#::add(source, keyBindingsBySelector, priority, throwOnInvalidSelector)
Add sets of key bindings grouped by CSS selector.
| Argument | Description |
|---|---|
source | A String (usually a path) uniquely identifying the given bindings so they can be removed later. |
keyBindingsBySelector | ObjectBindings grouped by CSS selector, with each value mapping keystroke patterns to commands. |
priority | A Number used to sort keybindings which have the same specificity. Defaults to 0. |
throwOnInvalidSelectoroptional, default: true | BooleanWhether invalid selectors should throw. |
Returns
Disposable — A disposable that removes the bindings.
Accessing Bindings2
#::getKeyBindings()
Get all current key bindings.
Returns
Array — of KeyBindings.
#::findKeyBindings(params)
Get the key bindings for a given command and optional target.
| Argument | Description |
|---|---|
params | An Object whose keys constrain the binding search: |
keystrokes | A String representing one or more keystrokes, such as ‘ctrl-x ctrl-s’ |
command | A String representing the name of a command, such as ‘editor:backspace’ |
target | 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 — of key bindings.
Managing Keymap Files2
#::loadKeymap(bindingsPath, options)
Load the key bindings from the given path.
| Argument | Description |
|---|---|
bindingsPath | StringA keymap file or directory. Directories load every contained JSON or JSONC keymap. |
options | An Object containing the following optional keys: |
watch | If true, the keymap will also reload the file at the given path whenever it changes. This option cannot be used with directory paths. |
priority | A Number used to sort keybindings which have the same specificity. |
#::watchKeymap(filePath, options)
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 | Description |
|---|---|
filePath | StringThe keymap file to watch. |
options | An Object containing the following optional keys: |
priority | A Number used to sort keybindings which have the same specificity. |
Managing Keyboard Events4
#::handleKeyboardEvent(event, param)
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 | Description |
|---|---|
event | A KeyboardEvent of type ‘keydown’ |
#::keystrokeForKeyboardEvent(event)
Translate a keydown event to a keystroke string.
| Argument | Description |
|---|---|
event | A KeyboardEvent of type ‘keydown’ |
Returns
String — describing the keystroke.
#::addKeystrokeResolver(resolver)
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 | Description |
|---|---|
resolver | A Function that returns a keystroke String and is called with an object containing the following keys: |
keystroke | StringThe currently resolved keystroke string. A falsy resolver result keeps this value. |
event | The raw DOM 3 KeyboardEvent being resolved. See the DOM API documentation for more details. |
layoutName | The OS-specific name of the current keyboard layout. |
keymap | 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.
#::getPartialMatchTimeout()
Get the number of milliseconds allowed before pending states caused by partial matches of multi-keystroke bindings are terminated.
Returns
Number
Essential API
LayerDecorationsrc/layer-decoration.js:14
Represents a decoration that applies to every marker on a given layer. Created via TextEditor#decorateMarkerLayer.
Methods5
#::destroy()
Destroys the decoration.
#::isDestroyed()
Determine whether this decoration is destroyed.
Returns
Boolean
#::getProperties()
Get this decoration’s properties.
Returns
Object
#::setProperties(newProperties)
Set this decoration’s properties.
| Argument | Description |
|---|---|
newProperties | See TextEditor#decorateMarker for more information on the properties. The type of gutter and overlay are not supported on layer decorations. |
#::setPropertiesForMarker(marker, properties)
Override the decoration properties for a specific marker.
| Argument | Description |
|---|---|
marker | The DisplayMarker or Marker for which to override properties. |
properties | An Object containing properties to apply to this marker. Pass null to clear the override. |
Experimental API
MarkerLayersrc/marker-layer.js:23
A container for a related set of markers.
This API is experimental and subject to change on any release.
Lifecycle4
Marker creation2
#::markRange(range, options = {})
Create a marker with the given range.
| Argument | Description |
|---|---|
range | A Range or range-compatible Array |
options | A hash of key-value pairs to associate with the marker. There are also reserved property names that have marker-specific meaning. |
reversedoptional | BooleanCreates the marker in a reversed orientation. (default: false) |
invalidateoptional | StringDetermines 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: * 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. |
exclusive | Booleanindicating 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 behavior in all circumstances. |
#::markPosition(position, options = {})
Create a marker at with its head at the given position with no tail.
| Argument | Description |
|---|---|
position | Pointor point-compatible Array |
optionsoptional | An Object with the following keys: |
invalidateoptional | StringDetermines 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: * 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. |
exclusive | Booleanindicating 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 behavior in all circumstances. |
Event subscription3
#::onDidUpdate(callback)
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 | Description |
|---|---|
callback | A Function that will be called with no arguments when changes occur on this layer. |
#::onDidCreateMarker(callback)
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 | Description |
|---|---|
callback | A Function that will be called with a Marker whenever a new marker is created. |
#::onDidDestroy(callback)
Subscribe to be notified synchronously when this layer is destroyed.
Public API
Notificationsrc/notification.js:10
A notification to the user containing a message and type.
Event Subscription2
#::onDidDismiss(callback)
Invoke the given callback when the notification is dismissed.
| Argument | Description |
|---|---|
callback | Functionto be called when the notification is dismissed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDisplay(callback)
Invoke the given callback when the notification is displayed.
| Argument | Description |
|---|---|
callback | Functionto be called when the notification is displayed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Methods3
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
#::onDidAddNotification(callback)
Invoke the given callback after a notification has been added.
| Argument | Description |
|---|---|
callback | Functionto be called after the notification is added. |
notification | The Notification that was added. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidClearNotifications(callback)
Invoke the given callback after the notifications have been cleared.
| Argument | Description |
|---|---|
callback | Functionto be called after the notifications are cleared. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidBeep(callback)
Invoke the given callback whenever #beep is called.
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Adding Notifications7
#::addSuccess(message, options)
Add a success notification.
| Argument | Description |
|---|---|
message | A String message |
optionsoptional | An Object with the following keys: |
buttonsoptional | An Array of Object where each Object has the following options: |
classNameoptional | Stringa class name to add to the button’s default class name ( btn btn-success). |
onDidClickoptional | Functioncallback to call when the button has been clicked. The context will be set to the NotificationElement instance. |
text | Stringinner text for the button |
descriptionoptional | A Markdown String containing a longer description about the notification. By default, this will not preserve newlines and whitespace when it is rendered. |
detailoptional | A plain-text String containing additional details about the notification. By default, this will preserve newlines and whitespace when it is rendered. |
dismissableoptional | A Boolean indicating whether this notification can be dismissed by the user. Defaults to false. |
iconoptional | A String name of an icon from Octicons to display in the notification header. Defaults to 'check'. |
Returns
Notification — that was added.
#::addHint(message, options)
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 | Description |
|---|---|
message | A String message |
optionsoptional | An Object with the following keys: |
buttonsoptional | An Array of Object where each Object has the following options: |
classNameoptional | Stringa class name to add to the button’s default class name ( btn). |
onDidClickoptional | Functioncallback to call when the button has been clicked. The context will be set to the NotificationElement instance. |
text | Stringinner text for the button |
descriptionoptional | A Markdown String containing a longer description about the notification. By default, this will not preserve newlines and whitespace when it is rendered. |
detailoptional | A plain-text String containing additional details about the notification. By default, this will preserve newlines and whitespace when it is rendered. |
dismissableoptional | A Boolean indicating whether this notification can be dismissed by the user. Defaults to false. |
iconoptional | A String name of an icon from Octicons to display in the notification header. Defaults to 'light-bulb'. |
Returns
Notification — that was added.
#::addInfo(message, options)
Add an informational notification.
| Argument | Description |
|---|---|
message | A String message |
optionsoptional | An Object with the following keys: |
buttonsoptional | An Array of Object where each Object has the following options: |
classNameoptional | Stringa class name to add to the button’s default class name ( btn btn-info). |
onDidClickoptional | Functioncallback to call when the button has been clicked. The context will be set to the NotificationElement instance. |
text | Stringinner text for the button |
descriptionoptional | A Markdown String containing a longer description about the notification. By default, this will not preserve newlines and whitespace when it is rendered. |
detailoptional | A plain-text String containing additional details about the notification. By default, this will preserve newlines and whitespace when it is rendered. |
dismissableoptional | A Boolean indicating whether this notification can be dismissed by the user. Defaults to false. |
iconoptional | A String name of an icon from Octicons to display in the notification header. Defaults to 'info'. |
Returns
Notification — that was added.
#::addWarning(message, options)
Add a warning notification.
| Argument | Description |
|---|---|
message | A String message |
optionsoptional | An Object with the following keys: |
buttonsoptional | An Array of Object where each Object has the following options: |
classNameoptional | Stringa class name to add to the button’s default class name ( btn btn-warning). |
onDidClickoptional | Functioncallback to call when the button has been clicked. The context will be set to the NotificationElement instance. |
text | Stringinner text for the button |
descriptionoptional | A Markdown String containing a longer description about the notification. By default, this will not preserve newlines and whitespace when it is rendered. |
detailoptional | A plain-text String containing additional details about the notification. By default, this will preserve newlines and whitespace when it is rendered. |
dismissableoptional | A Boolean indicating whether this notification can be dismissed by the user. Defaults to false. |
iconoptional | A String name of an icon from Octicons to display in the notification header. Defaults to 'alert'. |
Returns
Notification — that was added.
#::addError(message, options)
Add an error notification.
| Argument | Description |
|---|---|
message | A String message |
optionsoptional | An Object with the following keys: |
buttonsoptional | An Array of Object where each Object has the following options: |
classNameoptional | Stringa class name to add to the button’s default class name ( btn btn-error). |
onDidClickoptional | Functioncallback to call when the button has been clicked. The context will be set to the NotificationElement instance. |
text | Stringinner text for the button |
descriptionoptional | A Markdown String containing a longer description about the notification. By default, this will not preserve newlines and whitespace when it is rendered. |
detailoptional | A plain-text String containing additional details about the notification. By default, this will preserve newlines and whitespace when it is rendered. |
dismissableoptional | A Boolean indicating whether this notification can be dismissed by the user. Defaults to false. |
iconoptional | A String name of an icon from Octicons to display in the notification header. Defaults to 'flame'. |
stackoptional | A preformatted String with stack trace information describing the location of the error. Requires detail to be set. |
Returns
Notification — that was added.
#::addFatalError(message, options)
Add a fatal error notification.
| Argument | Description |
|---|---|
message | A String message |
optionsoptional | An Object with the following keys: |
buttonsoptional | An Array of Object where each Object has the following options: |
classNameoptional | Stringa class name to add to the button’s default class name ( btn btn-error). |
onDidClickoptional | Functioncallback to call when the button has been clicked. The context will be set to the NotificationElement instance. |
text | Stringinner text for the button |
descriptionoptional | A Markdown String containing a longer description about the notification. By default, this will not preserve newlines and whitespace when it is rendered. |
detailoptional | A plain-text String containing additional details about the notification. By default, this will preserve newlines and whitespace when it is rendered. |
dismissableoptional | A Boolean indicating whether this notification can be dismissed by the user. Defaults to false. |
iconoptional | A String name of an icon from Octicons to display in the notification header. Defaults to 'bug'. |
stackoptional | A preformatted String with stack trace information describing the location of the error. Requires detail to be set. |
Returns
Notification — that was added.
#::beep()
Request audible or visual attention from notification consumers.
Getting Notifications1
#::getNotifications()
Get all the notifications.
Returns
Array — of Notifications.
Managing Notifications1
#::clear()
Clear all the notifications.
Extended API
Packagesrc/package.js:34
Loads and activates a package’s main module and resources such as stylesheets, keymaps, grammar, editor properties, and menus.
Event Subscription1
#::onDidDeactivate(callback)
Invoke the given callback when all packages have been activated.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Native Module Compatibility3
#::isCompatible()
Are all native modules depended on by this package correctly compiled against the current version of Lumine?
Incompatible packages cannot be activated.
Returns
Boolean — true if compatible, false if incompatible.
#::rebuild()
Rebuild native modules in this package’s dependencies for the current version of Lumine.
Returns
Promise — that resolves with an object containing code, stdout, and stderr properties based on the results of running lumine -p rebuild on the package.
#::getBuildFailureOutput()
If a previous rebuild failed, get the contents of stderr.
Returns
String — or null if no previous build failure occurred.
Extended API
PackageManagersrc/package-manager.js:54
Package manager for coordinating the lifecycle of Lumine packages.
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 Subscription6
#::onDidLoadInitialPackages(callback)
Invoke the given callback when all packages have been loaded.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidActivateInitialPackages(callback)
Invoke the given callback when all packages have been activated.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidActivatePackage(callback)
Invoke the given callback when a package is activated.
| Argument | Description |
|---|---|
callback | A Function to be invoked when a package is activated. |
package | The Package that was activated. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDeactivatePackage(callback)
Invoke the given callback when a package is deactivated.
| Argument | Description |
|---|---|
callback | A Function to be invoked when a package is deactivated. |
package | The Package that was deactivated. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidLoadPackage(callback)
Invoke the given callback when a package is loaded.
| Argument | Description |
|---|---|
callback | A Function to be invoked when a package is loaded. |
package | The Package that was loaded. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidUnloadPackage(callback)
Invoke the given callback when a package is unloaded.
| Argument | Description |
|---|---|
callback | A Function to be invoked when a package is unloaded. |
package | The Package that was unloaded. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Package system data1
#::getPackageDirPaths()
Get the paths being used to look for packages.
Returns
Array — of String directory paths.
General package data2
#::resolvePackagePath(name)
Resolve the given package name to a path on disk.
| Argument | Description |
|---|---|
name | The String package name. |
Returns
String — folder path or undefined if it could not be resolved.
#::isBundledPackage(name)
Is the package with the given name bundled with Lumine?
| Argument | Description |
|---|---|
name | The String package name. |
Returns
Boolean
Enabling and disabling packages3
#::enablePackage(name)
Enable the package with the given name.
| Argument | Description |
|---|---|
name | The String package name. |
Returns
Package — that was enabled or null if it isn’t loaded.
#::disablePackage(name)
Disable the package with the given name.
| Argument | Description |
|---|---|
name | The String package name. |
Returns
Package — that was disabled or null if it isn’t loaded.
#::isPackageDisabled(name)
Is the package with the given name disabled?
| Argument | Description |
|---|---|
name | The String package name. |
Returns
Boolean
Accessing active packages4
#::getActivePackages()
Get an Array of all the active Packages.
#::getActivePackage(name)
Get the active Package with the given name.
| Argument | Description |
|---|---|
name | The String package name. |
Returns
Package — or undefined.
#::isPackageActive(name)
Is the Package with the given name active?
| Argument | Description |
|---|---|
name | The String package name. |
Returns
Boolean
#::hasActivatedInitialPackages()
Returns
Boolean — indicating whether package activation has occurred.
Accessing loaded packages4
#::getLoadedPackages()
Get an Array of all the loaded Packages
#::getLoadedPackage(name)
Get the loaded Package with the given name.
| Argument | Description |
|---|---|
name | The String package name. |
Returns
Package — or undefined.
#::isPackageLoaded(name)
Is the package with the given name loaded?
| Argument | Description |
|---|---|
name | The String package name. |
Returns
Boolean
#::hasLoadedInitialPackages()
Returns
Boolean — indicating whether package loading has occurred.
Accessing available packages6
#::getAvailablePackagePaths()
Returns
Array — of Strings of all the available package paths.
#::getAvailablePackageNames()
Returns
Array — of Strings of all the available package names.
#::getAvailablePackageMetadata()
Returns
Array — of Strings of all the available package metadata.
#::getAvailablePackages(options)
| Argument | Description |
|---|---|
optionsoptional | Object |
includeShadowed | 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 — Available package descriptors that own their names, sorted by name.
#::getAvailablePackage(name)
Get the available package that owns the given name.
Returns
Object|undefined — package descriptor or undefined.
#::refreshPackageIndex()
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.
Extended API
Panesrc/pane.js:32
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.
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 Subscription15
#::onDidChangeFlexScale(callback)
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 | Description |
|---|---|
callback | Functionto be called when the pane is resized. |
flexScale | Numberrepresenting the pane’s flex-grow; ability for a flex item to grow if necessary. |
Returns
Disposable — on which ‘.dispose()’ can be called to unsubscribe.
#::observeFlexScale(callback)
Invoke the given callback with the current and future values of
getFlexScale.
| Argument | Description |
|---|---|
callback | Functionto be called with the current and future values of the getFlexScale property. |
flexScale | Numberrepresenting the panes flex-grow; ability for a flex item to grow if necessary. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidActivate(callback)
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 | Description |
|---|---|
callback | Functionto be called when the pane is activated. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onWillDestroy(callback)
Invoke the given callback before the pane is destroyed.
| Argument | Description |
|---|---|
callback | Functionto be called before the pane is destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDestroy(callback)
Invoke the given callback when the pane is destroyed.
| Argument | Description |
|---|---|
callback | Functionto be called when the pane is destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeActive(callback)
Invoke the given callback when the value of the #isActive property changes.
| Argument | Description |
|---|---|
callback | Functionto be called when the value of the #isActive property changes. |
active | Booleanindicating whether the pane is active. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeActive(callback)
Invoke the given callback with the current and future values of the #isActive property.
| Argument | Description |
|---|---|
callback | Functionto be called with the current and future values of the #isActive property. |
active | Booleanindicating whether the pane is active. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidAddItem(callback)
Invoke the given callback when an item is added to the pane.
| Argument | Description |
|---|---|
callback | Functionto be called when items are added. |
event | Objectwith the following keys: |
item | The added pane item. |
index | Numberindicating where the item is located. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidRemoveItem(callback)
Invoke the given callback when an item is removed from the pane.
| Argument | Description |
|---|---|
callback | Functionto be called when items are removed. |
event | Objectwith the following keys: |
item | The removed pane item. |
index | Numberindicating where the item was located. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onWillRemoveItem(callback)
Invoke the given callback before an item is removed from the pane.
| Argument | Description |
|---|---|
callback | Functionto be called before items are removed. |
event | Objectwith the following keys: |
item | The pane item to be removed. |
index | Numberindicating where the item is located. |
#::onDidMoveItem(callback)
Invoke the given callback when an item is moved within the pane.
| Argument | Description |
|---|---|
callback | Functionto be called when items are moved. |
event | Objectwith the following keys: |
item | The removed pane item. |
oldIndex | Numberindicating where the item was located. |
newIndex | Numberindicating where the item is now located. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeItems(callback)
Invoke the given callback with all current and future items.
| Argument | Description |
|---|---|
callback | Functionto 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.
#::onDidChangeActiveItem(callback)
Invoke the given callback when the value of #getActiveItem changes.
| Argument | Description |
|---|---|
callback | Functionto be called when the active item changes. |
activeItem | The current active item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeActiveItem(callback)
Invoke the given callback with the current and future values of #getActiveItem.
| Argument | Description |
|---|---|
callback | Functionto be called with the current and future active items. |
activeItem | The current active item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onWillDestroyItem(callback)
Invoke the given callback before items are destroyed.
| Argument | Description |
|---|---|
callback | Functionto be called before items are destroyed. |
event | Objectwith the following keys: |
item | The item that will be destroyed. |
index | The location of the item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Items29
#::getItems()
Get the items in this pane.
Returns
Array — of items.
#::getActiveItem()
Get the active pane item in this pane.
Returns
* — pane item.
#::itemAtIndex(index)
| Argument | Description |
|---|---|
index | Number |
Returns
* — The item at the index, or null when no item exists there.
#::activateNextRecentlyUsedItem()
Makes the next item in the itemStack active.
#::activatePreviousRecentlyUsedItem()
Makes the previous item in the itemStack active.
#::moveActiveItemToTopOfStack()
Moves the active item to the end of the item stack once a modifier key (typically Ctrl) is lifted.
#::activateNextItem()
Makes the next item active.
#::activatePreviousItem()
Makes the previous item active.
#::moveItemRight()
Move the active tab to the right.
#::moveItemLeft()
Move the active tab to the left
#::getActiveItemIndex()
Get the index of the active item.
Returns
Number
#::activateItemAtIndex(index)
Activate the item at the given index.
| Argument | Description |
|---|---|
index | Number |
#::activateItem(item, options = {})
Make the given item active, causing it to be displayed by the pane’s view.
| Argument | Description |
|---|---|
item | The item to activate |
optionsoptional | Object |
pendingoptional | Booleanindicating 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. |
#::addItem(item, options = {})
Add the given item to the pane.
| Argument | Description |
|---|---|
item | The item to add. It can be a model with an associated view or a view. |
optionsoptional | Object |
indexoptional | Numberindicating the index at which to add the item. If omitted, the item is added after the current active item. |
pendingoptional | Booleanindicating 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. |
Returns
* — added item.
#::togglePendingItem()
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
onDidChange is watched so that editing it clears the pending state, the
same way natively-previewed items behave. 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.
#::addItems(items, index = this.getActiveItemIndex() + 1)
Add the given items to the pane.
| Argument | Description |
|---|---|
items | 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 | Numberindex at which to add the items. If omitted, the item is # added after the current active item. |
Returns
Array — of added items.
#::moveItem(item, newIndex)
Move the given item to the given index.
| Argument | Description |
|---|---|
item | The item to move. |
newIndex | Numberindicating the index to which to move the item. |
#::moveItemToPane(item, pane, index)
Move the given item to the given index on another pane.
| Argument | Description |
|---|---|
item | The item to move. |
pane | Paneto which to move the item. |
index | Numberindicating the index to which to move the item in the given pane. |
#::destroyActiveItem()
Destroy the active item and activate the next item.
Returns
Promise — that resolves when the item is destroyed.
#::destroyItem(item, force)
Destroy the given item.
If the item is active, the next item will be activated. If the item is the
last item, the pane will be destroyed if the core.destroyEmptyPanes config
setting is true.
This action can be prevented by onWillDestroyPaneItem callbacks in which case nothing happens.
| Argument | Description |
|---|---|
item | Item to destroy |
forceoptional | BooleanDestroy the item without prompting to save it, even if the item’s isPermanentDockItem method returns true. |
Returns
Promise — that resolves with a Boolean indicating whether or not the item was destroyed.
#::destroyItems()
Destroy all items.
#::destroyInactiveItems()
Destroy all items except for the active item.
#::saveActiveItem(nextAction)
Save the active item.
#::saveActiveItemAs(nextAction)
Prompt the user for a location and save the active item with the path they select.
| Argument | Description |
|---|---|
nextActionoptional | Functionwhich will be called after the item is successfully saved. |
Returns
Promise — that resolves when the save is complete
#::saveItem(item, nextAction)
Save the given item.
| Argument | Description |
|---|---|
item | The item to save. |
nextActionoptional | Functionwhich 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 — that resolves when the save is complete, or rejects if the save could not be completed.
#::saveItemAs(item, nextAction)
Prompt the user for a location and save the active item with the path they select.
| Argument | Description |
|---|---|
item | The item to save. |
nextActionoptional | Functionwhich 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. |
#::saveItems()
Save all modified items in this pane.
Returns
Promise — that resolves when all items have been saved.
#::itemForURI(uri)
| Argument | Description |
|---|---|
uri | Stringcontaining a URI. |
Returns
*|undefined — first item that matches the given URI or undefined if none exists.
#::activateItemForURI(uri)
Activate the first item that matches the given URI.
| Argument | Description |
|---|---|
uri | Stringcontaining a URI. |
Returns
Boolean — indicating whether an item matching the URI was found.
Lifecycle4
#::isActive()
Determine whether the pane is active.
Returns
Boolean
#::activate()
Makes this pane the active pane, causing it to gain focus.
#::destroy()
Close the pane and destroy all its items.
If this is the last pane, all the items will be destroyed but the pane itself will not be destroyed.
#::isDestroyed()
Determine whether this pane has been destroyed.
Returns
Boolean
Splitting4
#::splitLeft(params)
Create a new pane to the left of this pane.
| Argument | Description |
|---|---|
paramsoptional | Objectwith the following keys: |
itemsoptional | Arrayof items to add to the new pane. |
copyActiveItemoptional | Booleantrue will copy the active item into the new split pane |
activateoptional | Booleanfalse will leave the currently active pane active instead of activating the new pane. Defaults to true. |
Returns
#::splitRight(params)
Create a new pane to the right of this pane.
| Argument | Description |
|---|---|
paramsoptional | Objectwith the following keys: |
itemsoptional | Arrayof items to add to the new pane. |
copyActiveItemoptional | Booleantrue will copy the active item into the new split pane |
activateoptional | Booleanfalse will leave the currently active pane active instead of activating the new pane. Defaults to true. |
Returns
#::splitUp(params)
Creates a new pane above the receiver.
| Argument | Description |
|---|---|
paramsoptional | Objectwith the following keys: |
itemsoptional | Arrayof items to add to the new pane. |
copyActiveItemoptional | Booleantrue will copy the active item into the new split pane |
activateoptional | Booleanfalse will leave the currently active pane active instead of activating the new pane. Defaults to true. |
Returns
#::splitDown(params)
Creates a new pane below the receiver.
| Argument | Description |
|---|---|
paramsoptional | Objectwith the following keys: |
itemsoptional | Arrayof items to add to the new pane. |
copyActiveItemoptional | Booleantrue will copy the active item into the new split pane |
activateoptional | Booleanfalse will leave the currently active pane active instead of activating the new pane. Defaults to true. |
Returns
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()
Destroy and remove this panel from the UI.
Event Subscription2
#::onDidChangeVisible(callback)
Invoke the given callback when the pane hidden or shown.
| Argument | Description |
|---|---|
callback | Functionto be called when the pane is destroyed. |
visible | Booleantrue when the panel has been shown |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDestroy(callback)
Invoke the given callback when the pane is destroyed.
| Argument | Description |
|---|---|
callback | Functionto be called when the pane is destroyed. |
panel | Panelthis panel |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Panel Details5
#::getItem()
Returns
* — panel’s item.
#::getPriority()
Returns
Number — indicating this panel’s priority.
#::isVisible()
Returns
Boolean — true when the panel is visible.
#::hide()
Hide this panel
#::show(options)
Show this panel.
| Argument | Description |
|---|---|
optionsoptional | Object |
crumb | 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.
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 return 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 must decide synchronously. The editor may be inside a native
paste ClipboardEvent, whose clipboardData is readable only for the
duration of that event, so claim the paste first and then do the slow part.
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
#::add(provider, { priority = 0 } = {})
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 | Description |
|---|---|
provider | An Object with a handlePaste(context) method. It receives exactly what #handlePaste was given, and returns true to claim the paste or false to pass it on. |
optionsoptional | ObjectRegistration options. |
priorityoptional, default: 0 | NumberThe order in which providers are consulted, highest first. Ties preserve registration order. |
Returns
Disposable — A disposable that unregisters the provider.
#::handlePaste(context)
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.
| Argument | Description |
|---|---|
context | An Object describing the paste, with the following keys: |
target | 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 | 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 | 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 | An Object of the paste options the editor would otherwise have used, such as autoIndent and normalizeLineEndings. |
Returns
Boolean — true when a provider claimed the paste and the caller must not handle it itself, false when none did.
Extended API
PathWatchersrc/path-watcher.js:671
Manage a subscription to filesystem events that occur beneath a
root directory. Construct these by calling watchPath. To watch for events
within active project directories, use Project#onDidChangeFiles instead.
Multiple PathWatchers may be backed by a single native watcher to conserve operating-system resources.
Call #dispose to stop receiving events and, if possible, release
underlying resources. A PathWatcher may be added to a CompositeDisposable
to manage its lifetime along with other Disposable resources like event
subscriptions.
const {watchPath} = require('lumine')
const disposable = await watchPath('/var/log', {}, events => {
console.log(`Received batch of ${events.length} events.`)
for (const event of events) {
// "created", "updated", "deleted", "renamed"
console.log(`Event action: ${event.action}`)
// absolute path to the filesystem entry that was touched
console.log(`Event path: ${event.path}`)
if (event.action === 'renamed') {
console.log(`.. renamed from: ${event.oldPath}`)
}
}
})
// Immediately stop receiving filesystem events. If this is the last
// watcher, asynchronously release any OS resources required to
// subscribe to these events.
disposable.dispose()
watchPath accepts the following arguments:
rootPathStringspecifies the absolute path to the root of the filesystem content to watch.optionsControl the watcher’s behavior:realPathsBooleanwhether to report the real path on disk for each event. Defaulttrue;falsereports paths that descend fromrootPatheven where symlinks point elsewhere.
eventCallbackFunctionto be called each time a batch of filesystem events is observed. Each event object has the keys:action, aStringdescribing the filesystem action that occurred, one of"created","updated","deleted", or"renamed";path, aStringcontaining the absolute path to the filesystem entry that was acted upon;oldPath(forrenamedevents only), aStringcontaining the filesystem entry’s former absolute path.
Methods3
#::getStartPromise()
PathWatchers acquired through watchPath are already started.
const {watchPath} = require('lumine')
const ROOT = path.join(__dirname, 'fixtures')
const FILE = path.join(ROOT, 'filename.txt')
describe('something', function () {
it("doesn't miss events", async function () {
const watcher = watchPath(ROOT, {}, events => {})
await watcher.getStartPromise()
fs.writeFile(FILE, 'contents\n', err => {
// The watcher is listening and the event should be
// received asynchronously
}
})
})
Returns
Promise — that will resolve when the underlying native watcher is ready to begin sending events. When testing filesystem watchers, it’s important to await this promise before making filesystem changes that you intend to assert about because there will be a delay between the instantiation of the watcher and the activation of the underlying OS resources that feed its events.
#::onDidError(callback)
Invoke a Function when any errors related to this watcher are
reported.
| Argument | Description |
|---|---|
callback | Functionto be called when an error occurs. |
err | An Error describing the failure condition. |
Returns
Disposable
#::dispose()
Unsubscribe all subscribers from filesystem events. Native resources will be released asynchronously, but this watcher will stop broadcasting events immediately.
Public API
Pointsrc/point.js:20
Represents a point in a buffer in row/column coordinates.
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
Methods1
#.fromObject(object, copy)
Convert any point-compatible object to a Point.
| Argument | Description |
|---|---|
object | This can be an object that’s already a Point, in which case it’s simply returned; or an array containing two Numbers representing the row and column. |
copy | An optional boolean indicating whether to force the copying of objects that are already points. |
Returns
Point — A point based on the given object.
Comparison9
#.min(point1, point2)
Returns
#.max(point1, point2)
Returns
#.assertValid(point)
Ensure the given Point is valid by throwing a TypeError if
either its row or its column is not an integer.
#::compare(other)
| Argument | Description |
|---|---|
other | A Point or point-compatible Array. |
Returns
Number — -1 when this point precedes the argument, 0 when they are equal, or 1 when it follows.
#::isEqual(other)
| Argument | Description |
|---|---|
other | A Point or point-compatible Array. |
Returns
Boolean — indicating whether this point has the same row and column as the given Point or point-compatible Array.
#::isLessThan(other)
| Argument | Description |
|---|---|
other | A Point or point-compatible Array. |
Returns
Boolean — indicating whether this point precedes the given Point or point-compatible Array.
#::isLessThanOrEqual(other)
| Argument | Description |
|---|---|
other | A Point or point-compatible Array. |
Returns
Boolean — indicating whether this point precedes or is equal to the given Point or point-compatible Array.
#::isGreaterThan(other)
| Argument | Description |
|---|---|
other | A Point or point-compatible Array. |
Returns
Boolean — indicating whether this point follows the given Point or point-compatible Array.
#::isGreaterThanOrEqual(other)
| Argument | Description |
|---|---|
other | A Point or point-compatible Array. |
Returns
Boolean — indicating whether this point follows or is equal to the given Point or point-compatible Array.
Construction3
Operations3
#::freeze()
Make this point immutable and return itself.
Returns
#::translate(other)
Build and return a new point by adding the rows and columns of the given point.
| Argument | Description |
|---|---|
other | A Point whose row and column will be added to this point’s row and column to build the returned point. |
Returns
#::traverse(other)
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 | Description |
|---|---|
other | A Point providing the rows and columns to traverse by. |
Returns
Conversion3
Extended API
Projectsrc/project.js:21
Represents a project that’s opened in Lumine.
An instance of this class is always available as the lumine.project global.
Event Subscription4
#::onDidChangePaths(callback)
Invoke the given callback when the project paths change.
| Argument | Description |
|---|---|
callback | Functionto be called after the project paths change. |
projectPaths | An Array of String project paths. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidAddBuffer(callback)
Invoke the given callback when a text buffer is added to the project.
| Argument | Description |
|---|---|
callback | Functionto be called when a text buffer is added. |
buffer | A TextBuffer item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeBuffers(callback)
Invoke the given callback with all current and future text buffers in the project.
| Argument | Description |
|---|---|
callback | Functionto be called with current and future text buffers. |
buffer | A TextBuffer item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeFiles(callback)
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.
Only the non-recursive watchers behind PathWatcher report renames.
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 watchPaths function instead; see PathWatcher.
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 | Description |
|---|---|
callback | Functionto be called with batches of filesystem events reported by the operating system. |
events | An Array of objects that describe a batch of filesystem events. |
action | Stringdescribing the filesystem action that occurred. One of "created", "updated", or "deleted". |
path | Stringcontaining the absolute path to the filesystem entry that was acted upon. |
Returns
Disposable — to manage this event subscription.
Accessing the git repository2
#::repositoryForDirectory(directory)
Get the repository for a given directory asynchronously.
nullif no repository can be created for the given directory.
| Argument | Description |
|---|---|
directory | Directoryfor which to get a GitRepository. |
Returns
Promise — that resolves with either: * GitRepository if a repository can be created for the given directory
#::repositoryForPath(filePath)
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. The path is resolved to its
containing Directory (a file path resolves to its parent directory), so
callers no longer need to construct a Directory themselves.
nullif no repository can be created for the given path.
| Argument | Description |
|---|---|
filePath | Stringpath of a file or directory. |
Returns
Promise — that resolves with either: * GitRepository if a repository can be created for the given path
Managing Paths10
#::getPaths()
Get an Array of Strings containing the paths of the project’s
directories.
#::setPaths(projectPaths, options = {})
Set the paths of the project’s directories.
| Argument | Description |
|---|---|
projectPaths | Arrayof String paths. |
options | An optional Object that may contain the following keys: |
mustExist | 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. |
exact | 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. |
#::setState(projectPaths)
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
LumineEnvironment.openwithnewWindowfor those. - State is keyed by the set of folders, so a project already open in another window shares one saved state with it and the last window to save wins.
- Package state is not re-applied. A package that follows the project observes #onDidChangePaths and rebuilds itself.
| Argument | Description |
|---|---|
projectPaths | Arrayof String paths to the directories the window should have open. |
Returns
Promise — 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.
#::addPath(projectPath, options = {})
Add a path to the project’s list of root paths
| Argument | Description |
|---|---|
projectPath | StringThe path to the directory to add. |
options | An optional Object that may contain the following keys: |
mustExist | If true, throw an Error if the projectPath does not exist. If false, a projectPath that does not exist is ignored. Default: false. |
exact | If true, only add projectPath if it names an existing directory. If false, if projectPath is a a file or does not exist, its parent directory will be added instead. |
#::addPaths(projectPaths, options = {})
Add multiple paths to the project’s list of root paths,
emitting a single did-change-paths event after all paths are added.
| Argument | Description |
|---|---|
projectPaths | An Array of String paths to add. |
options | An optional Object passed to #addPath for each path. |
#::getWatcherPromise(projectPath)
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 | Description |
|---|---|
projectPath | StringOne of the project’s root directories. |
Returns
Promise — that resolves with the PathWatcher associated with this project root once it has initialized and is ready to start sending events. The Promise will reject with an error instead if projectPath is not currently a root directory.
#::removePath(projectPath)
remove a path from the project’s list of root paths.
| Argument | Description |
|---|---|
projectPath | StringThe path to remove. |
#::getDirectories()
Get an Array of Directorys associated with this project.
#::relativizePath(fullPath)
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 | Description |
|---|---|
fullPath | StringAn absolute path. |
Returns
Array — with two elements:
#::contains(pathToCheck)
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 | Description |
|---|---|
pathToCheck | Stringpath |
Returns
Boolean — whether the path is inside the project’s root directory.
Crawling files8
#::crawl(options = {})
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 | Description |
|---|---|
optionsoptional | Object |
didFindPaths | Functioncalled with an Array of absolute paths as they are found. Called several times over the life of one crawl. |
directoryPaths | an Array of String paths to crawl. Defaults to the project’s root directories. |
inclusion | Stringglob scoping the crawl. ** means “everything”. |
ignoredNames | an Array of String globs to exclude. Defaults to core.ignoredNames. |
followSymlinks | Booleanwhether to descend into symlinked directories. Defaults to core.followSymlinks. |
excludeVcsIgnoredPaths | Booleanwhether to honor VCS ignore files. Defaults to core.excludeVcsIgnoredPaths. Only takes effect inside a repository — a directory with no .git above it lists everything. |
sort | Booleanwhether 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.
#::observeFilePaths(callback)
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 | Description |
|---|---|
callback | Functionto be called with each batch of changes. |
added | An Array of String absolute paths new to the index. |
removed | An Array of String absolute paths no longer in it. |
indexing | A Boolean, true while a crawl is still running. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::getFilePaths()
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 — of String absolute paths.
#::getFilePathsForRoot(root)
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 | Description |
|---|---|
root | String|Directorya project root path, or its Directory. |
Returns
Array — of String absolute paths, empty for a path that is not a project root.
#::hasFilePath(filePath)
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 | Description |
|---|---|
filePath | Stringan absolute path. |
Returns
Boolean
#::getFilePathCount()
How many files are indexed.
Cheaper than getFilePaths().length, which materializes the array.
Returns
Number
#::isIndexing()
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
#::refreshFilePaths(options = {})
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 | Description |
|---|---|
optionsoptional | Object |
rootPaths | An Array of String roots to re-crawl. Defaults to all of them. |
Returns
Promise — that resolves when the crawl settles.
Public API
Rangesrc/range.js:32
Represents a region in a buffer in row/column coordinates.
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
#.fromObject(object, copy)
Convert any range-compatible object to a Range.
| Argument | Description |
|---|---|
object | |
copy | An optional boolean indicating whether to force the copying of objects that are already ranges. |
Returns
Range — A range based on the given object.
#new Range(pointA, pointB)
Construct a Range object
#::copy()
Returns
Range — new range with the same start and end positions.
#::negate()
Returns
Range — new range with the start and end positions negated.
Serialization and Deserialization2
#.deserialize(array)
Call this with the result of Range#serialize to construct a new Range.
| Argument | Description |
|---|---|
array | Arrayof params to pass to the #constructor |
#::serialize()
Returns
Object — plain JavaScript object representation of the range.
Range Details4
#::isEmpty()
Is the start position of this range equal to the end position?
Returns
Boolean
#::isSingleLine()
Returns
Boolean — indicating whether this range starts and ends on the same row.
#::getRowCount()
Get the number of rows in this range.
Returns
Number
#::getRows()
Returns
Array — array of all rows in the range.
Operations4
#::freeze()
Freezes the range and its start and end point so it becomes immutable and returns itself.
Returns
#::union(otherRange)
| Argument | Description |
|---|---|
otherRange | A Range or range-compatible Array |
Returns
Range — new range that contains this range and the given range.
#::translate(startDelta, endDelta)
Build and return a new range by translating this range’s start and end points by the given delta(s).
| Argument | Description |
|---|---|
startDelta | A Point by which to translate the start of this range. |
endDeltaoptional | A Point to by which to translate the end of this range. If omitted, the startDelta will be used instead. |
Returns
#::traverse(delta)
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 | Description |
|---|---|
delta | A Point containing the rows and columns to traverse to derive the new range. |
Returns
Comparison8
#::compare(other)
Compare two Ranges
| Argument | Description |
|---|---|
other | A Range or range-compatible Array. |
Returns
Number — -1 when this range starts first, 0 when the ranges are equal, or 1 when the argument starts first.
#::isEqual(other)
| Argument | Description |
|---|---|
other | A Range or range-compatible Array. |
Returns
Boolean — indicating whether this range has the same start and end points as the given Range or range-compatible Array.
#::coversSameRows(other)
| Argument | Description |
|---|---|
other | A Range or range-compatible Array. |
Returns
Boolean — indicating whether this range starts and ends on the same row as the argument.
#::intersectsWith(otherRange, exclusive)
Determines whether this range intersects with the argument.
| Argument | Description |
|---|---|
otherRange | A Range or range-compatible Array |
exclusiveoptional | Booleanindicating whether to exclude endpoints when testing for intersection. Defaults to false. |
Returns
Boolean
#::containsRange(otherRange, exclusive)
| Argument | Description |
|---|---|
otherRange | A Range or range-compatible Array |
exclusiveoptional | Booleanincluding that the containment should be exclusive of endpoints. Defaults to false. |
Returns
Boolean — indicating whether this range contains the given range.
#::containsPoint(point, exclusive)
| Argument | Description |
|---|---|
point | A Point or point-compatible Array |
exclusiveoptional | Booleanincluding that the containment should be exclusive of endpoints. Defaults to false. |
Returns
Boolean — indicating whether this range contains the given point.
#::intersectsRow(row)
| Argument | Description |
|---|---|
row | Row Number |
Returns
Boolean — indicating whether this range intersects the given row Number.
#::intersectsRowRange(startRow, endRow)
| Argument | Description |
|---|---|
startRow | Numberstart row |
endRow | Numberend row |
Returns
Boolean — indicating whether this range intersects the row range indicated by the given startRow and endRow Numbers.
Conversion1
#::toString()
Returns
String — string representation of the range.
Public API
RepositoryRegistrysrc/repository-registry.js:145
Every Git repository this window knows about, available as
lumine.repositories.
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
#::getActiveRepository()
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 — or null when the active item belongs to none.
#::getActiveRepositoryContext()
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.
#::isActiveRepositoryPinned()
Whether the active repository is pinned to a manual selection.
Returns
Boolean
#::onDidChangeActiveRepository(callback)
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 | Description |
|---|---|
callback | Functioncalled with the context #getActiveRepositoryContext |
Returns
Disposable — A subscription that can be disposed to unsubscribe.
#::observeActiveRepository(callback)
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 | Description |
|---|---|
callback | Functioncalled with the context #getActiveRepositoryContext |
Returns
Disposable — A subscription that can be disposed to unsubscribe.
#::setActiveRepository(repository, { pin = false } = {})
Select the active repository manually.
Throws a TypeError if the repository is unregistered or destroyed.
| Argument | Description |
|---|---|
repository | The GitRepository to activate, or null to clear any pin and recompute the active repository from the workspace. |
optionsoptional | ObjectActivation options. |
pinoptional, default: false | BooleanKeep the selection until it is cleared instead of following the next pane-item change. |
#::setActiveRepositoryForPath(filePath, { pin = false } = {})
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 | Description |
|---|---|
filePath | The String path to resolve. |
optionsoptional | ObjectActivation options. |
pinoptional, default: false | BooleanKeep the selection as in #setActiveRepository. |
Returns
Promise — that resolves to the GitRepository, or to null when the path is not in one.
Accessing Repositories3
#::getSnapshot()
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.
#::getRepositories()
Every registered repository.
This is a snapshot. Use #observeRepositories to keep up with the ones registered later.
Returns
Array — of GitRepository.
#::getById(id)
Look a repository up by the id the registry gave it.
| Argument | Description |
|---|---|
id | The String id. |
Returns
GitRepository — or null if nothing is registered under it.
Event Subscription9
#::observeRepositories(callback)
Invoke the callback with every registered repository, now and in the future.
| Argument | Description |
|---|---|
callback | Functioncalled with each GitRepository. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidAddRepository(callback)
Invoke the callback when a repository is registered.
| Argument | Description |
|---|---|
callback | Functioncalled with the new GitRepository. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidRemoveRepository(callback)
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 | Description |
|---|---|
callback | Functioncalled with the removed GitRepository. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChange(callback)
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 | Description |
|---|---|
callback | Functioncalled with a frozen Object. |
version | The Number the registry is now at. |
added | An Array of newly registered GitRepository. |
removed | An Array of GitRepository no longer registered. |
updated | An Array of GitRepository whose routing changed. |
rootsAdded | An Array of String project roots added. |
rootsRemoved | An Array of String project roots removed. |
routingChangedPrefixes | 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.
#::onDidStartRescan(callback)
Invoke the callback when a rescan of the project roots begins.
| Argument | Description |
|---|---|
callback | Functioncalled with a frozen Object. |
id | A Number identifying this rescan. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidFinishRescan(callback)
Invoke the callback when a rescan finishes, whether or not it succeeded.
| Argument | Description |
|---|---|
callback | Functioncalled with a frozen Object. |
id | The Number of the rescan that started. |
repositories | A frozen Array of the GitRepository it found. |
error | The Error that ended the scan, or null. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidQueueOperation(callback)
Invoke the callback when an operation is queued behind another on the same repository.
| Argument | Description |
|---|---|
callback | Functioncalled with an operation snapshot; see #getPendingOperations. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidStartOperation(callback)
Invoke the callback when an operation starts running.
| Argument | Description |
|---|---|
callback | Functioncalled with an operation snapshot; see #getPendingOperations. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidFinishOperation(callback)
Invoke the callback when an operation finishes, whether or not it succeeded.
| Argument | Description |
|---|---|
callback | Functioncalled with an operation snapshot; see #getPendingOperations. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Resolving Paths5
#::getForPath(filePath)
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 | Description |
|---|---|
filePath | The String path to look up. |
Returns
GitRepository — or null.
#::resolveForPath(filePath)
The repository a path belongs to, discovering and registering one if it is not known yet.
| Argument | Description |
|---|---|
filePath | The String path to resolve. |
Returns
Promise — that resolves to a GitRepository, or to null when the path is not in one.
#::resolveForPathSync(filePath)
#resolveForPath, synchronously.
Discovery reads the filesystem, so this blocks the renderer. Prefer #getForPath when the repository is expected to be known already, and #resolveForPath when it is not.
| Argument | Description |
|---|---|
filePath | The String path to resolve. |
Returns
GitRepository — or null.
#::resolveDirectory(directory)
The repository for a Directory, discovering and registering one
if it is not known yet.
| Argument | Description |
|---|---|
directory | The Directory to resolve. |
Returns
Promise — that resolves to a GitRepository, or to null.
#::resolveDirectorySync(directory)
#resolveDirectory, synchronously. Reads the filesystem.
| Argument | Description |
|---|---|
directory | The Directory to resolve. |
Returns
GitRepository — or null.
Managing Repositories4
#::retain(repository, source = "pin")
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 | Description |
|---|---|
repository | The GitRepository to hold. |
sourceoptional | A String label for the hold, for debugging. |
Returns
Disposable — that releases the hold.
#::runOperation(repository, operation)
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 | Description |
|---|---|
repository | The GitRepository to work with. |
operation | An async Function called with the repository. |
Returns
Promise — for whatever the operation returned.
#::add(filePath, { persist = true } = {})
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 | Description |
|---|---|
filePath | The String path inside the repository to add. |
optionsoptional | ObjectRegistration options. |
persistoptional, default: true | BooleanRemember the repository across window reloads. Pass false to keep it for this session only. |
Returns
Promise — that resolves to an Object, or to null when the path is not in a repository.
#::forget(repository)
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 | Description |
|---|---|
repository | The GitRepository to forget. |
Returns
Boolean — true if the repository was registered.
Operations5
#::addOperationProvider(provider, { fallback = false } = {})
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 | Description |
|---|---|
provider | The Object implementing the operations. |
optionsoptional | ObjectProvider options. |
fallbackoptional, default: false | BooleanPut the provider last so later registrations take precedence. |
Returns
Disposable — that removes the provider and everything it implemented.
#::getOperations(repository)
The operations available on a repository.
| Argument | Description |
|---|---|
repository | The GitRepository. |
Returns
Object — of operation functions, or null when no provider has claimed the repository.
#::canPerformOperation(repository, operationName)
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 | Description |
|---|---|
repository | The GitRepository. |
operationName | The String name of the operation, such as "commit". |
Returns
Boolean
#::getOperationCapabilities(repository)
Every operation any provider can perform on a repository.
| Argument | Description |
|---|---|
repository | The GitRepository. |
Returns
Array — frozen Array of String operation names.
#::getPendingOperations(repository)
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 | Description |
|---|---|
repository | The GitRepository it runs on, or null. |
Returns
Array — frozen Array of frozen Objects.
Creating Repositories4
#::getWorkspaceOperationCapabilities()
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 — frozen Array of String operation names.
#::canPerformWorkspaceOperation(operationName)
Whether a repository-creating operation can be performed.
| Argument | Description |
|---|---|
operationName | A String, "initialize" or "clone". |
Returns
Boolean
#::initialize(directoryPath, options)
Create a repository in a directory and register it.
| Argument | Description |
|---|---|
directoryPath | The String directory to initialize. |
optionsoptional | Objectpassed through to the provider. |
Returns
Promise — 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(remoteUrl, destinationPath, options)
Clone a remote into a directory and register the result.
| Argument | Description |
|---|---|
remoteUrl | The String URL to clone. |
destinationPath | The String directory to clone into. |
optionsoptional | Objectpassed through to the provider. |
Returns
Promise — that resolves to the new GitRepository, and rejects the same way #initialize does.
Running Git3
#::canExecuteGitCommands()
Whether any provider can run raw Git commands.
Returns
Boolean
#::executeGit(args, workingDirectory, options)
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 | Description |
|---|---|
args | An Array of String arguments, without the leading git. |
workingDirectory | The String directory to run in. |
optionsoptional | Objectpassed 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.
#::getGitExecutablePath()
The Git binary the active provider runs.
Returns
String — path, or null when no provider runs Git commands or it does not say which binary it uses.
Public API
RuntimeServicesrc/runtime-service.js:7
Renderer-runtime readiness and unhandled-error events.
Methods4
#::onWillThrowError(callback)
Subscribe before an unhandled renderer error is reported.
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidThrowError(callback)
Subscribe after an unhandled renderer error is reported.
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::whenShellEnvironmentLoaded()
Wait until the current renderer has loaded its shell environment.
Returns
Promise — that resolves once environment loading is complete.
#::getShellLoadTime()
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.
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.
Construction and Destruction2
#new ScopeDescriptor({ scopes })
Create a ScopeDescriptor object.
| Argument | Description |
|---|---|
object | ObjectScope data. |
scopes | Array<String>The ordered syntax scopes. |
#::getScopesArray()
Returns
Array — of Strings
Public API
SecretStoresrc/secret-store.js:35
Somewhere to keep an access token, available as lumine.secrets.
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.
Storing Secrets4
#::isEncryptionAvailable()
Whether the operating system will encrypt what is stored.
When it will not, secrets last for this session only. Worth checking before telling the user that a token has been saved — the first call warns them once on its own.
Returns
Promise — resolving to a Boolean.
#::get(key)
Read a secret.
| Argument | Description |
|---|---|
key | The String key it was stored under. |
Returns
Promise — 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.
#::set(key, value)
Store a secret.
| Argument | Description |
|---|---|
key | The String key to store it under. |
value |
Returns
Promise — that resolves once the value is written.
#::delete(key)
Forget a secret.
Deleting a key that was never stored is not an error and emits nothing.
| Argument | Description |
|---|---|
key | The String key to remove. |
Returns
Promise — that resolves once the key is gone.
Event Subscription1
#::onDidChange(callback)
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 | Description |
|---|---|
callback | Functioncalled with an Object. |
key | The String key that changed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Extended API
Selectionsrc/selection.js:14
Represents a selection in the TextEditor.
Event Subscription2
#::onDidChangeRange(callback)
Calls your callback when the selection was moved.
| Argument | Description |
|---|---|
callback | Function |
event | Object |
oldBufferRange | |
oldScreenRange | |
newBufferRange | |
newScreenRange | |
selection | Selectionthat triggered the event |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDestroy(callback)
Calls your callback when the selection was destroyed
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Managing the selection range5
#::getScreenRange()
Returns
#::setScreenRange(screenRange, options)
Modifies the screen range for the selection.
| Argument | Description |
|---|---|
screenRange | The new Range to use. |
optionsoptional | Objectoptions matching those found in #setBufferRange. |
#::getBufferRange()
Returns
#::setBufferRange(bufferRange, options = {})
Modifies the buffer Range for the selection.
| Argument | Description |
|---|---|
bufferRange | The new Range to select. |
optionsoptional | Objectwith the keys: |
reversed | Booleanindicating whether to set the selection in a reversed orientation. |
preserveFolds | if true, the fold settings are preserved after the selection moves. |
autoscroll | Booleanindicating whether to autoscroll to the new range. Defaults to true if this is the most recently added selection, false otherwise. |
#::getBufferRowRange()
Returns
Array<Number> — The starting and ending buffer rows highlighted by the selection.
Info about the selection6
#::isEmpty()
Determines if the selection contains anything.
#::isReversed()
Determines if the ending position of a marker is greater than the starting position.
This can happen when, for example, you highlight text “up” in a TextBuffer.
#::isSingleScreenLine()
Returns
Boolean — whether the selection is a single line or not.
#::getText()
Returns
String — text in the selection.
#::intersectsBufferRange(bufferRange)
Identifies if a selection intersects with a given buffer range.
| Argument | Description |
|---|---|
bufferRange | A Range to check against. |
Returns
Boolean
#::intersectsWith(otherSelection, exclusive)
Identifies if a selection intersects with another selection.
| Argument | Description |
|---|---|
otherSelection | A Selection to check against. |
Returns
Boolean
Managing multiple selections3
#::addSelectionBelow()
Moves the selection down one row.
#::addSelectionAbove()
Moves the selection up one row.
#::merge(otherSelection, options = {})
Combines the given selection into this selection and then destroys the given selection.
| Argument | Description |
|---|---|
otherSelection | A Selection to merge with. |
optionsoptional | Objectoptions matching those found in #setBufferRange. |
Comparing to other selections1
#::compare(otherSelection)
Compare this selection’s buffer range to another selection’s buffer range.
See Range#compare for more details.
| Argument | Description |
|---|---|
otherSelection | A Selection to compare against |
Public API
ServiceHubsrc/service-hub.js:151
Methods4
#::provide(keyPath, version, service)
Provide a service by invoking the callback of all current and future consumers matching the given service name and version range.
| Argument | Description |
|---|---|
keyPath | 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 | A String containing a semantic version for the service’s API. |
service | An object exposing the service API. |
Returns
Disposable — on which .dispose() can be called to remove the provided service.
#::consume(keyPath, versionRange, callback)
Consume a service by invoking the given callback for all current and future provided services matching the given service name and version range.
| Argument | Description |
|---|---|
keyPath | A String naming the service. Names are matched exactly; see #provide. |
versionRange | A String containing a semantic version range that any provided services for the given service name must satisfy. |
callback | A Function to be called with current and future matching service objects. |
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.
#::unmatchedConsumers()
Names consumed by someone and provided by no one.
Deliberately not reported on its own: packages activate lazily, so a
consumer with no provider yet is ordinary. 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. Nothing makes the check statically
either, so this is the only place the question is answered at all.
Returns
Array — of {keyPath, versionRange}.
#::clear()
Clear out all service consumers and providers, disposing of any disposables returned by previous consumers.
Public API
ShellServicesrc/shell-service.js:7
Operating-system shell integrations.
Methods4
#::trashItem(filePath)
Move an item to the operating system trash.
Returns
Promise — that resolves when the operation completes.
#::showItemInFolder(filePath)
Reveal a path in the operating system file browser.
Returns
Promise — that resolves when the request completes.
#::openPath(filePath)
Open a path with its operating system default application.
Returns
Promise — resolving to Electron’s result string.
#::openExternal(url)
Open a URL with its operating system default handler.
Returns
Promise — that resolves when the request completes.
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
#::observeStyleElements(callback)
Invoke callback for all current and future style elements.
| Argument | Description |
|---|---|
callback | Functionthat is called with style elements. |
styleElement | 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 | A String containing the path from which the style element was loaded. |
context | A String indicating the target context of the style element. |
Returns
Disposable — on which .dispose() can be called to cancel the subscription.
#::onDidAddStyleElement(callback)
Invoke callback when a style element is added.
| Argument | Description |
|---|---|
callback | Functionthat is called with style elements. |
styleElement | 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 | A String containing the path from which the style element was loaded. |
context | A String indicating the target context of the style element. |
Returns
Disposable — on which .dispose() can be called to cancel the subscription.
#::onDidRemoveStyleElement(callback)
Invoke callback when a style element is removed.
| Argument | Description |
|---|---|
callback | Functionthat is called with style elements. |
styleElement | An HTMLStyleElement instance. |
Returns
Disposable — on which .dispose() can be called to cancel the subscription.
#::onDidUpdateStyleElement(callback)
Invoke callback when an existing style element is updated.
| Argument | Description |
|---|---|
callback | Functionthat is called with style elements. |
styleElement | 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 | A String containing the path from which the style element was loaded. |
context | 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
#::getStyleElements()
Get all loaded style elements.
Paths1
#::getUserStyleSheetPath()
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.
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();
};
Methods7
#.once(taskPath, ...args)
A helper method to easily launch and run a task once.
| Argument | Description |
|---|---|
taskPath | The String path to the CoffeeScript/JavaScript file which exports a single Function to execute. |
...args | The arguments to pass to the exported function. |
#new Task(taskPath)
Creates a task. You should probably use {.once}
| Argument | Description |
|---|---|
taskPath | The String path to the CoffeeScript/JavaScript file that exports a single Function to execute. |
#::start(...args)
Starts the task.
Throws an error if this task has already been terminated or if sending a message to the child process fails.
| Argument | Description |
|---|---|
...args | ...*Arguments passed to the function exported by the task script. |
callbackoptional | FunctionCalled when the task completes. |
#::send(message)
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 | Description |
|---|---|
message | The message to send to the task. |
#::on(eventName, callback)
Call a function when an event is emitted by the child process
| Argument | Description |
|---|---|
eventName | The String name of the event to handle. |
callback | The Function to call when the event is emitted. |
Returns
Disposable — that can be used to stop listening for the event.
#::terminate()
Forcefully stop the running task.
No more events are emitted once this method is called.
Returns
Boolean — indicating whether the task was terminated.
#::cancel()
Cancel the running task and emit an event if it was canceled.
Returns
Boolean — indicating whether the task was terminated.
Extended API
TextBuffersrc/text-buffer.js:74
A mutable text container with undo/redo support and the ability to annotate logical regions in the text.
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)
}
})
Construction4
#new TextBuffer(params)
Create a new buffer with the given params.
| Argument | Description |
|---|---|
params | Objector String of text |
text | The initial String text of the buffer. |
shouldDestroyOnFileDelete | A Function that returns a Boolean indicating whether the buffer should be destroyed if its file is deleted. |
#.load(source, params)
Create a new buffer backed by the given file path.
| Argument | Description |
|---|---|
source | Either a String path to a local file or (experimentally) a file Object as described by the #setFile method. |
params | An Object with the following properties: |
encodingoptional | StringThe file’s encoding. |
shouldDestroyOnFileDeleteoptional | A Function that returns a Boolean indicating whether the buffer should be destroyed if its file is deleted. |
Returns
Promise — that resolves with a TextBuffer instance.
#.loadSync(filePath, params)
Create a new buffer backed by the given file path. For better performance, use TextBuffer.load instead.
| Argument | Description |
|---|---|
filePath | The String file path. |
params | An Object with the following properties: |
encodingoptional | StringThe file’s encoding. |
shouldDestroyOnFileDeleteoptional | A Function that returns a Boolean indicating whether the buffer should be destroyed if its file is deleted. |
Returns
TextBuffer — instance.
#.deserialize(params)
Restore a TextBuffer based on an earlier state created using
the TextBuffer.serialize method.
| Argument | Description |
|---|---|
params | An Object returned from TextBuffer.serialize |
Returns
Promise — that resolves with a TextBuffer instance.
Event Subscription18
#::onWillChange(callback)
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.
| Argument | Description |
|---|---|
callback | Functionto be called when the buffer changes. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChange(callback)
Invoke the given callback synchronously when a transaction finishes with a list of all the changes in the transaction.
| Argument | Description |
|---|---|
callback | Functionto be called when a transaction in which textual changes occurred is completed. |
event | Objectwith the following keys: |
oldRange | The smallest combined Range containing all of the old text. |
newRange | The smallest combined Range containing all of the new text. |
changes | Arrayof 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 | 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 | The Range of the inserted text in the current contents of the buffer. |
oldText | A String representing the deleted text. |
newText | A String representing the inserted text. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeText(callback)
This is now identical to #onDidChange.
#::onDidStopChanging(callback)
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 | Description |
|---|---|
callback | Functionto be called when the buffer stops changing. |
event | Objectwith the following keys: |
changes | An Array containing Objects summarizing the aggregated changes. See Working With Aggregated Changes in the description of the TextBuffer class for details. |
oldRange | 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 | The Range of the inserted text in the current contents of the buffer. |
oldText | A String representing the deleted text. |
newText | A String representing the inserted text. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidConflict(callback)
Invoke the given callback when the in-memory contents of the buffer become in conflict with the contents of the file on disk.
| Argument | Description |
|---|---|
callback | Functionto be called when the buffer enters conflict. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeModified(callback)
Invoke the given callback if the value of #isModified changes.
| Argument | Description |
|---|---|
callback | Functionto be called when #isModified changes. |
modified | Booleanindicating whether the buffer is modified. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidUpdateMarkers(callback)
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 | Description |
|---|---|
callback | Functionto be called after markers are updated. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidCreateMarker(callback)
Invoke the given callback when a marker is created.
| Argument | Description |
|---|---|
callback | Functionto be called when a marker is created. |
marker | Markerthat was created. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangePath(callback)
Invoke the given callback when the value of #getPath changes.
| Argument | Description |
|---|---|
callback | Functionto be called when the path changes. |
path | Stringrepresenting the buffer’s current path on disk. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeEncoding(callback)
Invoke the given callback when the value of #getEncoding changes.
| Argument | Description |
|---|---|
callback | Functionto be called when the encoding changes. |
encoding | Stringcharacter set encoding of the buffer. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onWillSave(callback)
Invoke the given callback before the buffer is saved to disk.
| Argument | Description |
|---|---|
callback | Functionto 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.
#::onDidSave(callback)
Invoke the given callback after the buffer is saved to disk.
| Argument | Description |
|---|---|
callback | Functionto be called after the buffer is saved. |
event | Objectwith the following keys: |
path | The path to which the buffer was saved. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDelete(callback)
Invoke the given callback after the file backing the buffer is deleted.
| Argument | Description |
|---|---|
callback | Functionto be called after the buffer is deleted. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onWillReload(callback)
Invoke the given callback before the buffer is reloaded from the contents of its file on disk.
| Argument | Description |
|---|---|
callback | Functionto be called before the buffer is reloaded. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidReload(callback)
Invoke the given callback after the buffer is reloaded from the contents of its file on disk.
| Argument | Description |
|---|---|
callback | Functionto be called after the buffer is reloaded. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDestroy(callback)
Invoke the given callback when the buffer is destroyed.
| Argument | Description |
|---|---|
callback | Functionto be called when the buffer is destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onWillThrowWatchError(callback)
Invoke the given callback when there is an error in watching the file.
| Argument | Description |
|---|---|
callback | Functioncallback |
errorObject | Object |
error | Objectthe error object |
handle | Functioncall 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.
#::getStoppedChangingDelay()
Get the number of milliseconds that will elapse without a change before #onDidStopChanging observers are invoked following a change.
Returns
Number
File Details9
#::isModified()
Determine if the in-memory contents of the buffer differ from its contents on disk.
If the buffer is unsaved, always returns true unless the buffer is empty.
Returns
Boolean
#::isDeleted()
Determine if the buffer is in a deleted state — meaning that it was previously backed by a file on disk, but is no longer.
#::isInConflict()
Determine if the in-memory contents of the buffer conflict with the on-disk contents of its associated file.
This happens if the contents of a buffer’s backing file change while the editor has uncommitted changes. Those uncommitted changes build upon a state that is now stale; if those changes were committed to disk, it could clobber the changes made by the external program.
Returns
Boolean
#::getPath()
Get the path of the associated file.
Returns
String
#::setPath(filePath)
Set the path for the buffer’s associated file.
| Argument | Description |
|---|---|
filePath | A String representing the new file path |
#::setFile(file)
Set a custom File object as the buffer’s backing store.
| Argument | Description |
|---|---|
file | An Object with the following properties: |
getPath | A Function that returns the String path to the file. |
createReadStream | A Function that returns a Readable stream that can be used to load the file’s content. |
createWriteStream | A Function that returns a Writable stream that can be used to save content to the file. |
existsSync | A Function that returns a Boolean, true if the file exists, false otherwise. |
onDidChangeoptional | 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 | 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 | 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. |
#::setEncoding(encoding = "utf8")
Sets the character set encoding for this buffer.
| Argument | Description |
|---|---|
encoding | The String encoding to use (default: ‘utf8’). |
#::getEncoding()
Returns
String — encoding of this buffer.
#::getUri()
Get the path of the associated file.
Returns
String
Reading Text12
#::isEmpty()
Determine whether the buffer is empty.
Returns
Boolean
#::getText()
Get the entire text of the buffer. Avoid using this unless you know that the buffer’s text is reasonably short.
Returns
String
#::getTextInRange(range)
Get the text in a range.
| Argument | Description |
|---|---|
range | A Range |
Returns
String
#::getLines()
Get the text of all lines in the buffer, without their line endings.
Returns
Array — of Strings.
#::getLastLine()
Get the text of the last line of the buffer, without its line ending.
Returns
String
#::lineForRow(row)
Get the text of the line at the given 0-indexed row, without its line ending.
| Argument | Description |
|---|---|
row | A Number representing the row. |
Returns
String
#::lineEndingForRow(row)
Get the line ending for the given 0-indexed row.
| Argument | Description |
|---|---|
row | 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.
#::lineLengthForRow(row)
Get the length of the line for the given 0-indexed row, without its line ending.
| Argument | Description |
|---|---|
row | A Number indicating the row. |
Returns
Number
#::isRowBlank(row)
Determine if the given row contains only whitespace.
| Argument | Description |
|---|---|
row | A Number representing a 0-indexed row. |
Returns
Boolean
#::previousNonBlankRow(startRow)
Given a row, find the first preceding row that’s not blank.
| Argument | Description |
|---|---|
startRow | A Number identifying the row to start checking at. |
Returns
Number — or null if there’s no preceding non-blank row.
#::nextNonBlankRow(startRow)
Given a row, find the next row that’s not blank.
| Argument | Description |
|---|---|
startRow | A Number identifying the row to start checking at. |
Returns
Number — or null if there’s no next non-blank row.
#::hasAstral()
Returns
Boolean — Whether the buffer contains astral-plane Unicode characters encoded as surrogate pairs.
Mutating Text8
#::setText(text)
Replace the entire contents of the buffer with the given text.
| Argument | Description |
|---|---|
text | A String |
Returns
Range — spanning the new buffer contents.
#::setTextViaDiff(text)
Replace the current buffer contents by applying a diff based on the given text.
| Argument | Description |
|---|---|
text | A String containing the new buffer contents. |
#::setTextInRange(range, newText, options)
Set the text in the given range.
| Argument | Description |
|---|---|
range | A Range |
newText | A String |
optionsoptional | Object |
normalizeLineEndingsoptional | Boolean(default: true) |
undooptional | 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.
#::insert(position, text, options)
Insert text at the given position.
| Argument | Description |
|---|---|
position | A Point representing the insertion location. The position is clipped before insertion. |
text | A String representing the text to insert. |
optionsoptional | Object |
normalizeLineEndingsoptional | Boolean(default: true) |
undooptional | Deprecated String ‘skip’ will skip the undo system. This property is deprecated. Call groupLastChanges() on the TextBuffer afterward instead. |
Returns
Range — of the inserted text.
#::append(text, options)
Append text to the end of the buffer.
| Argument | Description |
|---|---|
text | A String representing the text to append. |
optionsoptional | Object |
normalizeLineEndingsoptional | Boolean(default: true) |
undooptional | Deprecated String ‘skip’ will skip the undo system. This property is deprecated. Call groupLastChanges() on the TextBuffer afterward instead. |
Returns
Range — of the inserted text
#::delete(range)
Delete the text in the given range.
| Argument | Description |
|---|---|
range | A Range in which to delete. The range is clipped before deleting. |
Returns
#::deleteRow(row)
Delete the line associated with a specified 0-indexed row.
| Argument | Description |
|---|---|
row | A Number representing the row to delete. |
Returns
Range — of the deleted text.
#::deleteRows(startRow, endRow)
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 | Description |
|---|---|
startRow | A Number representing the first row to delete. |
endRow | A Number representing the last row to delete, inclusive. |
Returns
Range — of the deleted text.
Markers9
#::addMarkerLayer(options)
Create a layer to contain a set of related markers.
| Argument | Description |
|---|---|
optionsoptional | An Object containing the following keys: |
maintainHistoryoptional | A Boolean indicating whether or not the state of this layer should be restored on undo/redo operations. Defaults to false. |
persistentoptional | 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 | A String indicating role of this marker layer |
Returns
#::getMarkerLayer(id)
Get a MarkerLayer by id.
| Argument | Description |
|---|---|
id | The id of the marker layer to retrieve. |
Returns
MarkerLayer — or undefined if no layer exists with the given id.
#::getDefaultMarkerLayer()
Get the default MarkerLayer.
All Marker APIs not tied to an explicit layer interact with this default
layer.
Returns
#::markRange(range, properties)
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 | Description |
|---|---|
range | A Range or range-compatible Array |
propertiesoptional | A hash of key-value pairs to associate with the marker. There are also reserved property names that have marker-specific meaning. |
reversedoptional | BooleanCreates the marker in a reversed orientation. (default: false) |
invalidateoptional | StringDetermines 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: * 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. |
exclusiveoptional | Booleanindicating 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 behavior in all circumstances. |
Returns
Marker
#::markPosition(position, options)
Create a Marker at the given position with no tail in the default
marker layer.
| Argument | Description |
|---|---|
position | Pointor point-compatible Array |
optionsoptional | An Object with the following keys: |
invalidateoptional | StringDetermines 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: * 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. |
exclusiveoptional | Booleanindicating 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 behavior in all circumstances. |
Returns
Marker
#::getMarkers()
Get all existing markers on the default marker layer.
Returns
Array — of Markers.
#::getMarker(id)
Get an existing marker by its id from the default marker layer.
| Argument | Description |
|---|---|
id | Numberid of the marker to retrieve |
Returns
Marker
#::findMarkers(params)
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 | Description |
|---|---|
params | 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: |
startPosition | Only include markers that start at the given Point. |
endPosition | Only include markers that end at the given Point. |
startsInRange | Only include markers that start inside the given Range. |
endsInRange | Only include markers that end inside the given Range. |
containsPoint | Only include markers that contain the given Point, inclusive. |
containsRange | Only include markers that contain the given Range, inclusive. |
startRow | Only include markers that start at the given row Number. |
endRow | Only include markers that end at the given row Number. |
intersectsRow | Only include markers that intersect the given row Number. |
Returns
Array — of Markers.
#::getMarkerCount()
Get the number of markers in the default marker layer.
Returns
Number
History10
#::undo(options)
Undo the last operation. If a transaction is in progress, aborts it.
| Argument | Description |
|---|---|
optionsoptional | Object |
selectionsMarkerLayeroptional | Restore snapshot of selections marker layer to given selectionsMarkerLayer. |
Returns
Boolean — of whether or not a change was made.
#::redo(options)
Redo the last operation
| Argument | Description |
|---|---|
optionsoptional | Object |
selectionsMarkerLayeroptional | Restore snapshot of selections marker layer to given selectionsMarkerLayer. |
Returns
Boolean — of whether or not a change was made.
#::transact(options, fn)
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.
| Argument | Description |
|---|---|
optionsoptional | Object |
fn | A Function to call inside the transaction. |
groupingIntervaloptional | NumberMilliseconds for which this transaction remains open for grouping. A subsequent transaction committed in that interval is merged with it for undo and redo. |
selectionsMarkerLayeroptional | MarkerLayerSkip snapshots for other selection marker layers. |
#::abortTransaction()
Abort the currently running transaction
Only intended to be called within the fn option to #transact
#::clearUndoStack()
Clear the undo stack.
#::createCheckpoint(options)
Create a pointer to the current state of the buffer for use with #revertToCheckpoint and #groupChangesSinceCheckpoint.
| Argument | Description |
|---|---|
optionsoptional | Object |
selectionsMarkerLayeroptional | When provided, skip taking snapshot for other selections markerLayers except given one. |
Returns
Number — checkpoint id value.
#::revertToCheckpoint(checkpoint, options)
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 will
| Argument | Description |
|---|---|
checkpoint | Numberid of the checkpoint to revert to. |
optionsoptional | Object |
selectionsMarkerLayeroptional | Restore snapshot of selections marker layer to given selectionsMarkerLayer. |
Returns
Boolean — Whether the operation succeeded.
#::groupChangesSinceCheckpoint(checkpoint, options)
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 | Description |
|---|---|
checkpoint | Numberid of the checkpoint to group changes since. |
optionsoptional | Object |
selectionsMarkerLayeroptional | When provided, skip taking snapshot for other selections markerLayers except given one. |
Returns
Boolean — indicating whether the operation succeeded.
#::groupLastChanges()
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.
#::getChangesSinceCheckpoint(checkpoint)
If the given checkpoint is no longer present in the undo history, this
method will return an empty Array.
| Argument | Description |
|---|---|
checkpoint | Numberid 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.
Search And Replace16
#::scan(regex, options = {}, iterator)
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.
| Argument | Description |
|---|---|
regex | A RegExp to search for. |
optionsoptional | Object |
iterator | A Function that’s called on each match with an Object containing the following keys: |
leadingContextLineCount | Numberdefault 0; The number of lines before the matched line to include in the results object. |
trailingContextLineCount | Numberdefault 0; The number of lines after the matched line to include in the results object. |
match | The current regular expression match. |
matchText | A String with the text of the match. |
range | The Range of the match. |
stop | Call this Function to terminate the scan. |
replace | Call this Function with a String to replace the match. |
leadingContextLines | An Array with leadingContextLineCount lines before the match. |
trailingContextLines | An Array with trailingContextLineCount lines after the match. |
#::backwardsScan(regex, options = {}, iterator)
Scan regular expression matches in the entire buffer in reverse order, calling the given iterator function on each match.
| Argument | Description |
|---|---|
regex | A RegExp to search for. |
optionsoptional | Object |
iterator | A Function that’s called on each match with an Object containing the following keys: |
leadingContextLineCount | Numberdefault 0; The number of lines before the matched line to include in the results object. |
trailingContextLineCount | Numberdefault 0; The number of lines after the matched line to include in the results object. |
match | The current regular expression match. |
matchText | A String with the text of the match. |
range | The Range of the match. |
stop | Call this Function to terminate the scan. |
replace | Call this Function with a String to replace the match. |
leadingContextLines | An Array with leadingContextLineCount lines before the match. |
trailingContextLines | An Array with trailingContextLineCount lines after the match. |
#::scanInRange(regex, range, options = {}, callback, reverse = false)
Scan regular expression matches in a given range , calling the given iterator function on each match.
| Argument | Description |
|---|---|
regex | A RegExp to search for. |
range | A Range in which to search. |
optionsoptional | Object |
callback | A Function that’s called on each match with an Object containing the following keys: |
reverseoptional, default: false | No description. |
leadingContextLineCount | Numberdefault 0; The number of lines before the matched line to include in the results object. |
trailingContextLineCount | Numberdefault 0; The number of lines after the matched line to include in the results object. |
match | The current regular expression match. |
matchText | A String with the text of the match. |
range | The Range of the match. |
stop | Call this Function to terminate the scan. |
replace | Call this Function with a String to replace the match. |
leadingContextLines | An Array with leadingContextLineCount lines before the match. |
trailingContextLines | An Array with trailingContextLineCount lines after the match. |
#::backwardsScanInRange(regex, range, options = {}, iterator)
Scan regular expression matches in a given range in reverse order, calling the given iterator function on each match.
| Argument | Description |
|---|---|
regex | A RegExp to search for. |
range | A Range in which to search. |
optionsoptional | Object |
iterator | A Function that’s called on each match with an Object containing the following keys: |
leadingContextLineCount | Numberdefault 0; The number of lines before the matched line to include in the results object. |
trailingContextLineCount | Numberdefault 0; The number of lines after the matched line to include in the results object. |
match | The current regular expression match. |
matchText | A String with the text of the match. |
range | The Range of the match. |
stop | Call this Function to terminate the scan. |
replace | Call this Function with a String to replace the match. |
#::replace(regex, replacementText)
Replace all regular expression matches in the entire buffer.
| Argument | Description |
|---|---|
regex | A RegExp representing the matches to be replaced. |
replacementText | A String representing the text to replace each match. |
Returns
Number — representing the number of replacements made.
#::find(regex)
Asynchronously search the buffer for a given regex.
| Argument | Description |
|---|---|
regex | A RegExp to search for. |
Returns
Promise — that resolves with the first Range of text that matches the given regex.
#::findInRange(regex, range)
Asynchronously search a given range of the buffer for a given regex.
| Argument | Description |
|---|---|
regex | A RegExp to search for. |
range | A Range to search within. |
Returns
Promise — that resolves with the first Range of text that matches the given regex.
#::findSync(regex)
Search the buffer for a given regex.
| Argument | Description |
|---|---|
regex | A RegExp to search for. |
Returns
#::findInRangeSync(regex, range)
Search a given range of the buffer for a given regex.
| Argument | Description |
|---|---|
regex | A RegExp to search for. |
range | A Range to search within. |
Returns
#::findAll(regex)
Asynchronously search the buffer for a given regex.
| Argument | Description |
|---|---|
regex | A RegExp to search for. |
Returns
Promise — that resolves with an Array containing every Range of text that matches the given regex.
#::findAllInRange(regex, range)
Asynchronously search a given range of the buffer for a given regex.
| Argument | Description |
|---|---|
regex | A RegExp to search for. |
range | A Range to search within. |
Returns
Promise — that resolves with an Array containing every Range of text that matches the given regex.
#::findAllSync(regex)
Run an regexp search on the buffer
| Argument | Description |
|---|---|
regex | A RegExp to search for. |
Returns
Array — containing every Range of text that matches the given regex.
#::findAllInRangeSync(regex, range)
Search a given range of the buffer for a given regex.
| Argument | Description |
|---|---|
regex | A RegExp to search for. |
range | A Range to search within. |
Returns
Array — containing every Range of text that matches the given regex.
#::findAndMarkAllInRangeSync(markerLayer, regex, range, options = {})
Search a given range of the buffer for a given regex. Store the matching ranges in the given marker layer.
| Argument | Description |
|---|---|
markerLayer | A MarkerLayer to populate. |
regex | A RegExp to search for. |
range | A Range to search within. |
optionsoptional, default: {} | No description. |
Returns
Array — of Markers representing the matches.
#::findWordsWithSubsequence(query, extraWordCharacters, maxCount)
Find fuzzy match suggestions in the buffer
| Argument | Description |
|---|---|
query | A String to search for. |
extraWordCharacters | A String of additional word characters to use when deciphering word boundaries |
maxCount | A Number that limits the number of matches returned |
Returns
Array — containing every SubsequenceMatch of text that matches the given query.
#::findWordsWithSubsequenceInRange(query, extraWordCharacters, maxCount, range)
Find fuzzy match suggestions in the buffer in a given range
| Argument | Description |
|---|---|
query | A String to search for. |
extraWordCharacters | A String of additional word characters to use when deciphering word boundaries |
maxCount | A Number that limits the number of matches returned |
range | A Range that specifies the portion of the buffer to search |
Returns
Array — containing every SubsequenceMatch of text that matches the given query in the given range.
Buffer Range Details12
#::getRange()
Get the range spanning from [0, 0] to #getEndPosition.
Returns
#::getLineCount()
Get the number of lines in the buffer.
Returns
Number
#::getLastRow()
Get the last 0-indexed row in the buffer.
Returns
Number
#::getFirstPosition()
Get the first position in the buffer, which is always [0, 0].
Returns
#::getEndPosition()
Get the maximal position in the buffer, where new text would be appended.
Returns
#::getLength()
Get the length of the buffer’s text.
#::getMaxCharacterIndex()
Get the length of the buffer in characters.
Returns
Number
#::rangeForRow(row, includeNewline)
Get the range for the given row
| Argument | Description |
|---|---|
row | A Number representing a 0-indexed row. |
includeNewline | 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
#::characterIndexForPosition(position)
Convert a position in the buffer in row/column coordinates to an absolute character offset, inclusive of line ending characters.
The position is clipped prior to translating.
| Argument | Description |
|---|---|
position | A Point or point-compatible Array. |
Returns
Number
#::positionForCharacterIndex(offset)
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 | Description |
|---|---|
offset | A Number. |
Returns
#::clipRange(range)
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).
| Argument | Description |
|---|---|
range | A Range or range-compatible Array to clip. |
Returns
Range — given Range if it is already in bounds, or a new clipped Range if the given range is out-of-bounds.
#::clipPosition(position, options)
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 | Description |
|---|---|
position | A Point or point-compatible Array. |
Returns
Point — new Point if the given position is invalid, otherwise returns the given position.
Buffer Operations3
#::save()
Save the buffer.
Returns
Promise — that resolves when the save has completed.
#::saveAs(filePath)
Save the buffer at a specific path.
| Argument | Description |
|---|---|
filePath | The path to save at. |
Returns
Promise — that resolves when the save has completed.
#::reload()
Reload the file’s content from disk.
Returns
Promise — that resolves when the load is complete.
Display Layers3
#::getLanguageMode()
Get the language mode associated with this buffer.
Returns
Object — language mode Object (See TextBuffer#setLanguageMode for its interface).
#::setLanguageMode(languageMode)
Set the language mode for this buffer.
| Argument | Description |
|---|---|
languageMode | an Object with the following methods: |
getLanguageId | A Function that returns a String identifying the language. |
bufferDidChange | A Function that is called whenever the buffer changes. |
change | An Object with the following fields: |
oldText | StringThe deleted text |
oldRange | The Range of the deleted text before the change took place. |
newText | StringThe inserted text |
newRange | The Range of the inserted text after the change took place. |
onDidChangeHighlighting | 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 | A function that returns an iterator object with the following methods: |
seek | A Function that takes a Point and resets the iterator to that position. |
moveToSuccessor | A Function that advances the iterator to the next token |
getPosition | A Function that returns a Point representing the iterator’s current position in the buffer. |
getCloseTags | A Function that returns an Array of Numbers representing tokens that end at the current position. |
getOpenTags | A Function that returns an Array of Numbers representing tokens that begin at the current position. |
#::onDidChangeLanguageMode(callback)
Call the given callback whenever the buffer’s language mode changes.
| Argument | Description |
|---|---|
callback | A Function to call when the language mode changes. |
languageMode | The buffer’s new language mode Object. See TextBuffer#setLanguageMode for its interface. |
oldLanguageMode | 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.
Private Utility Methods1
#::getFileWatchStartPromise()
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.
Essential API
TextEditorsrc/text-editor.js:76
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.
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.
Event Subscription31
#::onDidChangeTitle(callback)
Calls your callback when the buffer’s title has changed.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangePath(callback)
Calls your callback when the buffer’s path, and therefore title, has changed.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChange(callback)
Invoke the given callback synchronously when the content of the buffer changes.
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 | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidStopChanging(callback)
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 | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeCursorPosition(callback)
Calls your callback when a Cursor is moved. If there are
multiple cursors, your callback will be called for each cursor.
| Argument | Description |
|---|---|
callback | Function |
event | Object |
oldBufferPosition | |
oldScreenPosition | |
newBufferPosition | |
newScreenPosition | |
textChanged | Boolean |
cursor | Cursorthat triggered the event |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeSelectionRange(callback)
Calls your callback when a selection’s screen range changes.
| Argument | Description |
|---|---|
callback | Function |
event | Object |
oldBufferRange | |
oldScreenRange | |
newBufferRange | |
newScreenRange | |
selection | Selectionthat triggered the event |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeSoftWrapped(callback)
Calls your callback when soft wrap was enabled or disabled.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeOvertypeMode(callback)
Calls your callback when overtype (overwrite) mode is enabled or
disabled for this editor.
| Argument | Description |
|---|---|
callback | Function |
overtypeMode | Booleanindicating the new state. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeEncoding(callback)
Calls your callback when the buffer’s encoding has changed.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeGrammar(callback)
Calls your callback when the grammar that interprets and
colorizes the text has been changed. Immediately calls your callback with
the current grammar.
| Argument | Description |
|---|---|
callback | Function |
grammar | Grammar |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeGrammar(callback)
Calls your callback when the grammar that interprets and
colorizes the text has been changed.
| Argument | Description |
|---|---|
callback | Function |
grammar | Grammar |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeModified(callback)
Calls your callback when the result of #isModified changes.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidConflict(callback)
Calls your callback when the buffer’s underlying file changes on
disk at a moment when the result of #isModified is true.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDelete(callback)
Calls your callback when the buffer’s underlying file is deleted
on disk.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onWillInsertText(callback)
Calls your callback before text has been inserted.
| Argument | Description |
|---|---|
callback | Function |
event | event Object |
text | Stringtext to be inserted |
cancel | FunctionCall to prevent the text from being inserted |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidInsertText(callback)
Calls your callback after text has been inserted.
| Argument | Description |
|---|---|
callback | Function |
event | event Object |
text | Stringtext to be inserted |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidSave(callback)
Invoke the given callback after the buffer is saved to disk.
| Argument | Description |
|---|---|
callback | Functionto be called after the buffer is saved. |
event | Objectwith the following keys: |
path | The path to which the buffer was saved. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDestroy(callback)
Invoke the given callback when the editor is destroyed.
| Argument | Description |
|---|---|
callback | Functionto be called when the editor is destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeCursors(callback)
Calls your callback when a Cursor is added to the editor.
Immediately calls your callback for each existing cursor.
| Argument | Description |
|---|---|
callback | Function |
cursor | Cursorthat was added |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidAddCursor(callback)
Calls your callback when a Cursor is added to the editor.
| Argument | Description |
|---|---|
callback | Function |
cursor | Cursorthat was added |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidRemoveCursor(callback)
Calls your callback when a Cursor is removed from the editor.
| Argument | Description |
|---|---|
callback | Function |
cursor | Cursorthat was removed |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeSelections(callback)
Calls your callback when a Selection is added to the editor.
Immediately calls your callback for each existing selection.
| Argument | Description |
|---|---|
callback | Function |
selection | Selectionthat was added |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidAddSelection(callback)
Calls your callback when a Selection is added to the editor.
| Argument | Description |
|---|---|
callback | Function |
selection | Selectionthat was added |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidRemoveSelection(callback)
Calls your callback when a Selection is removed from the editor.
| Argument | Description |
|---|---|
callback | Function |
selection | Selectionthat was removed |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeDecorations(callback)
Calls your callback with each Decoration added to the editor.
Calls your callback immediately for any existing decorations.
| Argument | Description |
|---|---|
callback | Function |
decoration |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidAddDecoration(callback)
Calls your callback when a Decoration is added to the editor.
| Argument | Description |
|---|---|
callback | Function |
decoration | Decorationthat was added |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidRemoveDecoration(callback)
Calls your callback when a Decoration is removed from the editor.
| Argument | Description |
|---|---|
callback | Function |
decoration | Decorationthat was removed |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangePlaceholderText(callback)
Calls your callback when the placeholder text is changed.
| Argument | Description |
|---|---|
callback | Function |
placeholderText | Stringnew text |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeGutters(callback)
Calls your callback when a Gutter is added to the editor.
Immediately calls your callback for each existing gutter.
| Argument | Description |
|---|---|
callback | Function |
gutter | Gutterthat currently exists/was added. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidAddGutter(callback)
Calls your callback when a Gutter is added to the editor.
| Argument | Description |
|---|---|
callback | Function |
gutter | Gutterthat was added. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidRemoveGutter(callback)
Calls your callback when a Gutter is removed from the editor.
| Argument | Description |
|---|---|
callback | Function |
name | The name of the Gutter that was removed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Buffer1
#::getBuffer()
Retrieves the current TextBuffer.
File Details9
#::getTitle()
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
#::getLongTitle()
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
#::getPath()
Returns
String — path of this editor’s text buffer.
#::getEncoding()
Returns
String — character set encoding of this editor’s text buffer.
#::setEncoding(encoding)
Set the character set encoding to use in this editor’s text buffer.
| Argument | Description |
|---|---|
encoding | The String character set encoding name such as ‘utf8’ |
#::isModified()
Returns
Boolean — true if this editor has been modified.
#::isDeleted()
Returns
Boolean — true if this editor’s buffer previously had a file on disk that has since been deleted (and has not been recreated or saved since). The buffer may still be unmodified — see #isModified.
#::isInConflict()
This can happen if another process writes to a file after you start to edit it in Lumine, but before you’re able to save those changes. It can also happen if you switch branches in version control while a certain buffer has uncommitted changes.
Returns
Boolean — true if this editor’s buffer is in conflict — that is, if the buffer is modified and those changes are based on buffer contents that do not match what is currently written to disk.
#::isEmpty()
Returns
Boolean — true if this editor has no content.
File Operations2
#::save()
Saves the editor’s text buffer.
See TextBuffer#save for more details.
#::saveAs(filePath)
Saves the editor’s text buffer as the given path.
See TextBuffer#saveAs for more details.
| Argument | Description |
|---|---|
filePath | A String path. |
Reading Text9
#::getText()
Returns
String — representing the entire contents of the editor.
#::getTextInBufferRange(range)
Get the text in the given Range in buffer coordinates.
| Argument | Description |
|---|---|
range | A Range or range-compatible Array. |
Returns
String
#::getLineCount()
Returns
Number — representing the number of lines in the buffer.
#::getScreenLineCount()
Returns
Number — representing the number of screen lines in the editor. This accounts for folds.
#::getLastBufferRow()
Returns
Number — representing the last zero-indexed buffer row number of the editor.
#::getLastScreenRow()
Returns
Number — representing the last zero-indexed screen row number of the editor.
#::lineTextForBufferRow(bufferRow)
| Argument | Description |
|---|---|
bufferRow | A Number representing a zero-indexed buffer row. |
Returns
String — representing the contents of the line at the given buffer row.
#::lineTextForScreenRow(screenRow)
| Argument | Description |
|---|---|
screenRow | A Number representing a zero-indexed screen row. |
Returns
String — representing the contents of the line at the given screen row.
#::getCurrentParagraphBufferRange()
Get the Range of the paragraph surrounding the most recently added cursor.
Returns
Mutating Text25
#::setText(text, options = {})
Replaces the entire contents of the buffer with the given String.
| Argument | Description |
|---|---|
text | StringText to replace the buffer contents with. |
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. |
#::setTextInBufferRange(range, text, options = {})
Set the text in the given Range in buffer coordinates.
| Argument | Description |
|---|---|
range | A Range or range-compatible Array. |
text | A String |
optionsoptional | Object |
normalizeLineEndingsoptional | Boolean(default: true) |
undooptional | Deprecated String ‘skip’ will skip the undo system. This property is deprecated. Call groupLastChanges() on the TextBuffer afterward instead. |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
Returns
Range — of the newly-inserted text.
#::insertText(text, options = {})
For each selection, replace the selected text with the given text.
| Argument | Description |
|---|---|
text | A String representing the text to insert. |
optionsoptional | See Selection#insertText. |
Returns
Range — when the text has been inserted. Returns a Boolean false when the text has not been inserted.
#::insertNewline(options = {})
For each selection, replace the selected text with a newline.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::delete(options = {})
For each selection, if the selection is empty, delete the character following the cursor. Otherwise delete the selected text.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::backspace(options = {})
For each selection, if the selection is empty, delete the character preceding the cursor. Otherwise delete the selected text.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::mutateSelectedText(fn, groupingInterval = 0)
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.
#::transpose(options = {})
For each selection, transpose the selected text.
If the selection is empty, the characters preceding and following the cursor are swapped. Otherwise, the selected characters are reversed.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::upperCase(options = {})
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.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::lowerCase(options = {})
Convert the selected text to lower case.
For each selection, if the selection is empty, converts the containing word to upper case. Otherwise convert the selected text to upper case.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::toggleLineCommentsInSelection(options = {})
Toggle line comments for rows intersecting selections.
If the current grammar doesn’t support comments, does nothing.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::collapseBlankLines(options = {})
Reduce every run of blank lines in the buffer to a single blank line.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::collapseContentSpaces(options = {})
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 | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::insertNewlineBelow(options = {})
For each cursor, insert a newline at beginning the following line.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::insertNewlineAbove(options = {})
For each cursor, insert a newline at the end of the preceding line.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::deleteToBeginningOfWord(options = {})
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 | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::deleteToPreviousWordBoundary(options = {})
Similar to #deleteToBeginningOfWord, but deletes only back to the previous word boundary.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::deleteToNextWordBoundary(options = {})
Similar to #deleteToEndOfWord, but deletes only up to the next word boundary.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::deleteToBeginningOfSubword(options = {})
For each selection, if the selection is empty, delete all characters of the containing subword following the cursor. Otherwise delete the selected text.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::deleteToEndOfSubword(options = {})
For each selection, if the selection is empty, delete all characters of the containing subword following the cursor. Otherwise delete the selected text.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::deleteToBeginningOfLine(options = {})
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 | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::deleteToEndOfLine(options = {})
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 | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::deleteToNextLineContent(options = {})
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 | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::deleteToEndOfWord(options = {})
For each selection, if the selection is empty, delete all characters of the containing word following the cursor. Otherwise delete the selected text.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::deleteLine(options = {})
Delete all lines intersecting selections.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
History7
#::undo(options = {})
Undo the last change.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::redo(options = {})
Redo the last change.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. (default: false) |
#::transact(groupingInterval, fn)
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.
| Argument | Description |
|---|---|
groupingIntervaloptional | 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. |
fn | A Function to call inside the transaction. |
#::abortTransaction()
Abort an open transaction, undoing any operations performed so far within the transaction.
#::createCheckpoint()
Create a pointer to the current state of the buffer for use with #revertToCheckpoint and #groupChangesSinceCheckpoint.
Returns
Number — checkpoint value.
#::revertToCheckpoint(checkpoint)
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 will
| Argument | Description |
|---|---|
checkpoint | The checkpoint to revert to. |
Returns
Boolean — Whether the operation succeeded.
#::groupChangesSinceCheckpoint(checkpoint)
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 | Description |
|---|---|
checkpoint | The checkpoint from which to group changes. |
Returns
Boolean — indicating whether the operation succeeded.
TextEditor Coordinates8
#::screenPositionForBufferPosition(bufferPosition, options)
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 | Description |
|---|---|
bufferPosition | A Point or Array of [row, column]. |
optionsoptional | An options object for #clipScreenPosition. |
Returns
#::bufferPositionForScreenPosition(screenPosition, options)
Convert a position in screen-coordinates to buffer-coordinates.
The position is clipped via #clipScreenPosition prior to the conversion.
| Argument | Description |
|---|---|
screenPosition | Point|Array<Number>The screen position to convert. |
optionsoptional | ObjectOptions for #clipScreenPosition. |
Returns
#::screenRangeForBufferRange(bufferRange, options)
Convert a range in buffer-coordinates to screen-coordinates.
| Argument | Description |
|---|---|
bufferRange | Rangein buffer coordinates to translate into screen coordinates. |
Returns
#::bufferRangeForScreenRange(screenRange)
Convert a range in screen-coordinates to buffer-coordinates.
| Argument | Description |
|---|---|
screenRange | Rangein screen coordinates to translate into buffer coordinates. |
Returns
#::clipBufferPosition(bufferPosition)
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 | Description |
|---|---|
bufferPosition | The Point representing the position to clip. |
Returns
#::clipBufferRange(range)
Clip the start and end of the given range to valid positions in the buffer. See #clipBufferPosition for more information.
| Argument | Description |
|---|---|
range | The Range to clip. |
Returns
#::clipScreenPosition(screenPosition, options)
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 | Description |
|---|---|
screenPosition | The Point representing the position to clip. |
optionsoptional | Object |
clipDirection | StringIf '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.
#::clipScreenRange(screenRange, options)
Clip the start and end of the given range to valid positions on screen. See #clipScreenPosition for more information.
| Argument | Description |
|---|---|
screenRange | The Range to clip. |
optionsoptional | See #clipScreenPosition options. |
Returns
Decorations7
#::decorateMarker(marker, decorationParams)
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>"> <!-- Will be one region for each row in the range. Spans 2 lines? There will be 2 regions. --> <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. - 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.
Arguments
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 | Description |
|---|---|
marker | A DisplayMarker you want this decoration to follow. |
decorationParams | An Object representing the decoration e.g. {type: 'line-number', class: 'linter-error'} |
type | Determines the behavior and appearance of this Decoration. Supported decoration types and their uses are listed above. |
class | This CSS class will be applied to the decorated line number, line, text spans, highlight regions, cursors, or overlay. |
style | 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 | An HTMLElement or a model Object with a corresponding view registered. Only applicable to the gutter, overlay and block decoration types. |
onlyHeadoptional | 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 | 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 | 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 | 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 | Only applicable to decorations of type overlay and block. Controls where the view is positioned relative to the TextEditorMarker. Values can be 'head' (the default) or 'tail' for overlay decorations, and 'before' (the default) or 'after' for block decorations. |
orderoptional | 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 | 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 | 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. |
priorityoptional | 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.
#::decorateMarkerLayer(markerLayer, decorationParams)
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 | Description |
|---|---|
markerLayer | A DisplayMarkerLayer or MarkerLayer to decorate. |
decorationParams | The same parameters that are passed to TextEditor#decorateMarker, except the type cannot be overlay or gutter. |
Returns
#::getDecorations(propertyFilter)
Get all decorations.
| Argument | Description |
|---|---|
propertyFilteroptional | An Object containing key value pairs that the returned decorations’ properties must match. |
Returns
Array — of Decorations.
#::getLineDecorations(propertyFilter)
Get all decorations of type ‘line’.
| Argument | Description |
|---|---|
propertyFilteroptional | An Object containing key value pairs that the returned decorations’ properties must match. |
Returns
Array — of Decorations.
#::getLineNumberDecorations(propertyFilter)
Get all decorations of type ‘line-number’.
| Argument | Description |
|---|---|
propertyFilteroptional | An Object containing key value pairs that the returned decorations’ properties must match. |
Returns
Array — of Decorations.
#::getHighlightDecorations(propertyFilter)
Get all decorations of type ‘highlight’.
| Argument | Description |
|---|---|
propertyFilteroptional | An Object containing key value pairs that the returned decorations’ properties must match. |
Returns
Array — of Decorations.
#::getOverlayDecorations(propertyFilter)
Get all decorations of type ‘overlay’.
| Argument | Description |
|---|---|
propertyFilteroptional | An Object containing key value pairs that the returned decorations’ properties must match. |
Returns
Array — of Decorations.
Markers11
#::markBufferRange(bufferRange, options)
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 | Description |
|---|---|
bufferRange | A Range or range-compatible Array |
options | A hash of key-value pairs to associate with the marker. There are also reserved property names that have marker-specific meaning. |
maintainHistoryoptional | BooleanWhether 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 | BooleanCreates the marker in a reversed orientation. (default: false) |
invalidateoptional | StringDetermines 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: * 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. |
Returns
#::markScreenRange(screenRange, options)
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 | Description |
|---|---|
screenRange | A Range or range-compatible Array |
options | A hash of key-value pairs to associate with the marker. There are also reserved property names that have marker-specific meaning. |
maintainHistoryoptional | BooleanWhether 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 | BooleanCreates the marker in a reversed orientation. (default: false) |
invalidateoptional | StringDetermines 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: * 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. |
Returns
#::markBufferPosition(bufferPosition, options)
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 | Description |
|---|---|
bufferPosition | A Point or point-compatible Array |
optionsoptional | An Object with the following keys: |
invalidateoptional | StringDetermines 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: * 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. |
Returns
#::markScreenPosition(screenPosition, options)
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 | Description |
|---|---|
screenPosition | A Point or point-compatible Array |
optionsoptional | An Object with the following keys: |
invalidateoptional | StringDetermines 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: * 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. |
clipDirection | StringIf '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.
#::findMarkers(params)
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 | Description |
|---|---|
params | 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: |
startBufferRow | Only include markers starting at this row in buffer coordinates. |
endBufferRow | Only include markers ending at this row in buffer coordinates. |
containsBufferRange | Only include markers containing this Range or in range-compatible Array in buffer coordinates. |
containsBufferPosition |
Returns
Array — of DisplayMarkers
#::getMarker(id)
Get the DisplayMarker on the default layer for the given marker id.
| Argument | Description |
|---|---|
id | Numberid of the marker |
#::getMarkers()
Get all DisplayMarkers on the default marker layer. Consider using #findMarkers
#::getMarkerCount()
Get the number of markers in the default marker layer.
Returns
Number
#::addMarkerLayer(options)
Create a marker layer to group related markers.
| Argument | Description |
|---|---|
options | An Object containing the following keys: |
maintainHistory | A Boolean indicating whether marker state should be restored on undo/redo. Defaults to false. |
persistent | 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. |
Returns
#::getMarkerLayer(id)
Get a DisplayMarkerLayer by id.
| Argument | Description |
|---|---|
id | The id of the marker layer to retrieve. |
Returns
DisplayMarkerLayer — or undefined if no layer exists with the given id.
#::getDefaultMarkerLayer()
Get the default DisplayMarkerLayer.
All marker APIs not tied to an explicit layer interact with this default layer.
Returns
Cursors34
#::getCursorBufferPosition()
Get the position of the most recently added cursor in buffer coordinates.
Returns
#::getCursorBufferPositions()
Get the position of all the cursor positions in buffer coordinates.
Returns
Array — of Points in the order they were added
#::setCursorBufferPosition(position, options)
Move the cursor to the given position in buffer coordinates.
If there are multiple cursors, they will be consolidated to a single cursor.
| Argument | Description |
|---|---|
position | |
optionsoptional | An Object containing the following keys: |
autoscroll | Determines whether the editor scrolls to the new cursor’s position. Defaults to true. |
#::getCursorAtScreenPosition(position)
| Argument | Description |
|---|---|
position |
Returns
#::getCursorScreenPosition()
Get the position of the most recently added cursor in screen coordinates.
Returns
#::getCursorScreenPositions()
Get the position of all the cursor positions in screen coordinates.
Returns
Array — of Points in the order the cursors were added
#::setCursorScreenPosition(position, options)
Move the cursor to the given position in screen coordinates.
If there are multiple cursors, they will be consolidated to a single cursor.
| Argument | Description |
|---|---|
position | |
optionsoptional | An Object combining options for #clipScreenPosition with: |
autoscroll | Determines whether the editor scrolls to the new cursor’s position. Defaults to true. |
#::addCursorAtBufferPosition(bufferPosition, options)
Add a cursor at the given position in buffer coordinates.
| Argument | Description |
|---|---|
bufferPosition |
Returns
#::addCursorAtScreenPosition(screenPosition, options)
Add a cursor at the position in screen coordinates.
| Argument | Description |
|---|---|
screenPosition |
Returns
#::hasMultipleCursors()
Returns
Boolean — indicating whether or not there are multiple cursors.
#::moveUp(lineCount)
Move every cursor up one row in screen coordinates.
| Argument | Description |
|---|---|
lineCountoptional | Numbernumber of lines to move |
#::moveDown(lineCount)
Move every cursor down one row in screen coordinates.
| Argument | Description |
|---|---|
lineCountoptional | Numbernumber of lines to move |
#::moveLeft(columnCount)
Move every cursor left one column.
| Argument | Description |
|---|---|
columnCountoptional | Numbernumber of columns to move (default: 1) |
#::moveRight(columnCount)
Move every cursor right one column.
| Argument | Description |
|---|---|
columnCountoptional | Numbernumber of columns to move (default: 1) |
#::moveToBeginningOfLine()
Move every cursor to the beginning of its line in buffer coordinates.
#::moveToBeginningOfScreenLine()
Move every cursor to the beginning of its line in screen coordinates.
#::moveToFirstCharacterOfLine()
Move every cursor to the first non-whitespace character of its line.
#::moveToEndOfLine()
Move every cursor to the end of its line in buffer coordinates.
#::moveToEndOfScreenLine()
Move every cursor to the end of its line in screen coordinates.
#::moveToBeginningOfWord()
Move every cursor to the beginning of its surrounding word.
#::moveToEndOfWord()
Move every cursor to the end of its surrounding word.
#::moveToTop()
Move every cursor to the top of the buffer.
If there are multiple cursors, they will be merged into a single cursor.
#::moveToBottom()
Move every cursor to the bottom of the buffer.
If there are multiple cursors, they will be merged into a single cursor.
#::moveToBeginningOfNextWord()
Move every cursor to the beginning of the next word.
#::moveToPreviousWordBoundary()
Move every cursor to the previous word boundary.
#::moveToNextWordBoundary()
Move every cursor to the next word boundary.
#::moveToPreviousSubwordBoundary()
Move every cursor to the previous subword boundary.
#::moveToNextSubwordBoundary()
Move every cursor to the next subword boundary.
#::moveToBeginningOfNextParagraph()
Move every cursor to the beginning of the next paragraph.
#::moveToBeginningOfPreviousParagraph()
Move every cursor to the beginning of the previous paragraph.
#::getLastCursor()
Returns
#::getWordUnderCursor(options)
| Argument | Description |
|---|---|
optionsoptional |
Returns
String — word surrounding the most recently added cursor.
#::getCursors()
Get an Array of all Cursors.
#::getCursorsOrderedByBufferPosition()
Get all Cursors, ordered by their position in the buffer instead of the order in which they were added.
Returns
Array — of Selections.
Selections42
#::getSelectedText()
Get the selected text of the most recently added selection.
Returns
String
#::getSelectedBufferRange()
Get the Range of the most recently added selection in buffer coordinates.
Returns
#::getSelectedBufferRanges()
Get the Ranges of all selections in buffer coordinates.
The ranges are sorted by when the selections were added. Most recent at the end.
Returns
Array — of Ranges.
#::setSelectedBufferRange(bufferRange, options)
Set the selected range in buffer coordinates. If there are multiple selections, they are reduced to a single selection with the given range.
| Argument | Description |
|---|---|
bufferRange | A Range or range-compatible Array. |
optionsoptional | An Object of options: |
reversed | A Boolean indicating whether to create the selection in a reversed orientation. |
preserveFolds | A Boolean, which if true preserves the fold settings after the selection is set. |
#::setSelectedBufferRanges(bufferRanges, options = {})
Set the selected ranges in buffer coordinates. If there are multiple selections, they are replaced by new selections with the given ranges.
| Argument | Description |
|---|---|
bufferRanges | |
optionsoptional | An Object of options: |
reversed | A Boolean indicating whether to create the selection in a reversed orientation. |
preserveFolds | A Boolean, which if true preserves the fold settings after the selection is set. |
#::getSelectedScreenRange()
Get the Range of the most recently added selection in screen coordinates.
Returns
#::getSelectedScreenRanges()
Get the Ranges of all selections in screen coordinates.
The ranges are sorted by when the selections were added. Most recent at the end.
Returns
Array — of Ranges.
#::setSelectedScreenRange(screenRange, options)
Set the selected range in screen coordinates. If there are multiple selections, they are reduced to a single selection with the given range.
| Argument | Description |
|---|---|
screenRange | A Range or range-compatible Array. |
optionsoptional | An Object of options: |
reversed | A Boolean indicating whether to create the selection in a reversed orientation. |
#::setSelectedScreenRanges(screenRanges, options = {})
Set the selected ranges in screen coordinates. If there are multiple selections, they are replaced by new selections with the given ranges.
| Argument | Description |
|---|---|
screenRanges | |
optionsoptional | An Object of options: |
reversed | A Boolean indicating whether to create the selection in a reversed orientation. |
#::addSelectionForBufferRange(bufferRange, options = {})
Add a selection for the given range in buffer coordinates.
| Argument | Description |
|---|---|
bufferRange | A Range |
optionsoptional | An Object of options: |
reversed | A Boolean indicating whether to create the selection in a reversed orientation. |
preserveFolds | A Boolean, which if true preserves the fold settings after the selection is set. |
Returns
#::addSelectionForScreenRange(screenRange, options = {})
Add a selection for the given range in screen coordinates.
| Argument | Description |
|---|---|
screenRange | A Range |
optionsoptional | An Object of options: |
reversed | A Boolean indicating whether to create the selection in a reversed orientation. |
preserveFolds | A Boolean, which if true preserves the fold settings after the selection is set. |
Returns
#::selectToBufferPosition(position)
Select from the current cursor position to the given position in buffer coordinates.
This method may merge selections that end up intersecting.
| Argument | Description |
|---|---|
position |
#::selectToScreenPosition(position, options)
Select from the current cursor position to the given position in screen coordinates.
This method may merge selections that end up intersecting.
| Argument | Description |
|---|---|
position |
#::selectUp(rowCount)
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 | Description |
|---|---|
rowCountoptional | Numbernumber of rows to select (default: 1) |
#::selectDown(rowCount)
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 | Description |
|---|---|
rowCountoptional | Numbernumber of rows to select (default: 1) |
#::selectLeft(columnCount)
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 | Description |
|---|---|
columnCountoptional | Numbernumber of columns to select (default: 1) |
#::selectRight(columnCount)
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 | Description |
|---|---|
columnCountoptional | Numbernumber of columns to select (default: 1) |
#::selectToTop()
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.
#::selectToBottom()
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.
#::selectAll()
Select all text in the buffer.
This method merges multiple selections into a single selection.
#::selectToBeginningOfLine()
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.
#::selectToFirstCharacterOfLine()
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.
#::selectToEndOfLine()
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.
#::selectToBeginningOfWord()
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.
#::selectToEndOfWord()
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.
#::selectToPreviousSubwordBoundary()
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.
#::selectToNextSubwordBoundary()
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.
#::selectLinesContainingCursors()
For each cursor, select the containing line.
This method merges selections on successive lines.
#::selectWordsContainingCursors()
Select the word surrounding each cursor.
#::selectSubwordsContainingCursors()
Select the subword surrounding each cursor.
#::selectToPreviousWordBoundary()
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.
#::selectToNextWordBoundary()
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.
#::selectToBeginningOfNextWord()
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.
#::selectToBeginningOfNextParagraph()
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.
#::selectToBeginningOfPreviousParagraph()
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.
#::selectLargerSyntaxNode()
For each selection, select the syntax node that contains that selection.
#::selectSmallerSyntaxNode()
Undo the effect of a preceding call to #selectLargerSyntaxNode.
#::selectMarker(marker)
Select the range of the given marker if it is valid.
| Argument | Description |
|---|---|
marker |
Returns
Range|undefined — selected Range or undefined if the marker is invalid.
#::getLastSelection()
Get the most recently added Selection.
Returns
#::getSelections()
Get current Selections.
Returns
Array<Selection> — The current selections.
#::getSelectionsOrderedByBufferPosition()
Get all Selections, ordered by their position in the buffer instead of the order in which they were added.
Returns
Array — of Selections.
#::selectionIntersectsBufferRange(bufferRange)
Determine if a given range in buffer coordinates intersects a selection.
| Argument | Description |
|---|---|
bufferRange | A Range or range-compatible Array. |
Returns
Boolean
Searching and Replacing3
#::scan(regex, options = {}, iterator)
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 | Description |
|---|---|
regex | A RegExp to search for. |
optionsoptional | Object |
iterator | A Function that’s called on each match |
leadingContextLineCount | Numberdefault 0; The number of lines before the matched line to include in the results object. |
trailingContextLineCount | Numberdefault 0; The number of lines after the matched line to include in the results object. |
object | Object |
match | The current regular expression match. |
matchText | A String with the text of the match. |
range | The Range of the match. |
stop | Call this Function to terminate the scan. |
replace | Call this Function with a String to replace the match. |
#::scanInBufferRange(regex, range, iterator)
Scan regular expression matches in a given range, calling the given iterator function on each match.
| Argument | Description |
|---|---|
regex | A RegExp to search for. |
range | A Range in which to search. |
iterator | A Function that’s called on each match with an Object containing the following keys: |
match | The current regular expression match. |
matchText | A String with the text of the match. |
range | The Range of the match. |
stop | Call this Function to terminate the scan. |
replace | Call this Function with a String to replace the match. |
#::backwardsScanInBufferRange(regex, range, iterator)
Scan regular expression matches in a given range in reverse order, calling the given iterator function on each match.
| Argument | Description |
|---|---|
regex | A RegExp to search for. |
range | A Range in which to search. |
iterator | A Function that’s called on each match with an Object containing the following keys: |
match | The current regular expression match. |
matchText | A String with the text of the match. |
range | The Range of the match. |
stop | Call this Function to terminate the scan. |
replace | Call this Function with a String to replace the match. |
Tab Behavior7
#::getSoftTabs()
Returns
Boolean — indicating whether softTabs are enabled for this editor.
#::setSoftTabs(softTabs)
Enable or disable soft tabs for this editor.
| Argument | Description |
|---|---|
softTabs | A Boolean |
#::toggleSoftTabs()
Toggle soft tabs for this editor
#::getTabLength()
Get the on-screen length of tab characters.
Returns
Number
#::setTabLength(tabLength)
Set the on-screen length of tab characters. Setting this to a
Number This will override the language.tabLength setting.
| Argument | Description |
|---|---|
tabLength | Numberlength of a single tab. Setting to null will fallback to using the language.tabLength config setting |
#::usesSoftTabs()
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.
#::getTabText()
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 Behavior8
#::isSoftWrapped()
Determine whether lines in this editor are soft-wrapped.
Returns
Boolean
#::setSoftWrapped(softWrapped)
Enable or disable soft wrapping for this editor.
| Argument | Description |
|---|---|
softWrapped | A Boolean |
Returns
Boolean
#::toggleSoftWrapped()
Toggle soft wrapping for this editor
Returns
Boolean
#::isOvertypeMode()
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
#::setOvertypeMode(overtypeMode)
Enable or disable overtype (overwrite) mode for this editor.
| Argument | Description |
|---|---|
overtypeMode | A Boolean. |
Returns
Boolean
#::toggleOvertypeMode()
Toggle overtype (overwrite) mode for this editor.
Returns
Boolean
#::applyOvertype()
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.
#::getSoftWrapColumn()
Gets the column at which column will soft wrap
Indentation6
#::indentationForBufferRow(bufferRow)
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 | Description |
|---|---|
bufferRow | A Number indicating the buffer row. |
Returns
Number
#::setIndentationForBufferRow(bufferRow, newLevel, { preserveLeadingWhitespace } = {})
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 | Description |
|---|---|
bufferRow | A Number indicating the buffer row. |
newLevel | A Number indicating the new indentation level. |
optionsoptional | ObjectIndentation options. |
preserveLeadingWhitespaceoptional, default: false | BooleanPreserve whitespace already at the beginning of the line. |
#::indentSelectedRows(options = {})
Indent rows intersecting selections by one level.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. |
#::outdentSelectedRows(options = {})
Outdent rows intersecting selections by one level.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. |
#::indentLevelForLine(line)
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 | Description |
|---|---|
line | A String representing a line of text. |
Returns
Number
#::autoIndentSelectedRows(options = {})
Indent rows intersecting selections based on the grammar’s suggested indent level.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. |
Grammars2
Managing Syntax Scopes6
#::getRootScopeDescriptor()
Returns
ScopeDescriptor — that includes this editor’s language. e.g. ['.source.ruby'], or ['.source.coffee']. You can use this with Config#get to get language specific config values.
#::scopeDescriptorForBufferPosition(bufferPosition)
Get the syntactic ScopeDescriptor for the given position in buffer coordinates. Useful with Config#get.
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"]
| Argument | Description |
|---|---|
bufferPosition |
Returns
#::syntaxTreeScopeDescriptorForBufferPosition(bufferPosition)
Get the syntactic tree ScopeDescriptor for the given position in buffer coordinates or the syntactic ScopeDescriptor for TextMate language mode
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"]
if tree-sitter is used
and the following scopes array:
["source.js"]
if textmate is used
| Argument | Description |
|---|---|
bufferPosition |
Returns
#::bufferRangeForScopeAtCursor(scopeSelector)
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 | Description |
|---|---|
scopeSelector | Stringselector. e.g. '.source.ruby' |
Returns
#::bufferRangeForScopeAtPosition(scopeSelector, bufferPosition)
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 | Description |
|---|---|
scopeSelector | Stringselector. e.g. '.source.ruby' |
bufferPosition | A Point or Array of [row, column] |
Returns
#::isBufferRowCommented(bufferRow)
Determine if the given row is entirely a comment
Clipboard Operations5
#::copySelectedText(clipboard = this.constructor.clipboard)
For each selection, copy the selected text.
| Argument | Description |
|---|---|
clipboardoptional, default: this.constructor.clipboard | No description. |
#::cutSelectedText(options = {})
For each selection, cut the selected text.
| Argument | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. |
#::pasteText(options = {})
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.
| Argument | Description |
|---|---|
optionsoptional | See Selection#insertText. |
#::cutToEndOfLine(options = {})
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 | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. |
#::cutToEndOfBufferLine(options = {})
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 | Description |
|---|---|
optionsoptional | Object |
bypassReadOnlyoptional | BooleanMust be true to modify a read-only editor. |
Folds14
#::foldCurrentRow()
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.
#::unfoldCurrentRow()
Unfold the most recent cursor’s row by one level.
#::foldBufferRow(bufferRow)
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 | Description |
|---|---|
bufferRow | A Number. |
#::unfoldBufferRow(bufferRow)
Unfold all folds containing the given row in buffer coordinates.
| Argument | Description |
|---|---|
bufferRow | A Number |
#::foldSelectedLines()
For each selection, fold the rows it intersects.
#::foldAll()
Fold all foldable lines.
#::unfoldAll()
Unfold all existing folds.
#::foldAllAtIndentLevel(level)
Fold all foldable lines at the given indent level.
| Argument | Description |
|---|---|
level | A Number starting at 0. |
#::isFoldableAtBufferRow(bufferRow)
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 | Description |
|---|---|
bufferRow | A Number |
Returns
Boolean
#::isFoldableAtScreenRow(screenRow)
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 | Description |
|---|---|
screenRow | A Number |
Returns
Boolean
#::toggleFoldAtBufferRow(bufferRow)
Fold the given buffer row if it isn’t currently folded, and unfold it otherwise.
#::isFoldedAtCursorRow()
Determine whether the most recently added cursor’s row is folded.
Returns
Boolean
#::isFoldedAtBufferRow(bufferRow)
Determine whether the given row in buffer coordinates is folded.
| Argument | Description |
|---|---|
bufferRow | A Number |
Returns
Boolean
#::isFoldedAtScreenRow(screenRow)
Determine whether the given row in screen coordinates is folded.
| Argument | Description |
|---|---|
screenRow | A Number |
Returns
Boolean
Gutters3
#::addGutter(options)
Add a custom Gutter.
| Argument | Description |
|---|---|
options | An Object with the following fields: |
name | (required) A unique String to identify this gutter. |
priorityoptional | A Number that determines stacking order between gutters. Lower priority items are forced closer to the edges of the window. (default: -100) |
visibleoptional | Booleanspecifying whether the gutter is visible initially after being created. (default: true) |
typeoptional | Stringspecifying the type of gutter to create. 'decorated' gutters are useful as a destination for decorations created with Gutter#decorateMarker. 'line-number' gutters. |
classoptional | Stringadded to the CSS classnames of the gutter’s root DOM element. |
labelFnoptional | Functioncalled 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 | an Object containing information about each line to label. |
bufferRow | Numberindicating the zero-indexed buffer index of this line. |
screenRow | Numberindicating the zero-indexed screen index. |
foldable | Booleanthat is true if a fold may be created here. |
softWrapped | Booleanif this screen row is the soft-wrapped continuation of the same buffer row. |
maxDigits | Numberthe maximum number of digits necessary to represent any known screen row. |
onMouseDownoptional | Functionto 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 | an Object containing information about the line that’s being clicked. |
bufferRow | Numberof the originating line element |
screenRow | Number |
onMouseMoveoptional | Functionto be called when a mousemove event occurs on a line-number element within within this type: 'line-number' Gutter. |
lineData | an Object containing information about the line that’s being clicked. |
bufferRow | Numberof the originating line element |
screenRow | Number |
Returns
#::getGutters()
Get this editor’s gutters.
Returns
Array — of Gutters.
#::gutterWithName(name)
Get the gutter with the given name.
Returns
Gutter — or null if no gutter exists for the given name.
Scrolling the TextEditor4
#::scrollToCursorPosition(options)
Scroll the editor to reveal the most recently added cursor if it is off-screen.
| Argument | Description |
|---|---|
optionsoptional | Object |
center | Center the editor around the cursor if possible. (default: true when an options object is given at all, false otherwise — the bare call is the one the editor’s own movement commands make, and they scroll only as far as they must) |
zone | Land the cursor inside a band of the viewport, instead of centering it. See #scrollToScreenRange. |
#::scrollToBufferPosition(bufferPosition, options)
Scrolls the editor to the given buffer position.
| Argument | Description |
|---|---|
bufferPosition | An object that represents a buffer position. It can be either an Object ({row, column}), Array ([row, column]), or Point |
optionsoptional | Object |
center | Center the editor around the position if possible. (default: false) |
zone | Land the position inside a band of the viewport. See #scrollToScreenRange. |
#::scrollToScreenPosition(screenPosition, options)
Scrolls the editor to the given screen position.
| Argument | Description |
|---|---|
screenPosition | An object that represents a screen position. It can be either an Object ({row, column}), Array ([row, column]), or Point |
optionsoptional | Object |
center | Center the editor around the position if possible. (default: false) |
zone | Land the position inside a band of the viewport. See #scrollToScreenRange. |
#::scrollToScreenRange(screenRange, options = {})
Scrolls the editor to the given screen range.
| Argument | Description |
|---|---|
screenRange | A Range or range-compatible Array. |
optionsoptional | Object |
center | Center the editor around the range if possible. (default: false) |
zone | Where in the viewport the range should come to rest, as a percentage of the travel it has between the vertical scroll margins: 0 rests it against the top margin and 100 against the bottom one. A Number pins the range to that one spot. An Array of two numbers names where it lands after leaving the band through the top and after leaving it through the bottom, and so describes the band itself — nothing scrolls while the range is already inside. Ordered ([0, 50]) that is the edge it just crossed, the smallest scroll that brings it back; inverted ([50, 0]) it is the opposite edge, throwing the range across the viewport to leave the most room ahead of it. [0, 100] is the default behaviour and 50 is center. |
reversed | Scroll to the start of the range before its end when both are off-screen. (default: true) |
clip | Clip the range to the editor’s contents first. (default: true) |
Config13
#::shouldAutoIndent()
Is auto-indentation enabled for this editor?
Returns
Boolean
#::shouldAutoIndentOnPaste()
Is auto-indentation on paste enabled for this editor?
Returns
Boolean
#::getScrollPastEnd()
Does this editor allow scrolling past the last line?
Returns
Boolean
#::getScrollSensitivity()
How fast does the editor scroll in response to mouse wheel movements?
Returns
Number — positive Number.
#::getSmoothScrolling()
Are mouse wheel and scroll command movements animated?
Returns
Boolean
#::getWheelSmoothness()
How gradually does the editor glide toward the target position when scrolling with the mouse wheel?
Returns
Number — positive Number.
#::getCommandSmoothness()
How gradually does the editor glide when scrolling via the scroll commands?
Returns
Number — positive Number.
#::getAltWheelMultiplier()
Speed multiplier applied to wheel scrolling while holding
alt.
Returns
Number — positive Number.
#::getScrollCommandDistance()
Distance scrolled by the scroll commands, as a fraction of the editor height. Seeded from config; the increase/decrease scroll distance commands adjust it per editor.
Returns
Number — positive Number.
#::getSoftWrapDebounceInterval()
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.
#::doesShowLineNumbers()
Are line numbers enabled for this editor?
Returns
Boolean
#::getUndoGroupingInterval()
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.
#::getNonWordCharacters(position)
Get the characters that are not considered part of words, for the purpose of word-based cursor movements.
Returns
String — containing the non-word characters.
TextEditor Rendering2
#::getPlaceholderText()
Retrieves the greyed out placeholder of a mini editor.
Returns
String
#::setPlaceholderText(placeholderText)
Set the greyed out placeholder of a mini editor. Placeholder text will be displayed when the editor has no content.
| Argument | Description |
|---|---|
placeholderText | Stringtext that is displayed when the editor has no content. |
Language Mode Delegated Methods1
#::getCommentDelimitersForBufferPosition(point)
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.
-
point - A Point or point-compatible
Array. -
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 — Information about the appropriate comment delimiters at the buffer position.
Essential API
TextEditorElementsrc/text-editor-element.js:4
Methods8
#::getNextUpdatePromise()
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
#::getBaseCharacterWidth()
get the width of an x character displayed in this element.
Returns
Number — of pixels.
#::scrollToTop()
Scrolls the editor to the top.
#::scrollToBottom()
Scrolls the editor to the bottom.
#::pixelPositionForBufferPosition(bufferPosition)
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 | Description |
|---|---|
bufferPosition | A Point-like object that represents a buffer position. |
Returns
Object — with two values: top and left, representing the pixel position.
#::pixelPositionForScreenPosition(screenPosition)
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 | Description |
|---|---|
screenPosition | A Point-like object that represents a buffer position. |
Returns
Object — with two values: top and left, representing the pixel position.
#::invalidateBlockDecorationDimensions(blockDecoration)
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 | Description |
|---|---|
blockDecoration | DecorationThe block decoration whose dimensions should be recalculated. |
#::pinScrollAnchorToBlockDecoration(blockDecoration)
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 | Description |
|---|---|
blockDecoration | Decorationthe decoration being interactively sized |
Returns
Disposable — ends the pin
Public API
TextEditorRegistrysrc/text-editor-registry.js:97
The global registry of every TextEditor in the window, available as
lumine.textEditors.
Workspace holds the editors that are pane items; this registry holds all of them, including the ones a package builds for its own interface — a search field, a notebook cell, a REPL prompt. Reach for it when a feature should apply to editors wherever they are rather than only to open files.
Observing every editor
#observe calls back with every editor that is registered now and every one registered later:
lumine.textEditors.observe(editor => {
// every editor in the window, not just the ones in panes
})
Registering your own
A package that embeds an editor registers it so everyone else’s features
reach it too. Dispose of the returned Disposable when the editor goes
away, or the registry keeps it alive:
const editor = lumine.workspace.buildTextEditor({ mini: true })
const registration = lumine.textEditors.add(editor, { role: 'fragment' })
// …later
registration.dispose()
Roles
The role an editor is registered with says how it relates to the user’s
documents, so a cross-editor feature can tell them apart:
"document"— a standalone document: a pane item, or an embedded editor holding complete content of its own. The default."fragment"— a piece of a larger composite document: a notebook cell, a watch expression, a REPL input. Fragments share context with the editors around them."background"— an infrastructure editor mirroring content the user works on through another view, such as the JSON source behind a notebook. It is registered so configuration and services apply to it, but cross-editor features like completion sourcing leave it alone.
Registering Editors3
#::add(editor, { role = "document" } = {})
Register a TextEditor, so that features written against the registry reach it.
Throws a TypeError if role is not one of those three.
| Argument | Description |
|---|---|
editor | The TextEditor to register. |
optionsoptional | ObjectRegistration options. |
roleoptional, default: "document" | "document"|"fragment"|"background"The editor role. See TextEditorRegistry for the behavior of each. |
Returns
Disposable — on which .dispose() can be called to remove the editor again. Call it when the editor is destroyed, or the registry holds the editor alive.
#::remove(editor)
Remove a TextEditor from the registry.
Disposing the Disposable that #add returned does this for you; call it
directly only when you no longer hold that disposable.
| Argument | Description |
|---|---|
editor | The TextEditor to remove. |
Returns
Boolean — true if the editor was registered, false if it was not.
#::roleFor(editor)
Get the role a TextEditor was registered with.
Use it to tell a document apart from a notebook cell or a background mirror before applying a cross-editor feature to it.
| Argument | Description |
|---|---|
editor | The TextEditor to look up. |
Returns
String — role, or null if the editor is not registered.
Accessing Editors2
#::getEditors()
Get every registered editor.
This is a snapshot. Use #observe to keep up with editors registered later.
Returns
Array — of TextEditors.
#::getActiveTextEditor()
Get the editor the user is typing in, wherever it is.
Unlike Workspace#getActiveTextEditor this sees editors that are not pane items — a search field, a notebook cell — which is usually what a command bound to the window should act on.
The answer is resolved outward from the focused element, so it never touches (or lazily builds) the views of other registered editors, and the innermost registered editor wins when editors are nested.
Returns
TextEditor — or null if focus is not in one.
Event Subscription2
#::observe(callback)
Invoke the given callback with every registered editor, now and in the future.
The callback runs synchronously for each editor already registered, then again for each one registered afterwards.
| Argument | Description |
|---|---|
callback | Functionto be called with each TextEditor. |
editor | The TextEditor. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidRemoveEditor(callback)
Invoke the given callback when an editor is removed from the registry.
The counterpart to #observe: anything that attached state to an editor when it arrived can release it here.
| Argument | Description |
|---|---|
callback | Functionto be called with each removed TextEditor. |
editor | The TextEditor that was removed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Configuration1
#::maintainConfig(editor)
Keep a TextEditor's settings in sync with the user’s.
Applies the settings that match the editor’s language now, and keeps applying them as the user changes a setting or the editor’s language mode changes — soft wrap, tab length, invisibles, scroll behaviour and the rest. An editor built by Workspace#buildTextEditor is already maintained; call this for one you constructed yourself.
A setting the user has overridden on this editor is left alone when the language changes, so switching grammar does not undo their choice.
Calling it twice for the same editor is a no-op.
| Argument | Description |
|---|---|
editor | The TextEditor whose configuration will be maintained. |
Returns
Disposable — that stops updating the editor’s configuration.
Extended API
ThemeManagersrc/theme-manager.js:92
Handles loading and activating available themes.
An instance of this class is always available as the lumine.themes global.
Event Subscription2
#::onDidChangeActiveThemes(callback)
Invoke callback when style sheet changes associated with
updating the list of active themes have completed.
| Argument | Description |
|---|---|
callback | Function |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeThemePacks(callback)
Invoke callback when a theme pack is registered or removed.
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Accessing Available Themes5
#::registerThemePack({ name, light, dark } = {})
Register a named light/dark theme pack.
A pack groups the complete theme stacks for both appearance modes.
| Argument | Description |
|---|---|
themePack | ObjectThe theme pack. |
name | StringIts 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.
#::getThemePacks()
Returns
Array<Object> — registered theme packs sorted by their user-facing names.
#::isThemePackActive(themePack)
Returns
Boolean — whether both configured mode pairs match themePack.
#::getActiveThemePack()
Returns
Object|undefined — registered pack matching both configured mode pairs.
#::setThemePack(themePack)
Configure both appearance modes from themePack.
Accessing Loaded Themes2
Accessing Active Themes2
Managing Enabled Themes1
#::getEnabledThemeNames()
Get the enabled theme names from the config.
Returns
Array — array of theme names in the order that they should be activated.
Private1
#::updateAppearance(mutate)
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 | Description |
|---|---|
mutate | Functionapplying the change to the document. |
Returns
Promise — that resolves once the change has been applied.
Essential API
TooltipManagersrc/tooltip-manager.js:70
Associates tooltips with HTML elements.
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(target, options)
Add a tooltip to the given element.
| Argument | Description |
|---|---|
target | An HTMLElement |
options | An object with one or more of the following options: |
title | 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. |
html | 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. |
item | 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. |
class | A String with a class to apply to the tooltip element to enable custom styling. |
placement | 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. |
trigger | A String indicating how the tooltip should be displayed. Choose from one of the following options: |
'hover' | Show the tooltip when the mouse hovers over the element. This is the default. |
'click' | Show the tooltip when the element is clicked. The tooltip will be hidden after clicking the element again or anywhere else outside of the tooltip itself. |
'focus' | Show the tooltip when the element is focused. |
'manual' | Show the tooltip immediately and only hide it when the returned disposable is disposed. |
delay | 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. |
keyBindingCommand | 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. |
keyBindingTarget | An HTMLElement on which to look up the key binding. If this option is not supplied, the first of all matching key bindings for the given command will be rendered. |
keyBindingExtra | 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.
#::addComposite(target, entries)
Add several tooltip entries that are displayed together.
| Argument | Description |
|---|---|
target | An HTMLElement |
entries | 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.
#::findTooltips(target)
Find the tooltips that have been applied to the given element.
| Argument | Description |
|---|---|
target | The HTMLElement to find tooltips on. |
Returns
Array — of Tooltip objects that match the target.
Extended API
TreeSitterGrammarsrc/tree-sitter-grammar.js:33
This class holds an instance of a Tree-sitter grammar.
Methods12
#::getCommentDelimiters()
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:
#::getLanguageSync()
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.
#::getLanguage()
Retrieves the Tree-sitter language instance associated with this grammar.
Returns
Promise — that will resolve with a Tree-sitter Language instance. Once it resolves, the grammar is ready to perform parsing and to execute query captures.
#::getQuery(queryType)
Given a kind of query, retrieves a Tree-sitter Query object
in async fashion.
| Argument | Description |
|---|---|
queryType | A String describing the query type: typically one of highlightsQuery, foldsQuery, tagsQuery, or indentsQuery, but could be any other custom type. |
Returns
Promise — that resolves to a Tree-sitter Query object.
#::createQuery(queryContents)
Creates an arbitrary query from this grammar. Package authors and end users can use queries for whatever purposes they like.
| Argument | Description |
|---|---|
queryContents | A String representing the entire contents of a query file. Can contain any number of queries. |
Returns
Promise — that will resolve to a Tree-sitter Query object.
#::createQuerySync(queryContents)
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 | Description |
|---|---|
queryContents | A String representing the entire contents of a query file. Can contain any number of queries. |
Returns
Object — Tree-sitter Query object.
#::onDidChangeQuery(callback)
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 | Description |
|---|---|
callback | Function |
data | Object |
filePath | StringThe path to the query file on disk. |
queryType | StringThe type of query file, as denoted by its configuration key in the grammar file. Usually one of highlightsQuery, indentsQuery, foldsQuery, or tagsQuery. |
#::onDidChangeQueryFile(callback)
Calls callback when any of this grammar’s queries change.
Alias of #onDidChangeQuery.
#::onDidLoadQueryFiles(callback)
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.
- callback A function with the following argument:
- grammar The TreeSitterGrammar whose queries have loaded.
#::onDidAddInjectionPoint(callback)
Calls callback when an injection point is added to this
grammar.
- callback A function with the following argument:
- injectionPoint The injection point added to the grammar. See TreeSitterGrammar#addInjectionPoint.
#::onDidRemoveInjectionPoint(callback)
Calls callback when an injection point is removed from this
grammar.
- callback A function with the following argument:
- injectionPoint The injection point removed from this grammar. See TreeSitterGrammar#addInjectionPoint.
#::addInjectionPoint(injectionPoint)
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)
This differs from TextMate-style injections, which operate at the scope level and are currently incompatible with Tree-sitter grammars.
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 | Description |
|---|---|
injectionPoint | The options for the injection point: |
type | A String describing the type of node to inject into. |
language | A Function that should return a string describing the language that should be injected into this area. The string should be a short, unambiguous description of the language; it will be tested against other grammars’ injectionRegex properties. Receives one parameter: |
node | A Tree-sitter node. |
content | 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 | Booleancontrolling 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 | Booleancontrolling 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 | Booleancontrolling 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. |
coverShallowerScopesoptional | Booleancontrolling 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 | 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. |
Extended API
URIHandlerRegistrysrc/uri-handler-registry.js:75
Associates listener functions with URIs from outside the application.
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.
By default, Lumine will defer activation of your package until a URI it needs to handle
is triggered. If you need your package to activate right away, you can add
"deferActivation": false to your “uriHandler” configuration object. When activation
is deferred, once Lumine receives a request for a URI in your package’s namespace, it will
activate your package and then call methodName on it as before.
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
}
}
No documented public members.
Essential API
ViewRegistrysrc/view-registry.js:29
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
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.
Methods2
#::addViewProvider(modelConstructor, createView)
Add a provider that will be used to construct views in the workspace’s view layer based on model objects in its model layer.
Examples
Text editors are divided into a model and a view layer, so when you interact
with methods like lumine.workspace.getActiveTextEditor() you’re only going
to get the model object. We display text editors on screen by teaching the
workspace what view constructor it should use to represent them:
lumine.views.addViewProvider(TextEditor, (textEditor) => {
const textEditorElement = new TextEditorElement()
textEditorElement.initialize(textEditor)
| Argument | Description |
|---|---|
modelConstructoroptional | 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 will be called for any object. |
createView | Factory Function that is passed an instance of your model and must return a subclass of HTMLElement or undefined. If it returns undefined, then the registry will continue to search for other view providers. |
Returns
Disposable — textEditorElement }) ```; on which .dispose() can be called to remove the added provider.
#::getView(object)
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.
Returns
HTMLElement — DOM element.
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.
Methods48
#::getId()
Returns
Number — stable numeric id of the current Lumine window.
#::onWillDestroy(callback)
Subscribe before the current editor window is destroyed.
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::whenLoaded()
Wait until the current editor window has finished loading.
Returns
Promise — resolving to the load time in milliseconds.
#::isDevMode()
Determine whether the current window is in development mode.
#::isSafeMode()
Determine whether the current window is in safe mode.
#::isSpecMode()
Determine whether the current window is running specs.
#::isHeadless()
Determine whether the current window is running headlessly.
#::getInitialPaths()
Returns
Array<String> — paths supplied when the current window was opened.
#::getLoadTime()
Returns
Number|null — The completed window load time in milliseconds, or null before loading completes.
#::getStartupMarkers()
Returns
Object — startup timing markers for the current window.
#::getState()
Returns
Promise<Object> — A serializable state snapshot with id, position, size, maximized, fullScreen, and visible fields.
#::getSize()
Returns
Promise<Object> — The current content size as {width, height}.
#::setSize(width, height)
Set the content size.
| Argument | Description |
|---|---|
width | A finite Number in pixels. |
height | A finite Number in pixels. |
Returns
Promise — that resolves when the request is applied.
#::getPosition()
Returns
Promise<Object> — The current screen position as {x, y}.
#::setPosition(x, y)
Set the current screen position.
| Argument | Description |
|---|---|
x | A finite Number in pixels. |
y | A finite Number in pixels. |
Returns
Promise — that resolves when the request is applied.
#::center()
Center the current window on its display.
Returns
Promise — that resolves when the request is applied.
#::focus()
Focus the current window.
Returns
Promise — that resolves when the request is applied.
#::show()
Show the current window and restore its focus policy.
Returns
Promise — that resolves when the request is applied.
#::hide()
Hide the current window.
Returns
Promise — that resolves when the request is applied.
#::close()
Close the current window.
Returns
Promise — that resolves when the close request is accepted.
#::reload()
Reload the current window.
Returns
Promise — that resolves after the reloaded renderer reports ready.
#::minimize()
Minimize the current window.
Returns
Promise — that resolves when the request is applied.
#::maximize()
Maximize the current window.
Returns
Promise — that resolves when the request is applied.
#::unmaximize()
Restore a maximized window.
Returns
Promise — that resolves when the request is applied.
#::isMaximized()
Determine whether the current window is maximized.
Returns
Promise — resolving to a Boolean.
#::isFullScreen()
Determine whether the current window is full screen.
Returns
Promise — resolving to a Boolean.
#::isVisible()
Determine whether the current window is visible.
Returns
Promise — resolving to a Boolean.
#::setFullScreen(fullScreen = false)
Enter or leave full-screen mode.
| Argument | Description |
|---|---|
fullScreen | A Boolean indicating the desired state. |
Returns
Promise — that resolves when the request is applied.
#::toggleFullScreen()
Toggle full-screen mode.
Returns
Promise — that resolves when the request is applied.
#::pickFolder()
Ask the user to select one or more folders.
Returns
Promise — resolving to an Array of paths, or null on cancellation.
#::showSaveDialog(options = {})
Show a save dialog owned by the current window.
| Argument | Description |
|---|---|
options | Serializable Electron save-dialog options. |
Returns
Promise — resolving to Electron’s serializable save-dialog result.
#::confirm(options)
Show a non-blocking confirmation dialog owned by the current window.
Returns
Promise — resolving to the selected button index.
#::downloadURL(url)
Start a download in the current window.
| Argument | Description |
|---|---|
url | The String URL to download. |
Returns
Promise — that resolves when the download is started.
#::getPrimaryDisplayWorkAreaSize()
Returns
Promise<Object> — The primary display’s available work-area size as {width, height}.
#::setAutoHideMenuBar(autoHide)
Control whether the menu bar hides automatically.
Returns
Promise — that resolves when the request is applied.
#::setMenuBarVisibility(visible)
Show or hide the menu bar.
Returns
Promise — that resolves when the request is applied.
#::openDevTools()
Open the current window’s developer tools.
Returns
Promise — that resolves when the request is applied.
#::closeDevTools()
Close the current window’s developer tools.
Returns
Promise — that resolves when the request is applied.
#::toggleDevTools()
Toggle the current window’s developer tools.
Returns
Promise — that resolves when the request is applied.
#::executeJavaScriptInDevTools(code)
Evaluate JavaScript in the current window’s developer tools.
Returns
Promise — that resolves after evaluation, or immediately when developer tools are closed.
#::broadcast(eventName, ...args)
Send a serializable event to every other registered Lumine window.
| Argument | Description |
|---|---|
eventName | A non-empty String event name. |
...args | Structured-cloneable values delivered to subscribers. |
Returns
Promise — that resolves after the event is sent.
#::onDidReceive(eventName, callback)
Subscribe to named events broadcast by other Lumine windows.
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidEnterFullScreen(callback)
Invoke callback after entering full-screen mode.
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidLeaveFullScreen(callback)
Invoke callback after leaving full-screen mode.
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidMaximize(callback)
Invoke callback after the window is maximized.
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidUnmaximize(callback)
Invoke callback after a maximized window is restored.
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidFocus(callback)
Invoke callback when the window gains focus.
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidBlur(callback)
Invoke callback when the window loses focus.
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Essential API
Workspacesrc/workspace.js:332
Represents the state of the user interface for the entire window.
An instance of this class is available via the lumine.workspace global.
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
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.
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 name of an icon. If this method is defined and
returns a string, the item’s tab element will be rendered with the icon and
icon-${iconName} CSS classes.
onDidChangeIcon(callback)
Called by the workspace 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'.
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.
isModified()
Returns whether or not the item is modified to reflect modification in the UI.
onDidChangeModified()
Called by the workspace so it can be notified when item’s modified status
changes. Must return a Disposable.
copy()
Create a copy of the item. If defined, the workspace will call this method to duplicate the item when splitting panes via certain split commands.
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.
Methods1
#::clear(options = {})
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 | Description |
|---|---|
options | An optional Object that may contain the following key: |
locations | An Array of the pane container locations to empty. Defaults to all four. |
Returns
Promise — that resolves once they are empty.
Event Subscription22
#::observeTextEditors(callback)
Invoke the given callback with all current and future text editors in the workspace.
| Argument | Description |
|---|---|
callback | Functionto be called with current and future text editors. |
editor | 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.
#::observePaneItems(callback)
Invoke the given callback with all current and future panes items in the workspace.
| Argument | Description |
|---|---|
callback | Functionto 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.
#::onDidChangeActivePaneItem(callback)
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 | Description |
|---|---|
callback | Functionto be called when the active pane item changes. |
item | The active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidStopChangingActivePaneItem(callback)
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 | Description |
|---|---|
callback | Functionto be called when the active pane item stops changing. |
item | The active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeActiveTextEditor(callback)
Invoke the given callback when a text editor becomes the active text editor and when there is no longer an active text editor.
| Argument | Description |
|---|---|
callback | Functionto be called when the active text editor changes. |
editor | The active TextEditor or undefined if there is no longer an active text editor. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeActivePaneItem(callback)
Invoke the given callback with the current active pane item and with all future active pane items in the workspace.
| Argument | Description |
|---|---|
callback | Functionto be called when the active pane item changes. |
item | The current active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeActiveTextEditor(callback)
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 | Description |
|---|---|
callback | Functionto be called when the active text editor changes. |
editor | The active TextEditor or undefined if there is not an active text editor. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeActiveFileTextEditor(callback)
Invoke the given callback when the editor holding the active item’s file content changes. See #getActiveFileTextEditor.
| Argument | Description |
|---|---|
callback | Functionto be called when the resolved editor changes. |
editor | The resolved TextEditor or undefined. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeActiveFileTextEditor(callback)
Invoke the given callback with the current and all future editors holding the active item’s file content. See #getActiveFileTextEditor.
| Argument | Description |
|---|---|
callback | Functionto be called when the resolved editor changes. |
editor | The resolved TextEditor or undefined. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeActiveEmbeddedTextEditor(callback)
Invoke the given callback when the editor being edited inside the active item changes. See #getActiveEmbeddedTextEditor.
| Argument | Description |
|---|---|
callback | Functionto be called when the resolved editor changes. |
editor | The resolved TextEditor or undefined. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeActiveEmbeddedTextEditor(callback)
Invoke the given callback with the current and all future editors being edited inside the active item. See #getActiveEmbeddedTextEditor.
| Argument | Description |
|---|---|
callback | Functionto be called when the resolved editor changes. |
editor | The resolved TextEditor or undefined. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidOpen(callback)
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 | Description |
|---|---|
callback | Functionto be called whenever an item is opened. |
event | Objectwith the following keys: |
uri | Stringrepresenting the opened URI. Could be undefined. |
item | The opened item. |
pane | The pane in which the item was opened. |
index | The index of the opened item on its pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidAddPane(callback)
Invoke the given callback when a pane is added to the workspace.
| Argument | Description |
|---|---|
callback | Functionto be called when panes are added. |
event | Objectwith the following keys: |
pane | The added pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onWillDestroyPane(callback)
Invoke the given callback before a pane is destroyed in the workspace.
| Argument | Description |
|---|---|
callback | Functionto be called before panes are destroyed. |
event | Objectwith the following keys: |
pane | The pane to be destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDestroyPane(callback)
Invoke the given callback when a pane is destroyed in the workspace.
| Argument | Description |
|---|---|
callback | Functionto be called when panes are destroyed. |
event | Objectwith the following keys: |
pane | The destroyed pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observePanes(callback)
Invoke the given callback with all current and future panes in the workspace.
| Argument | Description |
|---|---|
callback | Functionto be called with current and future panes. |
pane |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeActivePane(callback)
Invoke the given callback when the active pane changes.
| Argument | Description |
|---|---|
callback | Functionto be called when the active pane changes. |
pane | A Pane that is the current return value of #getActivePane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeActivePane(callback)
Invoke the given callback with the current active pane and when the active pane changes.
| Argument | Description |
|---|---|
callback | Functionto be called with the current and future active panes. |
pane | A Pane that is the current return value of #getActivePane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidAddPaneItem(callback)
Invoke the given callback when a pane item is added to the workspace.
| Argument | Description |
|---|---|
callback | Functionto be called when pane items are added. |
event | Objectwith the following keys: |
item | The added pane item. |
pane | Panecontaining the added item. |
index | Numberindicating the index of the added item in its pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onWillDestroyPaneItem(callback)
Invoke the given callback when a pane item is about to be destroyed, before the user is prompted to save it.
| Argument | Description |
|---|---|
callback | Functionto 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 | Objectwith the following keys: |
item | The item to be destroyed. |
pane | Panecontaining the item to be destroyed. |
index | Numberindicating the index of the item to be destroyed in its pane. |
Returns
Disposable — on which .dispose can be called to unsubscribe.
#::onDidDestroyPaneItem(callback)
Invoke the given callback when a pane item is destroyed.
| Argument | Description |
|---|---|
callback | Functionto be called when pane items are destroyed. |
event | Objectwith the following keys: |
item | The destroyed item. |
pane | Panecontaining the destroyed item. |
index | Numberindicating the index of the destroyed item in its pane. |
Returns
Disposable — on which .dispose can be called to unsubscribe.
#::onDidAddTextEditor(callback)
Invoke the given callback when a text editor is added to the workspace.
| Argument | Description |
|---|---|
callback | Functionto be called when text editors are added. |
event | Objectwith the following keys: |
textEditor | TextEditorthat was added. |
pane | Panecontaining the added text editor. |
index | Numberindicating the index of the added text editor in its pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Opening8
#::open(itemOrURI, options = {})
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.
| Argument | Description |
|---|---|
itemOrURIoptional | An item to open or a String containing a URI. |
optionsoptional | Object |
initialLine | A Number indicating which row to move the cursor to initially. Defaults to 0. |
initialColumn | A Number indicating which column to move the cursor to initially. Defaults to 0. |
split | 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. |
activatePane | |
activateItem | |
pending | 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. |
searchAllPanes | 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 | 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 — that resolves to the TextEditor for the file URI.
#::hide(itemOrURI)
Search the workspace for items matching the given URI and hide them.
| Argument | Description |
|---|---|
itemOrURI | The item to hide or a String containing the URI of the item to hide. |
Returns
Boolean — indicating whether any items were found (and hidden).
#::toggle(itemOrURI)
Search the workspace for items matching the given URI. If any are found, hide them. Otherwise, open the URL.
| Argument | Description |
|---|---|
itemOrURIoptional | The item to toggle or a String containing the URI of the item to toggle. |
Returns
Promise — Promise that resolves when the item is shown or hidden.
#::createItemForURI(uri, options)
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 | Description |
|---|---|
uri | A String containing a URI. |
Returns
Promise — that resolves to the TextEditor (or other item) for the given URI.
#::isTextEditor(object)
| Argument | Description |
|---|---|
object | An Object you want to perform the check against. |
Returns
Boolean — that is true if object is a TextEditor.
#::buildTextEditor(params)
Create a new text editor.
Returns
#::buildSelectList(props)
Create a fuzzy-searchable list shown in a modal panel.
The editor ships the implementation, so a package neither depends on it nor pins it, and a window holds exactly one copy of it. This is a factory, not a shared instance: every call returns a list that owns its own panel, so a renderer that throws takes down one package’s list rather than all of them.
The list owns its panel. Do not call #addModalPanel for it — show(),
hide() and toggle() manage a hidden-until-shown modal panel created on
first use, and getPanel() returns it.
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.
| Argument | Description |
|---|---|
props | An Object describing the list. The two that matter most: |
items | An Array of the objects to show. |
elementForItem | A Function called as (item, options) to render a row. Return an HTMLElement, or an Object with primary and an optional secondary, icon, className and trailing to have a row built for you. options carries selected, index, filterKey, visible, a lazily computed matchIndices, and highlight(text, indices) — which wraps the matched characters of text in span.character-match, defaulting to this item’s own indices. |
Returns
SelectListView
#::buildInputDialog(props)
Create a modal dialog whose query editor is the value.
The base of #buildSelectList without the list: a modal panel with a mini
editor, for prompts and save dialogs where the typed text is the answer.
Extra DOM goes above the editor via headerElement, below it via
contentElement, and a checkboxes row can bind straight to lumine.config.
Panel ownership is the same as #buildSelectList — the dialog creates and owns its own modal panel.
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.
| Argument | Description |
|---|---|
props | An Object describing the dialog, including didConfirm(query), didCancel() and didChangeQuery(query). |
Returns
InputDialogView
Modal flow6
#::popModal()
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.
Returns
Boolean — — false when there is no step to go back to.
#::popModalTo(index)
Jump back to an earlier step of the modal breadcrumb trail.
| Argument | Description |
|---|---|
index | 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.
#::getModalTrail()
The current modal breadcrumb trail.
Returns
Array — of String labels, root first; empty when no flow is active.
#::onDidChangeModalTrail(callback)
Invoke the given callback whenever the modal breadcrumb trail changes — a step is entered, the flow goes back, or the trail ends.
| Argument | Description |
|---|---|
callback | Functionreceiving the trail as #getModalTrail reports it. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::reopenItem()
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
#::addOpener(opener)
Register an opener for a 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 (path.extname(uri) === '.toml') return new TomlEditor(uri)
})
Note that the opener will be called if and only if the URI is not already open
in the current pane. The searchAllPanes flag expands the search from the
current pane to all panes. If you wish to open a view of a different type for
a file that is already open, consider changing the protocol of the URI. For
example, perhaps you wish to preview a rendered version of the file /foo/bar/baz.quux
that is already open in a text editor view. You could signal this by calling
Workspace#open on the URI quux-preview://foo/bar/baz.quux. Then your opener
can check the protocol for quux-preview and only handle those URIs that match.
To defer your package’s activation until a specific URL is opened, add a
workspaceOpeners field to your package.json containing an array of URL
strings.
| Argument | Description |
|---|---|
opener | A Function to be called when a path is being opened. |
Returns
Disposable — on which .dispose() can be called to remove the opener.
Pane Items9
#::getPaneItems()
Get all pane items in the workspace.
Returns
Array — of items.
#::getActivePaneItem()
Get the active Pane's active item.
Returns
Object — pane item Object.
#::getTextEditors()
Get all text editors in the workspace, if they are pane items.
Returns
Array — of TextEditors.
#::getActiveTextEditor()
Get the workspace center’s active item if it is a TextEditor.
Returns
TextEditor — or undefined if the workspace center’s current active item is not a TextEditor.
#::getActiveFileTextEditor()
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.
#::getActiveEmbeddedTextEditor()
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.
#::saveActivePaneItem()
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.
#::saveActivePaneItemAs()
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.
#::destroyActivePaneItem()
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, whose keystrokes fire from anywhere in the window, so
following focus would make Ctrl-S in a search field or a dock try to save
that instead of the document being edited.
Panes10
#::getActivePaneContainer()
Get the most recently focused pane container.
Returns
Dock — or the WorkspaceCenter.
#::getPanes()
Get all panes in the workspace.
Returns
Array — of Panes.
#::getActivePane()
Get the active Pane.
Returns
#::activateNextPane()
Make the next pane active.
#::activatePreviousPane()
Make the previous pane active.
#::paneContainerForURI(uri)
Get the first pane container that contains an item with the given URI.
| Argument | Description |
|---|---|
uri | Stringuri |
Returns
Dock — the WorkspaceCenter, or undefined if no item exists with the given URI.
#::paneContainerForItem(item)
Get the first pane container that contains the given item.
| Argument | Description |
|---|---|
item | the Item that the returned pane container must contain. |
Returns
Dock — the WorkspaceCenter, or undefined if no pane container contains the given item.
#::paneForURI(uri)
Get the first Pane that contains an item with the given URI.
| Argument | Description |
|---|---|
uri | Stringuri |
Returns
Pane — or undefined if no item exists with the given URI.
#::paneForItem(item)
Get the Pane containing the given item.
| Argument | Description |
|---|---|
item | the Item that the returned pane must contain. |
Returns
Pane — or undefined if no pane exists for the given item.
#::closeActivePaneItemOrEmptyPaneOrWindow()
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.
Pane Locations5
#::getCenter()
Get the WorkspaceCenter at the center of the editor window.
#::getLeftDock()
Get the Dock to the left of the editor window.
#::getRightDock()
Get the Dock to the right of the editor window.
#::getBottomDock()
Get the Dock below the editor window.
#::beginLayoutDrag()
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 drag 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.
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.
Panels15
#::getBottomPanels()
Get an Array of all the panel items at the bottom of the editor window.
#::addBottomPanel(options)
Adds a panel item to the bottom of the editor window.
| Argument | 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 | Booleanfalse if you want the panel to initially be hidden (default: true) |
priorityoptional | NumberDetermines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100) |
Returns
#::getLeftPanels()
Get an Array of all the panel items to the left of the editor window.
#::addLeftPanel(options)
Adds a panel item to the left of the editor window.
| Argument | 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 | Booleanfalse if you want the panel to initially be hidden (default: true) |
priorityoptional | NumberDetermines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100) |
Returns
#::getRightPanels()
Get an Array of all the panel items to the right of the editor window.
#::addRightPanel(options)
Adds a panel item to the right of the editor window.
| Argument | 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 | Booleanfalse if you want the panel to initially be hidden (default: true) |
priorityoptional | NumberDetermines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100) |
Returns
#::getTopPanels()
Get an Array of all the panel items at the top of the editor window.
#::addTopPanel(options)
Adds a panel item to the top of the editor window above the tabs.
| Argument | 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 | Booleanfalse if you want the panel to initially be hidden (default: true) |
priorityoptional | NumberDetermines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100) |
Returns
#::getHeaderPanels()
Get an Array of all the panel items in the header.
#::addHeaderPanel(options)
Adds a panel item to the header.
| Argument | 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 | Booleanfalse if you want the panel to initially be hidden (default: true) |
priorityoptional | NumberDetermines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100) |
Returns
#::getFooterPanels()
Get an Array of all the panel items in the footer.
#::addFooterPanel(options)
Adds a panel item to the footer.
| Argument | 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 | Booleanfalse if you want the panel to initially be hidden (default: true) |
priorityoptional | NumberDetermines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100) |
Returns
#::getModalPanels()
Get an Array of all the modal panel items
#::addModalPanel(options = {})
Adds a panel item as a modal dialog.
| Argument | Description |
|---|---|
options | 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. |
visibleoptional | Booleanfalse if you want the panel to initially be hidden (default: true) |
priorityoptional | NumberDetermines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100) |
autoFocusoptional | Boolean|Elementtrue 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 | Booleanfalse 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) |
crumboptional | Stringthe 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
#::panelForItem(item)
| Argument | Description |
|---|---|
item | Item the panel contains |
Returns
Panel — associated with the given item. Returns null when the item has no panel.
Searching and Replacing3
#::scan(regex, options = {}, iterator)
Performs a search across all files in the workspace.
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 | Description |
|---|---|
regex | RegExpto search with. |
optionsoptional | Object |
iterator | Functioncallback on each file found. |
paths | An Array of glob patterns to search within. (See note below for multi-root projects.) |
includeVcsIgnoredPaths | Booleandefault false; Whether to include paths excluded by VCS ignore files, regardless of the core preference. |
onPathsSearchedoptional | Functionto be periodically called with number of paths searched. |
leadingContextLineCount | Numberdefault 0; The number of lines before the matched line to include in the results object. |
trailingContextLineCount | Numberdefault 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.
#::replace(regex, replacementText, filePaths, iterator)
Performs a replace across all the specified files in the project.
| Argument | Description |
|---|---|
regex | A RegExp to search with. |
replacementText | Stringto replace all matches of regex with. |
filePaths | An Array of file path strings to run the replace on. |
iterator | A Function callback on each file with replacements: |
options | Objectwith keys filePath and replacements. |
Returns
Promise
#::filePathMatchesPatterns(filePath, rawPatterns)
Tests the path of a file in the project against a set of globs (using the same semantics as #scan) and reports whether the file satisfies the patterns.
Internally, this method is used to decide if a search result should be added to a list of project-wide search results.
| Argument | Description |
|---|---|
filePath | Stringrepresenting the absolute path to a file in the project. (Any external path will automatically return false.) |
rawPatterns | Arrayof strings that describe glob patterns. Identical to (and uses the same glob semantics as) the options.paths argument of #scan. |
Returns
Boolean — boolean indicating whether the given file path would be included in a project-wide search if the given path patterns were specified.
Essential API
WorkspaceCentersrc/workspace-center.js:12
Represents the workspace at the center of the entire window.
Event Subscription15
#::observeTextEditors(callback)
Invoke the given callback with all current and future text editors in the workspace center.
| Argument | Description |
|---|---|
callback | Functionto be called with current and future text editors. |
editor | 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.
#::observePaneItems(callback)
Invoke the given callback with all current and future panes items in the workspace center.
| Argument | Description |
|---|---|
callback | Functionto 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.
#::onDidChangeActivePaneItem(callback)
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 | Description |
|---|---|
callback | Functionto be called when the active pane item changes. |
item | The active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidStopChangingActivePaneItem(callback)
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 | Description |
|---|---|
callback | Functionto be called when the active pane item stops changing. |
item | The active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeActivePaneItem(callback)
Invoke the given callback with the current active pane item and with all future active pane items in the workspace center.
| Argument | Description |
|---|---|
callback | Functionto be called when the active pane item changes. |
item | The current active pane item. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidAddPane(callback)
Invoke the given callback when a pane is added to the workspace center.
| Argument | Description |
|---|---|
callback | Functionto be called when panes are added. |
event | Objectwith the following keys: |
pane | The added pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onWillDestroyPane(callback)
Invoke the given callback before a pane is destroyed in the workspace center.
| Argument | Description |
|---|---|
callback | Functionto be called before panes are destroyed. |
event | Objectwith the following keys: |
pane | The pane to be destroyed. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidDestroyPane(callback)
Invoke the given callback when a pane is destroyed in the workspace center.
| Argument | Description |
|---|---|
callback | Functionto be called when panes are destroyed. |
event | Objectwith the following keys: |
pane | The destroyed pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observePanes(callback)
Invoke the given callback with all current and future panes in the workspace center.
| Argument | Description |
|---|---|
callback | Functionto be called with current and future panes. |
pane |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidChangeActivePane(callback)
Invoke the given callback when the active pane changes.
| Argument | Description |
|---|---|
callback | Functionto be called when the active pane changes. |
pane | A Pane that is the current return value of #getActivePane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::observeActivePane(callback)
Invoke the given callback with the current active pane and when the active pane changes.
| Argument | Description |
|---|---|
callback | Functionto be called with the current and future active panes. |
pane | A Pane that is the current return value of #getActivePane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onDidAddPaneItem(callback)
Invoke the given callback when a pane item is added to the workspace center.
| Argument | Description |
|---|---|
callback | Functionto be called when pane items are added. |
event | Objectwith the following keys: |
item | The added pane item. |
pane | Panecontaining the added item. |
index | Numberindicating the index of the added item in its pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
#::onWillDestroyPaneItem(callback)
Invoke the given callback when a pane item is about to be destroyed, before the user is prompted to save it.
| Argument | Description |
|---|---|
callback | Functionto be called before pane items are destroyed. |
event | Objectwith the following keys: |
item | The item to be destroyed. |
pane | Panecontaining the item to be destroyed. |
index | Numberindicating the index of the item to be destroyed in its pane. |
Returns
Disposable — on which .dispose can be called to unsubscribe.
#::onDidDestroyPaneItem(callback)
Invoke the given callback when a pane item is destroyed.
| Argument | Description |
|---|---|
callback | Functionto be called when pane items are destroyed. |
event | Objectwith the following keys: |
item | The destroyed item. |
pane | Panecontaining the destroyed item. |
index | Numberindicating the index of the destroyed item in its pane. |
Returns
Disposable — on which .dispose can be called to unsubscribe.
#::onDidAddTextEditor(callback)
Invoke the given callback when a text editor is added to the workspace center.
| Argument | Description |
|---|---|
callback | Functionto be called when panes are added. |
event | Objectwith the following keys: |
textEditor | TextEditorthat was added. |
pane | Panecontaining the added text editor. |
index | Numberindicating the index of the added text editor in its pane. |
Returns
Disposable — on which .dispose() can be called to unsubscribe.
Pane Items4
#::getPaneItems()
Get all pane items in the workspace center.
Returns
Array — of items.
#::getActivePaneItem()
Get the active Pane's active item.
Returns
Object — pane item Object.
#::getTextEditors()
Get all text editors in the workspace center.
Returns
Array — of TextEditors.
#::getActiveTextEditor()
Get the active item if it is an TextEditor.
Returns
TextEditor — or undefined if the current active item is not an TextEditor.
Panes4
Public API
Functions
#applySyntaxHighlighting(content, givenOpts = {}, givenOpts.syntaxScopeNameFunc, givenOpts.renderMode, givenOpts.grammar, givenOpts.autoWidth)
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 | Description |
|---|---|
content | HTMLFragmentThe HTML Node/Fragment to apply syntax highlighting on. Will modify the original object. |
givenOpts | objectOptional Arguments: |
syntaxScopeNameFunc | functionA 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. |
renderMode | stringWhether we are rendering a document fragment or a full document. Valid values: “full”, “fragment”. |
grammar | objectThe grammar of the source file. Carryover from original markdown-preview functionality. |
autoWidth | booleanWhether 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. |
#convertToDOM(content)
Takes a raw HTML string of data and returns a proper HTMLFragment. This should be done if you need access to APIs available on the DOM itself.
| Argument | Description |
|---|---|
content | stringThe HTML String. |
Returns
HTMLFragment
#matcherForSelector(selector)
Build a reusable test for a scope selector.
Parsing the selector once and testing many scopes with the result is what
makes this worth having over selectorMatchesAnyScope in a loop.
| Argument | Description |
|---|---|
selector | A String selector such as "source.js", or an Array of the parts it is made of. An empty selector matches everything. |
Returns
Function — taking a scope String and returning a Boolean, true when the scope matches the selector.
#removeDiacritics(text)
Removes diacritical marks from a string, so that “café” can be matched by typing “cafe”.
| Argument | Description |
|---|---|
text | stringThe string to fold. |
Returns
string — The same string with its diacritics removed.
#renderMarkdown(content, givenOpts = {}, givenOpts.renderMode, givenOpts.html, givenOpts.sanitize, givenOpts.sanitizeAllowUnknownProtocols, givenOpts.sanitizeAllowSelfClose, givenOpts.breaks, givenOpts.handleFrontMatter, givenOpts.useDefaultEmoji, givenOpts.useGitHubHeadings, givenOpts.useTaskCheckbox, givenOpts.taskCheckboxDisabled, givenOpts.taskCheckboxDivWrap, givenOpts.transformImageLinks, givenOpts.transformNonFqdnLinks, givenOpts.rootDomain, givenOpts.filePath, givenOpts.disableMode)
Takes a Markdown document and renders it as HTML.
| Argument | Description |
|---|---|
content | stringThe Markdown source material. |
givenOpts | objectThe optional arguments: |
renderMode | stringDetermines how the page is rendered. Valid values “full” or “fragment”. |
html | booleanWhether HTML tags should be allowed. |
sanitize | booleanIf the page content should be saniized via DOMPurify. |
sanitizeAllowUnknownProtocols | booleanControls DOMPurify’s own option of ‘ALLOW_UNKNOWN_PROTOCOLS’. |
sanitizeAllowSelfClose | booleanControls DOMPurify’s own option of ‘ALLOW_SELF_CLOSE’ |
breaks | booleanIf newlines should always be converted into breaklines. |
handleFrontMatter | booleanWhether frontmatter data should processed and displayed. |
useDefaultEmoji | booleanWhether markdown-it-emoji should be enabled. |
useGitHubHeadings | booleanWhether markdown-it-github-headings should be enabled. False by default. |
useTaskCheckbox | booleanWhether markdown-it-task-checkbox should be enabled. True by default. |
taskCheckboxDisabled | booleanControls markdown-it-task-checkbox disabled option. True by default. |
taskCheckboxDivWrap | booleanControls markdown-it-task-checkbox divWrap option. False by default. |
transformImageLinks | booleanAttempt to resolve image URLs. True by default. |
transformNonFqdnLinks | booleanAttempt to resolve links that are not fully qualified domain names. True by default. |
rootDomain | stringThe root URL of the online resource. Useful when attempting to resolve any links on the page. Only works for online resources. |
filePath | stringThe local alternative to rootDomain. Used to resolve incomplete paths, but locally on the file system. |
disableMode | stringThe level of disabling of markdown features. none by default. But supports: “none”, “strict” |
Returns
string — Parsed HTML content.
#selectorMatchesAnyScope(selector, scopes)
Whether any of the given scopes matches a selector.
| Argument | Description |
|---|---|
selector | A String selector. An empty selector matches everything. |
scopes | An Array of scope Strings to test. |
Returns
Boolean
#watchFile(filePath)
Watch a single file for changes, deletion, and renaming. This is
the replacement for the old File watching API: it exposes just the change
notifications, backed by watchPath.
Subscriptions register synchronously, but the underlying watcher is armed
asynchronously by the file-watcher worker. Tests that need to observe the
very first change should await handle.getStartPromise() before writing.
onDidChange(callback)invokecallbackwhen the file is created or its contents change. Returns aDisposable.onDidDelete(callback)invokecallbackwhen the file is deleted (or renamed away from this path). Returns aDisposable.onDidRename(callback)invokecallbackwith the new path when the file is renamed onto a sibling path. Returns aDisposable.getStartPromise()aPromisethat resolves once the watcher is armed.dispose()stop watching and release the subscription.
| Argument | Description |
|---|---|
filePath | Stringabsolute path to the file to watch. |
Returns
Object — with:
#watchPath(rootPath, options, eventCallback, options.realPaths, eventCallback.events, eventCallback.events.action, eventCallback.events.path, eventCallback.events.oldPath)
Invoke a callback with each filesystem event that occurs beneath a specified path. If you only need to watch events within the project’s root paths, use Project#onDidChangeFiles instead.
watchPath handles the efficient re-use of operating system resources across living watchers. Watching the same path more than once, or the child of a watched path, will re-use the existing native watcher.
const {watchPath} = require('lumine')
const disposable = await watchPath('/var/log', {}, events => {
console.log(`Received batch of ${events.length} events.`)
for (const event of events) {
// "created", "updated", "deleted", "renamed"
console.log(`Event action: ${event.action}`)
// absolute path to the filesystem entry that was touched
console.log(`Event path: ${event.path}`)
if (event.action === 'renamed') {
console.log(`.. renamed from: ${event.oldPath}`)
}
}
})
// Immediately stop receiving filesystem events. If this is the last
// watcher, asynchronously release any OS resources required to subscribe
// to these events.
disposable.dispose()
| Argument | Description |
|---|---|
rootPath | Stringspecifies the absolute path to the root of the filesystem content to watch. |
options | Control the watcher’s behavior: |
eventCallback | Functionor other callable to be called each time a batch of filesystem events is observed. |
realPaths | BooleanWhether to report real paths on disk for filesystem events. Default is true; false reports paths that descend from rootPath even when symlinks point elsewhere. |
events | Arrayof objects that describe the events that have occurred. |
action | Stringdescribing the filesystem action that occurred. One of "created", "updated", "deleted", or "renamed". A recursive watch never reports "renamed": it reports a move as a "deleted" and a "created". |
path | Stringcontaining the absolute path to the filesystem entry that was acted upon. |
oldPath | For rename events, String containing the filesystem entry’s former absolute path. |
Returns
Promise<PathWatcher> — A promise resolving to the started watcher. Every watcher is also a Disposable.