Generated documentation

Lumine API reference

Public APIs extracted directly from Lumine’s JSDoc source comments.

Version 1.0.0 · 57 classes · 1232 documented members

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

#::deserializeTimingsObject<string, number>

PublicL166

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 {}.

#::toolsObject

PublicL478

Editor utilities a package can reuse instead of vendoring its own: markdown, fuzzyMatcher, and removeDiacritics.

Public API

ApplicationServicesrc/application-service.js:11

Main-process application services exposed as serializable values.

Methods16

#::getPath(name)

PublicL25

Return an Electron application path captured during bootstrap.

ArgumentDescription
name
String
A supported Electron application-path name.
Returns

StringThe cached path synchronously.

#::getLocale()

PublicL39

Return the application locale captured during bootstrap.

Returns

StringThe cached locale synchronously.

#::getResourcePath()

PublicL51

Return the editor resource directory captured during bootstrap.

Returns

StringThe absolute resource path synchronously.

#::getName()

PublicL63

Return the full name of this Lumine application.

Returns

StringThe application name synchronously.

#::getVersion()

PublicL75

Return the Lumine application version.

Returns

StringThe version synchronously.

#::versionSatisfies(range)

PublicL89

Determine whether the current application version satisfies a semantic-version range.

ArgumentDescription
range
String
A semantic-version range.
Returns

BooleanWhether the current version satisfies the range.

#::getReleaseChannel()

PublicL102

Return the current release channel.

Returns

StringThe release channel.

#::isReleasedVersion()

PublicL114

Determine whether this build came from the release pipeline.

Returns

BooleanWhether this is a released build.

#::openWindow(params)

PublicL128

Open paths in a new or reusable Lumine window.

The call returns immediately after sending the request to the main process.

ArgumentDescription
params
Object
Paths and window options to open.

#::getUserDefault(key, type)

PublicL140

Read an operating-system user default.

Returns

Promiseresolving to a serializable preference value.

#::getAccentColor()

PublicL153

Read the operating system’s accent color.

Returns

Promiseresolving to a #rrggbb string, or null where the platform has no accent color to report.

#::printToPDF(html, outputPath, options = {})

PublicL175

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.

ArgumentDescription
html
String
A complete HTML document. Reference assets by data URI: nothing relative to the calling document resolves.
outputPath
String
Where to write the PDF.
optionsoptional
Object
Electron printToPDF options. printBackground defaults to true.
Returns

Promiseresolving to {outcome: 'success', result: outputPath}, or {outcome: 'failure', error} when the document could not be printed.

#::isDefaultProtocolClient(protocol, path, args)

PublicL187

Determine whether Lumine is the default handler for a protocol.

Returns

Promiseresolving to a Boolean.

#::setAsDefaultProtocolClient(protocol, path, args)

PublicL199

Register Lumine as the default handler for a protocol.

Returns

Promiseresolving to a Boolean.

#::getFileIcon(filePath, options = {})

PublicL211

Load an operating-system file icon as a data URL.

ArgumentDescription
optionsoptional, default: {}
No description.
Returns

Promiseresolving to a data-URL String, or null.

#::restart()

PublicL223

Restart Lumine with the current launch options.

Returns

Promisethat 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 })

PublicL39

Runs the given Node script by spawning a new child process.

ArgumentDescription
options
Object
Process options.
command
String
Path to the JavaScript script.
argsoptional
Array<String>
Arguments passed to the script.
optionsoptional
Object
Options passed to Node’s ChildProcess.spawn.
stdoutoptional
Function
Receives buffered, complete lines of standard output and any remaining data when the stream closes.
data
String
Standard-output data.
stderroptional
Function
Receives buffered, complete lines of standard error and any remaining data when the stream closes.
data
String
Standard-error data.
exitoptional
Function
Receives the process exit status.
code
Number
The exit status.

Extended API

BufferedProcesssrc/buffered-process.js:25

A wrapper which provides standard error/output line buffering for Node’s ChildProcess.

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 } = {})

PublicL51

Runs the given command by spawning a new child process.

ArgumentDescription
optionsoptional
Object
Process options.
command
String
The command to execute.
argsoptional
Array<String>
Arguments passed to the command.
optionsoptional
Object
Options passed to Node’s ChildProcess.spawn.
stdoutoptional
Function
Receives buffered, complete lines of standard output and any remaining data when the stream closes.
data
String
Standard-output data.
stderroptional
Function
Receives buffered, complete lines of standard error and any remaining data when the stream closes.
data
String
Standard-error data.
exitoptional
Function
Receives the process exit status.
code
Number
The exit status.
autoStartoptional, default: true
Boolean
Whether to start immediately.

Event Subscription1

#::onWillThrowError(callback)

PublicL125

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.

ArgumentDescription
callback
Function
callback
errorObject
Object
error
Object
the error object
handle
Function
call this to indicate you have handled the error. The error will not be thrown if this function is called.
Returns

Disposable

Helper Methods1

#::kill()

PublicL234

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)

PublicL73

Write the given text to the clipboard.

The metadata associated with the text is available by calling #readWithMetadata.

ArgumentDescription
text
The String to store.
metadataoptional
The additional info to associate with the text.

#::writeNativeData(text, format, data)

asyncPublicL196

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.

ArgumentDescription
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

Promisethat resolves to true when the payload was written, or false when only the plain text could be written.

#::readNativeData(format)

asyncPublicL222

Read a JSON payload written by #writeNativeData in this or any other window.

ArgumentDescription
format
The MIME-style format String, without the web prefix.
Returns

Promisethat resolves to the parsed payload Object, or null when the clipboard holds no valid payload for the format.

#::read()

PublicL269

Read the text from the clipboard.

Returns

String

#::writeFindText(text)

PublicL279

Write the given text to the macOS find pasteboard

#::readFindText()

PublicL291

Read the text from the macOS find pasteboard.

Returns

String

#::readImage()

PublicL306

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

NativeImageempty when the clipboard holds no image.

#::writeImage(image)

PublicL318

Write an image to the clipboard, replacing whatever it held.

ArgumentDescription
image
A NativeImage, or the PNG bytes of one as a Buffer.

#::readSelectionText()

PublicL330

Read the text from the Linux primary selection.

Returns

Stringalways empty on the platforms that have no primary selection.

#::writeSelectionText(text)

PublicL346

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.

ArgumentDescription
text
The String to store.

#::readWithMetadata()

PublicL367

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.

  • text The String clipboard text.
  • metadata The metadata stored by an earlier call to #write.
Returns

Objectwith 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)

EssentialL20

Parse a String or Object into a Color.

ArgumentDescription
value
A String such as 'white', #ff00ff, or 'rgba(255, 15, 60, .75)' or an Object with red, green, blue, and alpha properties.
Returns

Coloror null if it cannot be parsed.

#::toHexString()

EssentialL97
Returns

Stringin the form '#abcdef'.

#::toRGBAString()

EssentialL109
Returns

Stringin 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)

PublicL125

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.

ArgumentDescription
target
String|Element
A CSS selector or DOM element. Selectors associate the command with all matching elements; the , combinator is not supported.
commandName
String|Object
A command name such as user:insert-date, or a map of command names to listeners.
listeneroptional
Function|Object
A function, or an object whose didDispatch property handles the command.
throwOnInvalidSelectoroptional, default: true
Boolean
Throw when target is an invalid selector.
event
Event
The dispatched DOM event. Call stopPropagation() or stopImmediatePropagation() to stop bubbling.
displayNameoptional
String
Overrides the generated display name.
descriptionoptional
String
Detailed command information.
hiddenInCommandPaletteoptional
Boolean
Hide the command from the bundled command palette by default.
modaloptional
Boolean|String
Declares that the command opens a modal, optionally naming its breadcrumb label.
Returns

Disposableon which .dispose() can be called to remove the added command handler(s).

#::findCommands({ target })

PublicL225

Find all registered commands matching a query.

  • name The name of the command. For example, user:insert-date.
  • displayName The display name of the command. For example, User: Insert Date. Additional metadata may also be present in the returned descriptor:
  • description a String describing the function of the command in more detail than the title
  • tags an Array of Strings that describe keywords related to the command Any additional nonstandard metadata provided when the command was added may also be present in the returned descriptor.
ArgumentDescription
params
Object
Query parameters.
target
Element
The hypothetical command target.
Returns

Array<Object>Command descriptors containing the documented keys.

#::dispatch(target, commandName, detail)

PublicL280

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.

ArgumentDescription
target
The DOM node at which to start bubbling the command event.
commandName
String
indicating 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)

PublicL295

Invoke the given callback before dispatching a command event.

ArgumentDescription
callback
Function
to be called before dispatching each command
event
The Event that will be dispatched

#::onDidDispatch(callback)

PublicL308

Invoke the given callback after dispatching a command event.

ArgumentDescription
callback
Function
to 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)

EssentialL542

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
})
ArgumentDescription
keyPath
String
The configuration key to observe.
optionsoptional
Object
Observation options.
scopeoptional
ScopeDescriptor
A path from the root of the syntax tree to a token. Get one by calling editor.getLastCursor().getScopeDescriptor(). See #get and the scopes docs for examples.
callback
Function
Called when the value changes.
value
*
The new value.
Returns

DisposableA disposable on which .dispose() can be called to unsubscribe.

#::onDidChange(...args)

EssentialL584

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.

ArgumentDescription
keyPathoptional
String
The key to observe. Required when options.scope is specified.
optionsoptional
Object
Observation options.
scopeoptional
ScopeDescriptor
A path from the root of the syntax tree to a token. Get one by calling editor.getLastCursor().getScopeDescriptor(). See #get and the scopes docs for examples.
callback
Function
Called when the value changes.
event
Object
The change event.
newValue
*
The new value.
oldValue
*
The previous value.
Returns

DisposableA disposable on which .dispose() can be called to unsubscribe.

Managing Settings7

#::get(...args)

EssentialL665

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
ArgumentDescription
keyPath
String
The key to retrieve.
optionsoptional
Object
Lookup options.
sourcesoptional
Array<String>
If provided, use only values associated with these sources during #set.
excludeSourcesoptional
Array<String>
If provided, exclude values associated with these sources during #set.
scopeoptional
ScopeDescriptor
A path from the root of the syntax tree to a token. Get one by calling editor.getLastCursor().getScopeDescriptor(). See the scopes docs for more information.
Returns

*The value from Lumine’s defaults or the user’s configuration, in the type specified by the configuration schema.

#::getAll(keyPath, options)

ExtendedL697

Get all of the values for the given key-path, along with their associated scope selector.

ArgumentDescription
keyPath
The String name of the key to retrieve
optionsoptional
Object
see the options argument to #get
scopeDescriptor
The ScopeDescriptor with which the value is associated
value
The value for the key-path
Returns

Arrayof Objects with the following keys:

#::set(...args)

EssentialL776

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
ArgumentDescription
keyPath
String
The configuration key.
value
*
The setting value. Passing undefined reverts it to the default value.
optionsoptional
Object
Write options.
scopeSelectoroptional
String
A scope such as .source.ruby. See the scopes docs for more information.
sourceoptional
String
The associated source file. Defaults to the user’s configuration file.
Returns

Booleantrue if the value was set; false if it could not be coerced to the type specified by the setting’s schema.

#::unset(keyPath, options)

EssentialL826

Restore the setting at keyPath to its default value.

ArgumentDescription
keyPath
The String name of the key.
optionsoptional
Object
scopeSelectoroptional
String
See #set
sourceoptional
String
See #set

#::getSources()

ExtendedL880

Get an Array of all of the source Strings with which settings have been added via #set.

#::getSchema(keyPath)

ExtendedL895

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.

ArgumentDescription
keyPath
The String name of the key.
Returns

Object|nullA schema such as {type: 'integer', default: 23, minimum: 1}, or null when the key path has no accessible schema.

#::transact(callback)

ExtendedL933

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.

ArgumentDescription
callback
Function
to execute while suppressing calls to handlers.

Extended API

ContextMenuManagersrc/context-menu-manager.js:65

Provides a registry for commands that you’d like to appear in the context menu.

An instance of this class is always available as the lumine.contextMenu global.

Context Menu Object Format

{
  "lumine-workspace": [
    { "label": "Help", "command": "application:open-documentation" }
  ],
  "lumine-text-editor": [
    {
      "label": "History",
      "submenu": [
        { "label": "Undo", "command": "core:undo" },
        { "label": "Redo", "command": "core:redo" }
      ]
    }
  ]
}

A package declares its context menu in a file under menus/, with the structure above under a context-menu key:

{
  "context-menu": {
    "lumine-workspace": [
      { "label": "Help", "command": "application:open-documentation" }
    ]
  }
}

The format for use in #add is the same minus the context-menu key. See #add for more information.

Methods2

#::add(itemsBySelector, throwOnInvalidSelector = true)

PublicL135

Add context menu items scoped by CSS selectors.

Examples

To add a context menu, pass a selector matching the elements to which you want the menu to apply as the top level key, followed by a menu descriptor. The invocation below adds a global ‘Help’ context menu item and a ‘History’ submenu on the editor supporting undo/redo. This is only an example and is not how Lumine’s menu is configured by default.

lumine.contextMenu.add({
  'lumine-workspace': [{label: 'Help', command: 'application:open-documentation'}]
  'lumine-text-editor': [{
    label: 'History',
    submenu: [
      {label: 'Undo', command:'core:undo'}
      {label: 'Redo', command:'core:redo'}
    ]
  }]
})

Arguments

ArgumentDescription
itemsBySelector
An Object whose keys are CSS selectors and whose values are Arrays of item Objects containing the following keys:
throwOnInvalidSelectoroptional, default: true
No description.
labeloptional
A String containing the menu item’s label.
commandoptional
A String containing the command to invoke on the target of the right click that invoked the context menu.
enabledoptional
A Boolean indicating whether the menu item should be clickable. Disabled menu items typically appear grayed out. Defaults to true.
submenuoptional
An Array of additional items.
typeoptional
If you want to create a separator, provide an item with type: 'separator' and no other keys.
visibleoptional
A Boolean indicating whether the menu item should appear in the menu. Defaults to true.
createdoptional
A Function that is called on the item each time a context menu is created via a right click. You can assign properties to this to dynamically compute the command, label, etc. This method is actually called on a clone of the original item template to prevent state from leaking across context menu deployments. Called with the following argument:
event
The click event that deployed the context menu.
shouldDisplayoptional
A Function that is called to determine whether to display this item on a given context menu deployment. Called with the following argument:
event
The click event that deployed the context menu.

#::show(target, menuTemplate)

PublicL301

Show a native context menu for a DOM target.

ArgumentDescription
target
The local DOM Element that receives selected commands.
menuTemplate
A serializable Electron menu-template Array; functions and native Electron objects are not allowed.
Returns

Promisethat resolves after the menu is shown.

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)

PublicL51

Calls your callback when the cursor has been moved.

ArgumentDescription
callback
Function
event
Object
oldBufferPosition
oldScreenPosition
newBufferPosition
newScreenPosition
textChanged
Boolean
cursor
Cursor
that triggered the event
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDestroy(callback)

PublicL64

Calls your callback when the cursor is destroyed

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

Managing Cursor Position11

#::setScreenPosition(screenPosition, options = {})

PublicL82

Moves a cursor to a given screen position.

ArgumentDescription
screenPosition
Array
of two numbers: the screen row, and the screen column.
optionsoptional
Object
with the following keys:
autoscroll
A Boolean which, if true, scrolls the TextEditor to wherever the cursor moves to.

#::getScreenPosition()

PublicL94
Returns

Pointscreen position of the cursor as a Point.

#::setBufferPosition(bufferPosition, options = {})

PublicL108

Moves a cursor to a given buffer position.

ArgumentDescription
bufferPosition
Array
of two numbers: the buffer row, and the buffer column.
optionsoptional
Object
with the following keys:
autoscroll
Boolean
indicating whether to autoscroll to the new position. Defaults to true if this is the most recently added cursor, false otherwise.

#::getBufferPosition()

PublicL120
Returns

Arraycurrent buffer position as an Array.

#::getScreenRow()

PublicL130
Returns

Numbercursor’s current screen row.

#::getScreenColumn()

PublicL140
Returns

Numbercursor’s current screen column.

#::getBufferRow()

PublicL150

Retrieves the cursor’s current buffer row.

#::getBufferColumn()

PublicL160
Returns

Numbercursor’s current buffer column.

#::getCurrentBufferLine()

PublicL170
Returns

Numbercursor’s current buffer row of text excluding its line ending.

#::isAtBeginningOfLine()

PublicL180
Returns

Booleanwhether the cursor is at the start of a line.

#::isAtEndOfLine()

PublicL190
Returns

Booleanwhether the cursor is on the line return character.

Cursor Position Details9

#::isSurroundedByWhitespace()

PublicL219

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()

PublicL238

This method returns false if the character before or after the cursor is whitespace.

Returns

BooleanWhether the cursor is between a word and non-word character. Non-word characters come from the language.nonWordCharacters setting.

#::isInsideWord(options)

PublicL261
ArgumentDescription
optionsoptional
Object
wordRegex
A RegExp indicating what constitutes a “word” (default: #wordRegExp).
Returns

Booleanwhether this cursor is between a word’s start and end.

#::getIndentLevel()

PublicL277
Returns

Numberindentation level of the current line.

#::getScopeDescriptor()

PublicL293

Retrieves the scope descriptor for the cursor’s current position.

Returns

ScopeDescriptor

#::getSyntaxTreeScopeDescriptor()

PublicL305

Retrieves the syntax tree scope descriptor for the cursor’s current position.

Returns

ScopeDescriptor

#::hasPrecedingCharactersOnLine()

PublicL315
Returns

Booleantrue if this cursor has no non-whitespace characters before its current position.

#::isLastCursor()

PublicL337

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 } = {})

PublicL356

Moves the cursor up one screen row.

ArgumentDescription
rowCountoptional
Number
number of rows to move (default: 1)
optionsoptional
Object
Movement options.
moveToEndOfSelectionoptional
Boolean
Move to the start of an existing selection.

#::moveDown(rowCount = 1, { moveToEndOfSelection } = {})

PublicL381

Moves the cursor down one screen row.

ArgumentDescription
rowCountoptional
Number
number of rows to move (default: 1)
optionsoptional
Object
Movement options.
moveToEndOfSelectionoptional
Boolean
Move to the end of an existing selection.

#::moveLeft(columnCount = 1, { moveToEndOfSelection } = {})

PublicL406

Moves the cursor left one screen column.

ArgumentDescription
columnCountoptional
Number
number of columns to move (default: 1)
optionsoptional
Object
Movement options.
moveToEndOfSelectionoptional
Boolean
Move to the start of an existing selection.

#::moveRight(columnCount = 1, { moveToEndOfSelection } = {})

PublicL435

Moves the cursor right one screen column.

ArgumentDescription
columnCountoptional
Number
number of columns to move (default: 1)
optionsoptional
Object
Movement options.
moveToEndOfSelectionoptional
Boolean
Move to the end of an existing selection.

#::moveToTop()

PublicL465

Moves the cursor to the top of the buffer.

#::moveToBottom()

PublicL475

Moves the cursor to the bottom of the buffer.

#::moveToBeginningOfScreenLine()

PublicL487

Moves the cursor to the beginning of the line.

#::moveToBeginningOfLine()

PublicL497

Moves the cursor to the beginning of the buffer line.

#::moveToFirstCharacterOfLine()

PublicL508

Moves the cursor to the beginning of the first character in the line.

#::moveToEndOfScreenLine()

PublicL541

Moves the cursor to the end of the line.

#::moveToEndOfLine()

PublicL551

Moves the cursor to the end of the buffer line.

#::moveToBeginningOfWord()

PublicL561

Moves the cursor to the beginning of the word.

#::moveToEndOfWord()

PublicL571

Moves the cursor to the end of the word.

#::moveToBeginningOfNextWord()

PublicL582

Moves the cursor to the beginning of the next word.

#::moveToPreviousWordBoundary()

PublicL593

Moves the cursor to the previous word boundary.

#::moveToNextWordBoundary()

PublicL604

Moves the cursor to the next word boundary.

#::moveToPreviousSubwordBoundary()

PublicL615

Moves the cursor to the previous subword boundary.

#::moveToNextSubwordBoundary()

PublicL627

Moves the cursor to the next subword boundary.

#::skipLeadingWhitespace()

PublicL640

Moves the cursor to the beginning of the buffer line, skipping all whitespace.

#::moveToBeginningOfNextParagraph()

PublicL658

Moves the cursor to the beginning of the next paragraph

#::moveToBeginningOfPreviousParagraph()

PublicL669

Moves the cursor to the beginning of the previous paragraph

Local Positions and Ranges9

#::getPreviousWordBoundaryBufferPosition(options = {})

PublicL686
ArgumentDescription
optionsoptional
Object
with the following keys:
wordRegex
A RegExp indicating what constitutes a “word” (default: #wordRegExp)
Returns

Pointbuffer position of previous word boundary. It might be on the current word, or the previous word.

#::getNextWordBoundaryBufferPosition(options = {})

PublicL718
ArgumentDescription
optionsoptional
Object
with the following keys:
wordRegex
A RegExp indicating what constitutes a “word” (default: #wordRegExp)
Returns

Pointbuffer position of the next word boundary. It might be on the current word, or the previous word.

#::getBeginningOfCurrentWordBufferPosition(options = {})

PublicL752

Retrieves the buffer position of where the current word starts.

ArgumentDescription
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

Range

#::getEndOfCurrentWordBufferPosition(options = {})

PublicL786

Retrieves the buffer position of where the current word ends.

ArgumentDescription
optionsoptional
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.
Returns

Range

#::getBeginningOfNextWordBufferPosition(options = {})

PublicL817

Retrieves the buffer position of where the next word starts.

ArgumentDescription
optionsoptional
Object
wordRegex
A RegExp indicating what constitutes a “word” (default: #wordRegExp).
Returns

Range

#::getCurrentWordBufferRange(options = {})

PublicL845
ArgumentDescription
optionsoptional
Object
wordRegex
A RegExp indicating what constitutes a “word” (default: #wordRegExp).
Returns

Rangebuffer Range occupied by the word located under the cursor.

#::getCurrentLineBufferRange(options)

PublicL865
ArgumentDescription
optionsoptional
Object
includeNewline
A Boolean which controls whether the Range should include the newline.
Returns

Rangebuffer Range for the current line.

#::getCurrentParagraphBufferRange()

PublicL879

Retrieves the range for the current paragraph.

A paragraph is defined as a block of text surrounded by empty lines or comments.

Returns

Range

#::getCurrentWordPrefix()

PublicL889
Returns

Stringcharacters preceding the cursor in the current word.

Comparing to another cursor1

#::compare(otherCursor)

PublicL914

Compare this cursor’s buffer position to another cursor’s buffer position.

See Point#compare for more details.

ArgumentDescription
otherCursor
Cursor
to compare against

Utilities3

#::clearSelection(options)

PublicL928

Deselects the current selection.

#::wordRegExp(options)

PublicL942

Get the RegExp used by the cursor to determine what a “word” is.

ArgumentDescription
optionsoptional
Object
with the following keys:
includeNonWordCharacters
A Boolean indicating whether to include non-word characters in the regex. (default: true)
Returns

RegExp

#::subwordRegExp(options = {})

PublicL961

Get the RegExp used by the cursor to determine what a “subword” is.

ArgumentDescription
optionsoptional
Object
with 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()

EssentialL100

Destroy this marker decoration.

You can also destroy the marker if you own it, which will destroy this decoration.

Event Subscription2

#::onDidChangeProperties(callback)

EssentialL132

When the Decoration is updated via Decoration#setProperties.

ArgumentDescription
callback
Function
event
Object
oldProperties
Object
the decoration’s previous properties
newProperties
Object
the decoration’s new properties
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDestroy(callback)

EssentialL145

Invoke the given callback when the Decoration is destroyed

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

Decoration Details3

#::isType(type)

PublicL182

Check if this decoration is of type type

ArgumentDescription
type
String
type 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()

EssentialL196
Returns

ObjectThe decoration’s properties.

#::setProperties(newProperties)

EssentialL214

Update the marker with new Properties. Allows you to change the decoration’s class.

Examples

decoration.setProperties({ type: 'line-number', class: 'my-new-class' })
ArgumentDescription
newProperties
Object
eg. {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)

PublicL46

Create a Directory that corresponds to the specified URI.

ArgumentDescription
uri
String
The path to the directory to add. This is guaranteed not to be contained by a Directory in lumine.project.
Returns

Directory|nullA directory when the URI is compatible, or null otherwise.

#::directoryForURI(uri)

PublicL96

Create a Directory that corresponds to the specified URI.

ArgumentDescription
uri
String
The path to the directory to add. This is guaranteed not to be contained by a Directory in lumine.project.
Returns

Promise<Directory|null>A promise resolving to a directory when the URI is compatible, or null otherwise.

#::normalizePath(uri)

PublicL109

Normalizes path.

ArgumentDescription
uri
String
The path that should be normalized.
Returns

Stringwith 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)

PublicL50

Register the given class(es) as deserializers.

ArgumentDescription
...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)

PublicL76

Deserialize the state and params.

ArgumentDescription
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()

EssentialL68

Destroys the marker, causing it to emit the ‘destroyed’ event. Once destroyed, a marker cannot be restored by undo/redo operations.

#::copy(params)

EssentialL97

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.

ArgumentDescription
paramsoptional
Object
properties to associate with the new marker. The new marker’s properties are computed by extending this marker’s properties with params.
Returns

DisplayMarker

Event Subscription2

#::onDidChange(callback)

EssentialL130

Invoke the given callback when the state of the marker changes.

ArgumentDescription
callback
Function
to be called when the marker changes.
event
Object
with the following keys:
oldHeadBufferPosition
Point
representing the former head buffer position
newHeadBufferPosition
Point
representing the new head buffer position
oldTailBufferPosition
Point
representing the former tail buffer position
newTailBufferPosition
Point
representing the new tail buffer position
oldHeadScreenPosition
Point
representing the former head screen position
newHeadScreenPosition
Point
representing the new head screen position
oldTailScreenPosition
Point
representing the former tail screen position
newTailScreenPosition
Point
representing the new tail screen position
wasValid
Boolean
indicating whether the marker was valid before the change
isValid
Boolean
indicating whether the marker is now valid
hadTail
Boolean
indicating whether the marker had a tail before the change
hasTail
Boolean
indicating whether the marker now has a tail
oldProperties
Object
containing the marker’s custom properties before the change.
newProperties
Object
containing the marker’s custom properties after the change.
textChanged
Boolean
indicating whether this change was caused by a textual change to the buffer or whether the marker was manipulated directly via its public API.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDestroy(callback)

EssentialL162

Invoke the given callback when the marker is destroyed.

ArgumentDescription
callback
Function
to be called when the marker is destroyed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

TextEditorMarker Details8

#::isValid()

EssentialL183
Returns

Booleanindicating whether the marker is valid. Markers can be invalidated when a region surrounding them in the buffer is changed.

#::isDestroyed()

EssentialL193
Returns

Booleanindicating 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()

EssentialL203
Returns

Booleanindicating whether the head precedes the tail.

#::isExclusive()

EssentialL213
Returns

Booleanindicating whether changes that occur exactly at the marker’s head or tail cause it to move.

#::getInvalidationStrategy()

EssentialL227

Get the invalidation strategy for this marker.

Valid values include: never, surround, overlap, inside, and touch.

Returns

String

#::getProperties()

EssentialL237
Returns

Objectcontaining any custom properties associated with the marker.

#::setProperties(properties)

EssentialL250

Merges an Object containing new properties into the marker’s existing properties.

ArgumentDescription
properties
Object

#::matchesProperties(attributes)

EssentialL260
Returns

Booleanwhether this marker matches the given parameters. The parameters are the same as DisplayMarkerLayer#findMarkers.

Comparing to other markers2

#::compare(otherMarker)

EssentialL278

Compares this marker to another based on their ranges.

ArgumentDescription
otherMarker
DisplayMarker
The marker to compare.
Returns

NumberThe ordering of this marker relative to otherMarker.

#::isEqual(other)

EssentialL289
ArgumentDescription
other
DisplayMarker
other marker
Returns

Booleanindicating whether this marker is equivalent to another marker, meaning they have the same range and options.

Managing the marker's range19

#::getBufferRange()

EssentialL308

Gets the buffer range of this marker.

Returns

Range

#::getScreenRange()

EssentialL320

Gets the screen range of this marker.

Returns

Range

#::setBufferRange(bufferRange, properties)

EssentialL334

Modifies the buffer range of this marker.

ArgumentDescription
bufferRange
The new Range to use
propertiesoptional
Object
properties to associate with the marker.
reversed
Boolean
If true, the marker will to be in a reversed orientation.

#::setScreenRange(screenRange, options)

EssentialL349

Modifies the screen range of this marker.

ArgumentDescription
screenRange
The new Range to use
optionsoptional
An Object with the following keys:
reversed
Boolean
If true, the marker will to be in a reversed orientation.
clipDirection
String
If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest' and applies to both ends of the range.

#::getHeadBufferPosition()

ExtendedL361

Retrieves the buffer position of the marker’s head.

Returns

Point

#::setHeadBufferPosition(bufferPosition)

ExtendedL373

Sets the buffer position of the marker’s head.

ArgumentDescription
bufferPosition
The new Point to use

#::getHeadScreenPosition(options)

ExtendedL387

Retrieves the screen position of the marker’s head.

ArgumentDescription
optionsoptional
An Object with the following keys:
clipDirection
String
If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'.
Returns

PointThe marker’s head screen position.

#::setHeadScreenPosition(screenPosition, options)

ExtendedL401

Sets the screen position of the marker’s head.

ArgumentDescription
screenPosition
The new Point to use
optionsoptional
An Object with the following keys:
clipDirection
String
If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'.

#::getTailBufferPosition()

ExtendedL413

Retrieves the buffer position of the marker’s tail.

Returns

Point

#::setTailBufferPosition(bufferPosition)

ExtendedL425

Sets the buffer position of the marker’s tail.

ArgumentDescription
bufferPosition
The new Point to use

#::getTailScreenPosition(options)

ExtendedL439

Retrieves the screen position of the marker’s tail.

ArgumentDescription
optionsoptional
An Object with the following keys:
clipDirection
String
If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'.
Returns

PointThe marker’s tail screen position.

#::setTailScreenPosition(screenPosition, options)

ExtendedL453

Sets the screen position of the marker’s tail.

ArgumentDescription
screenPosition
The new Point to use
optionsoptional
An Object with the following keys:
clipDirection
String
If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'.

#::getStartScreenPosition(options)

EssentialL483

Retrieves the screen position of the marker’s start. This will always be less than or equal to the result of DisplayMarker#getEndScreenPosition.

ArgumentDescription
optionsoptional
An Object with the following keys:
clipDirection
String
If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'.
Returns

PointThe marker’s start screen position.

#::getEndScreenPosition(options)

EssentialL511

Retrieves the screen position of the marker’s end. This will always be greater than or equal to the result of DisplayMarker#getStartScreenPosition.

ArgumentDescription
optionsoptional
An Object with the following keys:
clipDirection
String
If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'.
Returns

PointThe marker’s end screen position.

#::hasTail()

ExtendedL521
Returns

Booleanindicating whether the marker has a tail.

#::plantTail()

ExtendedL533

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()

ExtendedL545

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

#::destroy()

EssentialL40

Destroy this layer.

#::clear()

PublicL66

Destroy all markers in this layer.

#::isDestroyed()

EssentialL85

Determine whether this layer has been destroyed.

Returns

Boolean

Event Subscription3

#::onDidDestroy(callback)

PublicL101

Subscribe to be notified synchronously when this layer is destroyed.

Returns

Disposable

#::onDidUpdate(callback)

PublicL124

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.

ArgumentDescription
callback
A Function that will be called with no arguments when changes occur on this layer.
Returns

Disposable

#::onDidCreateMarker(callback)

PublicL143

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.

ArgumentDescription
callback
A Function that will be called with a TextEditorMarker whenever a new marker is created.
Returns

Disposable

Marker creation4

#::markScreenRange(screenRange, options)

PublicL174

Create a marker with the given screen range.

ArgumentDescription
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
Boolean
Creates the marker in a reversed orientation. (default: false)
invalidateoptional
String
Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility: * 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
Boolean
indicating whether insertions at the start or end of the marked range should be interpreted as happening outside the marker. Defaults to false, except when using the inside invalidation strategy or when the marker has no tail, in which case it defaults to true. Explicitly assigning this option overrides behavior in all circumstances.
clipDirection
String
If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest' and applies to both ends of the range.
Returns

DisplayMarkerThe new marker.

#::markScreenPosition(screenPosition, options)

PublicL194

Create a marker on this layer with its head at the given screen position and no tail.

ArgumentDescription
screenPosition
A Point or point-compatible Array
optionsoptional
An Object with the following keys:
invalidateoptional
String
Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility: * 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
Boolean
indicating whether insertions at the start or end of the marked range should be interpreted as happening outside the marker. Defaults to false, except when using the inside invalidation strategy or when the marker has no tail, in which case it defaults to true. Explicitly assigning this option overrides behavior in all circumstances.
clipDirection
String
If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'.
Returns

DisplayMarkerThe new marker.

#::markBufferRange(bufferRange, options)

PublicL213

Create a marker with the given buffer range.

ArgumentDescription
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
Boolean
Creates the marker in a reversed orientation. (default: false)
invalidateoptional
String
Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility: * 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
Boolean
indicating whether insertions at the start or end of the marked range should be interpreted as happening outside the marker. Defaults to false, except when using the inside invalidation strategy or when the marker has no tail, in which case it defaults to true. Explicitly assigning this option overrides behavior in all circumstances.
Returns

DisplayMarker

#::markBufferPosition(bufferPosition, options)

PublicL231

Create a marker on this layer with its head at the given buffer position and no tail.

ArgumentDescription
bufferPosition
A Point or point-compatible Array
optionsoptional
An Object with the following keys:
invalidateoptional
String
Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility: * 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
Boolean
indicating whether insertions at the start or end of the marked range should be interpreted as happening outside the marker. Defaults to false, except when using the inside invalidation strategy or when the marker has no tail, in which case it defaults to true. Explicitly assigning this option overrides behavior in all circumstances.
Returns

DisplayMarker

Querying4

#::getMarkers()

EssentialL271

Get all markers in the layer.

Returns

Arrayof DisplayMarkers.

#::getMarkerCount()

PublicL283

Get the number of markers in the marker layer.

Returns

Number

#::findMarkers(params)

PublicL321

Find markers in the layer conforming to the given parameters.

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.

ArgumentDescription
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:
startBufferPosition
Only include markers starting at this Point in buffer coordinates.
endBufferPosition
Only include markers ending at this Point in buffer coordinates.
startScreenPosition
Only include markers starting at this Point in screen coordinates.
endScreenPosition
Only include markers ending at this Point in screen coordinates.
startsInBufferRange
Only include markers starting inside this Range in buffer coordinates.
endsInBufferRange
Only include markers ending inside this Range in buffer coordinates.
startsInScreenRange
Only include markers starting inside this Range in screen coordinates.
endsInScreenRange
Only include markers ending inside this Range in screen coordinates.
startBufferRow
Only include markers starting at this row in buffer coordinates.
endBufferRow
Only include markers ending at this row in buffer coordinates.
startScreenRow
Only include markers starting at this row in screen coordinates.
endScreenRow
Only include markers ending at this row in screen coordinates.
intersectsBufferRowRange
Only include markers intersecting this Array of [startRow, endRow] in buffer coordinates.
intersectsScreenRowRange
Only include markers intersecting this Array of [startRow, endRow] in screen coordinates.
containsBufferRange
Only include markers containing this Range in buffer coordinates.
containsBufferPosition
Only include markers containing this Point in buffer coordinates.
containedInBufferRange
Only include markers contained in this Range in buffer coordinates.
containedInScreenRange
Only include markers contained in this Range in screen coordinates.
intersectsBufferRange
Only include markers intersecting this Range in buffer coordinates.
intersectsScreenRange
Only include markers intersecting this Range in screen coordinates.
Returns

Arrayof DisplayMarkers

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()

ExtendedL125

Show the dock and focus its active Pane.

#::show()

ExtendedL135

Show the dock without focusing it.

#::hide()

ExtendedL146

Hide the dock and activate the WorkspaceCenter if the dock was was previously focused.

#::toggle()

ExtendedL157

Toggle the dock’s visibility without changing the Workspace's active pane container.

#::isVisible()

ExtendedL171

Check if the dock is visible.

Returns

Boolean

Event Subscription16

#::onDidChangeVisible(callback)

EssentialL489

Invoke the given callback when the visibility of the dock changes.

ArgumentDescription
callback
Function
to be called when the visibility changes.
visible
Boolean
Is the dock now visible?
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeVisible(callback)

EssentialL503

Invoke the given callback with the current and all future visibilities of the dock.

ArgumentDescription
callback
Function
to be called when the visibility changes.
visible
Boolean
Is the dock now visible?
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observePaneItems(callback)

EssentialL519

Invoke the given callback with all current and future panes items in the dock.

ArgumentDescription
callback
Function
to be called with current and future pane items.
item
An item that is present in #getPaneItems at the time of subscription or that is added at some later time.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeActivePaneItem(callback)

EssentialL538

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.

ArgumentDescription
callback
Function
to be called when the active pane item changes.
item
The active pane item.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidStopChangingActivePaneItem(callback)

EssentialL559

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.

ArgumentDescription
callback
Function
to be called when the active pane item stops changing.
item
The active pane item.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeActivePaneItem(callback)

EssentialL574

Invoke the given callback with the current active pane item and with all future active pane items in the dock.

ArgumentDescription
callback
Function
to be called when the active pane item changes.
item
The current active pane item.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidAddPane(callback)

ExtendedL589

Invoke the given callback when a pane is added to the dock.

ArgumentDescription
callback
Function
to be called when panes are added.
event
Object
with the following keys:
pane
The added pane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onWillDestroyPane(callback)

ExtendedL605

Invoke the given callback before a pane is destroyed in the dock.

ArgumentDescription
callback
Function
to be called before panes are destroyed.
event
Object
with the following keys:
pane
The pane to be destroyed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDestroyPane(callback)

ExtendedL620

Invoke the given callback when a pane is destroyed in the dock.

ArgumentDescription
callback
Function
to be called when panes are destroyed.
event
Object
with the following keys:
pane
The destroyed pane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observePanes(callback)

ExtendedL635

Invoke the given callback with all current and future panes in the dock.

ArgumentDescription
callback
Function
to be called with current and future panes.
pane
A Pane that is present in #getPanes at the time of subscription or that is added at some later time.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeActivePane(callback)

ExtendedL649

Invoke the given callback when the active pane changes.

ArgumentDescription
callback
Function
to be called when the active pane changes.
pane
A Pane that is the current return value of #getActivePane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeActivePane(callback)

ExtendedL664

Invoke the given callback with the current active pane and when the active pane changes.

ArgumentDescription
callback
Function
to be called with the current and future active panes.
pane
A Pane that is the current return value of #getActivePane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidAddPaneItem(callback)

ExtendedL681

Invoke the given callback when a pane item is added to the dock.

ArgumentDescription
callback
Function
to be called when pane items are added.
event
Object
with the following keys:
item
The added pane item.
pane
Pane
containing the added item.
index
Number
indicating the index of the added item in its pane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onWillDestroyPaneItem(callback)

ExtendedL699

Invoke the given callback when a pane item is about to be destroyed, before the user is prompted to save it.

ArgumentDescription
callback
Function
to be called before pane items are destroyed.
event
Object
with the following keys:
item
The item to be destroyed.
pane
Pane
containing the item to be destroyed.
index
Number
indicating the index of the item to be destroyed in its pane.
Returns

Disposableon which .dispose can be called to unsubscribe.

#::onDidDestroyPaneItem(callback)

ExtendedL716

Invoke the given callback when a pane item is destroyed.

ArgumentDescription
callback
Function
to be called when pane items are destroyed.
event
Object
with the following keys:
item
The destroyed item.
pane
Pane
containing the destroyed item.
index
Number
indicating the index of the destroyed item in its pane.
Returns

Disposableon which .dispose can be called to unsubscribe.

#::onDidChangeHovered(callback)

ExtendedL730

Invoke the given callback when the hovered state of the dock changes.

ArgumentDescription
callback
Function
to be called when the hovered state changes.
hovered
Boolean
Is the dock now hovered?
Returns

Disposableon which .dispose() can be called to unsubscribe.

Pane Items2

#::getPaneItems()

EssentialL746

Get all pane items in the dock.

Returns

Arrayof items.

#::getActivePaneItem()

EssentialL758

Get the active Pane's active item.

Returns

Objectpane item Object.

Panes4

#::getPanes()

ExtendedL783

Get all panes in the dock.

Returns

Arrayof Panes.

#::getActivePane()

ExtendedL795

Get the active Pane.

Returns

Pane

#::activateNextPane()

ExtendedL805

Make the next pane active.

#::activatePreviousPane()

ExtendedL815

Make the previous pane active.

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)

PublicL118

Creates a new GitRepository instance.

ArgumentDescription
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

GitRepositoryinstance or null if the repository could not be opened.

#::destroy()

PublicL210

Destroy this GitRepository object.

This destroys any tasks and subscriptions and releases the underlying libgit2 repository handle. This method is idempotent.

#::isDestroyed()

PublicL249
Returns

Booleanindicating if this repository has been destroyed.

#::isPresent()

PublicL259
Returns

Booleanwhether this repository’s Git directory still exists.

#::getOperations()

PublicL269
Returns

Objectstable write facade assigned by lumine.repositories. Its methods are enabled by repositories.operations-provider services.

#::onDidDestroy(callback)

PublicL287

Invoke the given callback when this GitRepository’s destroy() method is invoked.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

Event Subscription4

#::onDidChangeStatus(callback)

PublicL313

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.

ArgumentDescription
callback
Function
event
Object
path
String
the path whose status changed
pathStatus
Number
representing the status.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeStatuses(callback)

PublicL328

Invoke the given callback when multiple files’ statuses have changed. Prefer #onDidChangeStatusSnapshot; this legacy event is retained for API compatibility.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeStatusSnapshot(callback)

PublicL347

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.

ArgumentDescription
callback
Function
called with an immutable status snapshot.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeRefsSnapshot(callback)

PublicL372

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.

ArgumentDescription
callback
Function
called with an immutable refs snapshot.
Returns

Disposableon which .dispose() can be called to unsubscribe.

Repository Details15

#::getType()

PublicL398

A String indicating the type of version control system used by this repository.

Returns

"git"

#::getPath()

PublicL408
Returns

Stringpath of the repository.

#::getWorkingDirectory()

PublicL422
Returns

Stringworking directory path of the repository.

#::isProjectAtRoot()

PublicL432
Returns

Booleantrue if at the root, false if in a subfolder of the repository.

#::relativize(path)

PublicL446

Makes a path relative to the repository’s working directory.

#::hasBranch(branch)

PublicL461
Returns

Booleantrue if the given branch exists.

#::getShortHead()

PublicL477

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

StringThe shortened HEAD reference.

#::isSubmodule(filePath)

PublicL502

Is the given path a submodule in the repository?

ArgumentDescription
filePath
The String path to check.
Returns

Boolean

#::getAheadBehindCount(reference)

PublicL514
ArgumentDescription
reference
The String branch reference name.
Returns

ObjectThe ahead and behind commit counts.

#::getCachedUpstreamAheadBehindCount()

PublicL536

Get the cached ahead/behind commit counts for the current branch’s upstream branch.

  • ahead The Number of commits ahead.
  • behind The Number of commits behind.
Returns

Objectwith the following keys:

#::getConfigValueAsync(key)

PublicL557

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.

ArgumentDescription
key
String
The configuration key to look up.
Returns

Promise<String|null>The configured value.

#::getOriginURL()

PublicL568
Returns

String|nullorigin 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()

PublicL582
Returns

String|nullThe upstream branch, such as refs/remotes/origin/master, or null when HEAD has no upstream.

#::getReferences()

PublicL602

Gets all the local and remote references.

  • heads An Array of head reference names.
  • remotes An Array of remote reference names.
  • tags An Array of tag reference names.
Returns

Objectwith the following keys:

#::getReferenceTarget(reference)

PublicL619
ArgumentDescription
reference
The String reference to get the target of.
Returns

String|nullThe current SHA for the reference, or null when it is unavailable.

Reading Status23

#::isPathModified(path)

PublicL667
ArgumentDescription
path
The String path to check.
Returns

BooleanWhether the path is modified in the detailed status snapshot. Returns false until the snapshot loads.

#::isPathNew(path)

PublicL679
ArgumentDescription
path
The String path to check.
Returns

BooleanWhether the path is new in the detailed status snapshot. Returns false until the snapshot loads.

#::isPathIgnored(path)

PublicL694

Is the given path ignored? Resolved from the detailed status snapshot’s ignored entries; returns false until the snapshot has loaded.

ArgumentDescription
path
The String path to check.
Returns

Booleanthat’s true if the path is ignored.

#::isPathIgnoredCached(filePath)

PublicL709

Whether the given path is ignored, resolved synchronously from the Git status snapshot’s ignored entries. Returns false until the first snapshot loads.

ArgumentDescription
filePath
The String path to check.
Returns

Booleanthat’s true if the filePath is ignored.

#::getStatusSnapshot()

PublicL725
Returns

Objectlatest 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 = {})

asyncPublicL738

Resolve with an initialized status snapshot, loading it on first call. Concurrent callers share one in-flight refresh.

ArgumentDescription
optionsoptional, default: {}
No description.
Returns

Promisethat resolves to the snapshot.

#::getStatusEntry(filePath)

PublicL767
Returns

Object|nulldetailed cached status for a repository path, or null.

#::refreshStatusSnapshot(options = {})

PublicL828

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.

ArgumentDescription
optionsoptional, default: {}
No description.

#::getPathStatusSummary(filePath)

PublicL929

Classified status for one path, read from the detailed status snapshot.

ArgumentDescription
filePath
A String path, absolute or repository-relative.
Returns

Object|nullfrozen {source, conflicted, modified, added, renamed} object (source is always "snapshot"), or null for clean, ignored, unknown, and pre-snapshot paths.

#::getDirectoryStatusSummary(directoryPath)

PublicL946

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()

PublicL969
Returns

Objectlatest 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 = {})

asyncPublicL982

Resolve with an initialized refs snapshot, loading it on first call. Concurrent callers share one in-flight refresh.

ArgumentDescription
optionsoptional, default: {}
No description.
Returns

Promisethat resolves to the snapshot.

#::refreshRefsSnapshot(options = {})

PublicL1010

Refresh the refs snapshot with Git. Concurrent calls coalesce into at most one in-flight and one trailing refresh; see coalesceSnapshotRefresh.

ArgumentDescription
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, } = {})

asyncPublicL1069

Compute a structured diff between two endpoints.

ArgumentDescription
optionsoptional
Object
Diff options.
fromoptional
Object
The starting endpoint.
tooptional
Object
The ending endpoint. Endpoints may be commit, index, worktree, file, or empty descriptors.
pathsoptional
Array<String>
Pathspecs limiting the diff.
contextoptional, default: 3
Number
Context lines.
ignoreWhitespaceoptional, default: false
Boolean
Ignore all whitespace.
detectRenamesoptional, default: true
Boolean
Detect renames.
diffFilteroptional
String
A Git diff-filter value.
maxBytesoptional, default: 10485760
Number
Output limit. Exceeding it rejects with ERR_GIT_DIFF_TOO_LARGE.
signaloptional
AbortSignal
Cancellation signal.
Returns

Promiseresolving 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, } = {})

asyncPublicL1134

Read paginated commit history.

ArgumentDescription
optionsoptional
Object
History options.
revisionoptional, default: "HEAD"
String
Starting revision.
pathoptional
String
Limit history to one path and follow renames.
limitoptional, default: 50
Number
Page size.
cursoroptional
Object
The nextCursor from a previous page.
signaloptional
AbortSignal
Cancellation signal.
Returns

Promiseresolving 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 } = {})

asyncPublicL1177

Read one commit with its changed-file summary.

ArgumentDescription
sha
The String commit id or any revision expression.
Returns

Promiseresolving to the commit object extended with changedFiles: [{path, originalPath, status, similarity}].

#::getFileAtRevision(filePath, revision, { encoding = "utf8", signal } = {})

PublicL1207

Read a file’s contents at a revision.

ArgumentDescription
filePath
A String path, absolute or repository-relative.
revision
A String revision expression.
optionsoptional
Object
Read options.
encodingoptional, default: "utf8"
String
Text encoding, or "buffer" for a Buffer.
signaloptional
AbortSignal
Cancellation signal.
Returns

Promiseresolving to the contents, or null when the path does not exist at that revision.

#::getBlob(oid, { encoding = "utf8", signal } = {})

PublicL1230

Read a blob’s contents by object id (git cat-file -p <oid>).

ArgumentDescription
oid
A String blob object id.
optionsoptional
Object
Read options.
encodingoptional, default: "utf8"
String
Text encoding, or "buffer" for a Buffer.
signaloptional
AbortSignal
Cancellation signal.
Returns

Promiseresolving to the contents, or null when the oid does not name an object.

#::getDescription()

PublicL1246

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 } = {})

PublicL1266

The fully-qualified refnames of branches that contain a commit (git branch --contains).

ArgumentDescription
commit
A String commit id or revision.
optionsoptional
Object
Branch filtering options.
showLocaloptional, default: false
Boolean
Include local branches.
showRemoteoptional, default: false
Boolean
Include remote branches.
patternoptional
String
Limit branch names by pattern.
Returns

Promiseresolving to an Array of refname Strings.

#::getFileMode(filePath)

PublicL1285

The index mode of a path (git ls-files --stage).

ArgumentDescription
filePath
A String path, absolute or repository-relative.
Returns

Promiseresolving to the String mode (e.g. "100644"), or null when the path is not tracked.

#::getSubmodulePaths()

PublicL1300

The repository-relative paths of the repository’s submodules (git submodule status).

Returns

Promiseresolving to an Array of path Strings.

#::getBlame(filePath, { revision = null, ignoreWhitespace = false, signal } = {})

asyncPublicL1319

Read line-by-line blame for a file.

ArgumentDescription
filePath
A String path, absolute or repository-relative.
optionsoptional
Object
Blame options.
revisionoptional
String
Revision to blame.
ignoreWhitespaceoptional
Boolean
Ignore whitespace-only changes when attributing a line, so a reindent does not reassign every line it touched.
signaloptional
AbortSignal
Cancellation signal.
Returns

Promiseresolving to a frozen {revision, lines} object where each line has line, originalLine, sha, author, summary.

Retrieving Diffs1

#::getLineDiffsAsync(filePath, text)

PublicL1346

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.

ArgumentDescription
filePath
The String path relative to the repository.
text
The String to compare against the HEAD contents.
Returns

Promiseresolving to an Array of hunk Objects, each with oldStart, newStart, oldLines, and newLines.

Checking Out2

#::checkoutHead(filePath)

asyncPublicL1376

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>).

ArgumentDescription
filePath
The String path to checkout.
Returns

Promiseresolving to a Boolean that’s true on success.

#::checkoutReference(reference, create)

asyncPublicL1398

Checks out a branch in your repository via the repository operation provider.

ArgumentDescription
reference
The String reference to checkout.
create
A Boolean value which, if true creates the new reference if it doesn’t exist.
Returns

Promiseresolving 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)

ExtendedL96

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.

ArgumentDescription
buffer
The TextBuffer whose language mode will be maintained.
Returns

Disposablethat can be used to stop updating the buffer’s language mode.

#::assignLanguageMode(buffer, languageId)

ExtendedL152

Force a TextBuffer to use a different grammar than the one that would otherwise be selected for it.

ArgumentDescription
buffer
The TextBuffer whose grammar will be set.
languageId
The String id of the desired language.
Returns

Booleanthat indicates whether the language was successfully found.

#::assignGrammar(buffer, grammar)

ExtendedL185

Force a TextBuffer to use a different grammar than the one that would otherwise be selected for it.

ArgumentDescription
buffer
The TextBuffer whose grammar will be set.
grammar
The desired Grammar.
Returns

Booleanthat indicates whether the assignment was successful

#::getAssignedLanguageId(buffer)

ExtendedL225

Get the languageId that has been explicitly assigned to the given buffer, if any.

Returns

Stringid of the language

#::autoAssignLanguageMode(buffer)

ExtendedL239

Remove any language mode override that has been set for the given TextBuffer. This will assign to the buffer the best language mode available.

ArgumentDescription
buffer

#::selectGrammar(filePath, fileContents)

ExtendedL277

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.

ArgumentDescription
filePath
A String file path.
fileContents
A String of text for the file path.
Returns

Grammarnever null.

#::getGrammarScore(grammar, filePath, contents)

ExtendedL324

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.

ArgumentDescription
grammar
A given Grammar.
filePath
A String path to the file.
contents
The String contents of the file.
Returns

Number

#::onDidAddGrammar(callback)

ExtendedL530

Invoke the given callback when a grammar is added to the registry.

ArgumentDescription
callback
Function
to call when a grammar is added.
grammar
Grammar
that was added.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidUpdateGrammar(callback)

ExtendedL550

Invoke the given callback when a grammar is updated due to a grammar it depends on being added or removed from the registry.

ArgumentDescription
callback
Function
to call when a grammar is updated.
grammar
Grammar
that was updated.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidRemoveGrammar(callback)

ExtendedL570

Invoke the given callback when a grammar is removed from the registry, which happens whenever the package that provides it deactivates.

ArgumentDescription
callback
Function
to call when a grammar is removed.
grammar
Grammar
that was removed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::addInjectionPoint(grammarId, injectionPoint)

PublicL597

Specify a type of syntax node that may embed other languages.

ArgumentDescription
grammarId
String
The id of the parent language.
injectionPoint
Object
Injection behavior.
type
String
The syntax-node type that may embed other languages.
language
Function
Called with a matching syntax node and returns the language name tested against other grammars’ injectionRegex values.
content
Function
Called with a matching syntax node and returns the node or nodes containing embedded source. The nodes become visible buffer ranges for the injected parser.
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

DisposableA disposable that removes the injection point.

#::loadGrammar(grammarPath, callback)

ExtendedL686

Read a grammar asynchronously and add it to the registry.

ArgumentDescription
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)

ExtendedL703

Read a grammar synchronously and add it to this registry.

ArgumentDescription
grammarPath
A String absolute file path to a grammar file.
Returns

Grammar

#::readGrammar(grammarPath, callback)

ExtendedL721

Read a grammar asynchronously but don’t add it to the registry.

ArgumentDescription
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

undefinedundefined.

#::readGrammarSync(grammarPath)

ExtendedL742

Read a grammar synchronously but don’t add it to the registry.

ArgumentDescription
grammarPath
A String absolute file path to a grammar file.
Returns

Grammar

#::getGrammars(params)

ExtendedL767

Get all the grammars in this registry.

ArgumentDescription
paramsoptional
Object
includeTreeSitteroptional
Boolean
Set to include Tree-sitter grammars
Returns

Arraynon-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()

EssentialL39

Destroys the gutter.

Event Subscription2

#::onDidChangeVisible(callback)

EssentialL63

Calls your callback when the gutter’s visibility changes.

ArgumentDescription
callback
Function
gutter
The gutter whose visibility changed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDestroy(callback)

EssentialL76

Calls your callback when the gutter is destroyed.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

Visibility4

#::hide()

EssentialL90

Hide the gutter.

#::show()

EssentialL104

Show the gutter.

#::isVisible()

EssentialL120

Determine whether the gutter is visible.

Returns

Boolean

#::decorateMarker(marker, options)

EssentialL139

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

ArgumentDescription
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

Decorationobject

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()

PublicL46

Obtain a list of previously opened projects.

Returns

Arrayof HistoryProject objects, most recent first.

#::clearProjects()

asyncPublicL61

Clear all projects from the history.

Note: This is not a privacy function - other traces will still exist, e.g. window state.

Returns

Promisethat resolves when the history has been successfully cleared.

#::onDidChangeProjects(callback)

PublicL76

Invoke the given callback when the list of projects changes.

ArgumentDescription
callback
Function
Returns

Disposableon 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 } = {})

EssentialL309

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 = {})

EssentialL370

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.

ArgumentDescription
optionsoptional, default: {}
No description.

#::applyTo(element, target, options = {})

EssentialL443

Render target’s icon into element and keep it current.

ArgumentDescription
element
Element
The element that receives the icon.
target
Object
The icon target.
optionsoptional
Object
Rendering options.
classesoptional
Array<String>
Extra classes to add.
nameoptional
String
An explicit data-name.
setDataoptional, default: true
Boolean
Set data-name and data-path.
liveoptional, default: true
Boolean
Re-render when the icon changes.
renderoptional, default: true
Boolean
Render children and styles in addition to applying classes.
skipFallbackoptional, default: false
Boolean
Render nothing unless a provider above the built-in answers.
Returns

Disposablethat removes everything the call added.

#::invalidate(scope)

ExtendedL507

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)

ExtendedL585

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)

ExtendedL595

Override the icon for one or more kinds. Returns a Disposable.

#::onDidChange(callback)

ExtendedL625

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)

PublicL129

Create a keydown DOM event for testing purposes.

ArgumentDescription
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)

PublicL150

Create a new KeymapManager.

ArgumentDescription
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()

PublicL170

Clear all registered key bindings and enqueued keystrokes. For use in tests.

#::destroy()

PublicL184

Unwatch all watched paths.

Event Subscription4

#::onDidMatchBinding(callback)

PublicL209

Invoke the given callback when one or more keystrokes completely match a key binding.

ArgumentDescription
callback
Function
to be called when keystrokes match a binding.
event
Object
with the following keys:
keystrokes
String
of keystrokes that matched the binding.
binding
KeyBinding
that the keystrokes matched.
keyboardEventTarget
DOM element that was the target of the most recent keyboard event.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidPartiallyMatchBindings(callback)

PublicL227

Invoke the given callback when one or more keystrokes partially match a binding.

ArgumentDescription
callback
Function
to be called when keystrokes partially match a binding.
event
Object
with the following keys:
keystrokes
String
of keystrokes that matched the binding.
partiallyMatchedBindings
KeyBinding
s that the keystrokes partially matched.
keyboardEventTarget
DOM element that was the target of the most recent keyboard event.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidFailToMatchBinding(callback)

PublicL244

Invoke the given callback when one or more keystrokes fail to match any bindings.

ArgumentDescription
callback
Function
to be called when keystrokes fail to match any bindings.
event
Object
with the following keys:
keystrokes
String
of keystrokes that matched the binding.
keyboardEventTarget
DOM element that was the target of the most recent keyboard event.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidFailToReadFile(callback)

PublicL282

Invoke the given callback when a keymap file not able to be loaded.

ArgumentDescription
callback
Function
to be called when a keymap file is unloaded.
error
Object
with the following keys:
message
String
the error message.
stack
String
the error stack trace.
Returns

Disposableon which .dispose() can be called to unsubscribe.

Adding and Removing Bindings2

#::build(source, keyBindingsBySelector, priority, throwOnInvalidSelector)

ExtendedL304

Construct KeyBindings from an object grouping them by CSS selector.

ArgumentDescription
source
A String (usually a path) uniquely identifying the given bindings so they can be removed later.
keyBindingsBySelector
Object
Bindings grouped by CSS selector, with each value mapping keystroke patterns to commands.
priority
A Number used to sort keybindings which have the same specificity. Defaults to 0.
throwOnInvalidSelectoroptional, default: true
Boolean
Whether invalid selectors should throw.
Returns

Array<KeyBinding>The constructed bindings.

#::add(source, keyBindingsBySelector, priority, throwOnInvalidSelector)

PublicL370

Add sets of key bindings grouped by CSS selector.

ArgumentDescription
source
A String (usually a path) uniquely identifying the given bindings so they can be removed later.
keyBindingsBySelector
Object
Bindings grouped by CSS selector, with each value mapping keystroke patterns to commands.
priority
A Number used to sort keybindings which have the same specificity. Defaults to 0.
throwOnInvalidSelectoroptional, default: true
Boolean
Whether invalid selectors should throw.
Returns

DisposableA disposable that removes the bindings.

Accessing Bindings2

#::getKeyBindings()

PublicL411

Get all current key bindings.

Returns

Arrayof KeyBindings.

#::findKeyBindings(params)

PublicL427

Get the key bindings for a given command and optional target.

ArgumentDescription
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

Arrayof key bindings.

Managing Keymap Files2

#::loadKeymap(bindingsPath, options)

PublicL474

Load the key bindings from the given path.

ArgumentDescription
bindingsPath
String
A 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)

PublicL515

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.

ArgumentDescription
filePath
String
The 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)

PublicL625

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.

ArgumentDescription
event
A KeyboardEvent of type ‘keydown’

#::keystrokeForKeyboardEvent(event)

PublicL905

Translate a keydown event to a keystroke string.

ArgumentDescription
event
A KeyboardEvent of type ‘keydown’
Returns

Stringdescribing the keystroke.

#::addKeystrokeResolver(resolver)

PublicL926

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.

ArgumentDescription
resolver
A Function that returns a keystroke String and is called with an object containing the following keys:
keystroke
String
The currently resolved keystroke string. A falsy resolver result keeps this value.
event
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

DisposableA disposable that removes the resolver.

#::getPartialMatchTimeout()

PublicL945

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()

EssentialL31

Destroys the decoration.

#::isDestroyed()

EssentialL49

Determine whether this decoration is destroyed.

Returns

Boolean

#::getProperties()

EssentialL69

Get this decoration’s properties.

Returns

Object

#::setProperties(newProperties)

EssentialL81

Set this decoration’s properties.

ArgumentDescription
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)

EssentialL98

Override the decoration properties for a specific marker.

ArgumentDescription
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

#::copy()

PublicL88

Create a copy of this layer with markers in the same state and locations.

#::destroy()

PublicL108

Destroy this layer.

#::clear()

PublicL131

Remove all markers from this layer.

#::isDestroyed()

PublicL152

Determine whether this layer has been destroyed.

Querying5

#::getMarker(id)

PublicL171

Get an existing marker by its id.

#::getMarkers()

PublicL183

Get all existing markers on the marker layer.

#::getMarkerCount()

PublicL195

Get the number of markers in the marker layer.

#::findMarkers(params)

PublicL206

Find markers in the layer conforming to the given parameters. See TextBuffer#findMarkers for the supported search parameters.

#::getRole()

PublicL296

Get the role of the marker layer e.g. lumine.selection.

Marker creation2

#::markRange(range, options = {})

PublicL317

Create a marker with the given range.

ArgumentDescription
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
Boolean
Creates the marker in a reversed orientation. (default: false)
invalidateoptional
String
Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility: * 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
Boolean
indicating whether insertions at the start or end of the marked range should be interpreted as happening outside the marker. Defaults to false, except when using the inside invalidation strategy or when the marker has no tail, in which case it defaults to true. Explicitly assigning this option overrides behavior in all circumstances.

#::markPosition(position, options = {})

PublicL334

Create a marker at with its head at the given position with no tail.

ArgumentDescription
position
Point
or point-compatible Array
optionsoptional
An Object with the following keys:
invalidateoptional
String
Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility: * 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
Boolean
indicating whether insertions at the start or end of the marked range should be interpreted as happening outside the marker. Defaults to false, except when using the inside invalidation strategy or when the marker has no tail, in which case it defaults to true. Explicitly assigning this option overrides behavior in all circumstances.

Event subscription3

#::onDidUpdate(callback)

PublicL365

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.

ArgumentDescription
callback
A Function that will be called with no arguments when changes occur on this layer.

#::onDidCreateMarker(callback)

PublicL385

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.

ArgumentDescription
callback
A Function that will be called with a Marker whenever a new marker is created.

#::onDidDestroy(callback)

PublicL398

Subscribe to be notified synchronously when this layer is destroyed.

Extended API

MenuManagersrc/menu-manager.js:72

Provides a registry for menu items that you’d like to appear in the application menu.

An instance of this class is always available as the lumine.menu global.

Menu Object Format

Here is an example from Lumine’s bundled tree-view:

[
  {
    "label": "View",
    "submenu": [
      { "label": "Toggle Tree View", "command": "tree-view:toggle" }
    ]
  },
  {
    "label": "Packages",
    "submenu": [
      {
        "label": "Tree View",
        "submenu": [
          { "label": "Focus", "command": "tree-view:toggle-focus" },
          { "label": "Toggle", "command": "tree-view:toggle" },
          { "label": "Reveal Active File", "command": "tree-view:reveal-active-file" },
          { "label": "Toggle Tree Side", "command": "tree-view:toggle-side" }
        ]
      }
    ]
  }
]

A package declares its menu in a file under menus/, with the structure above under a menu key:

{
  "menu": [
    {
      "label": "View",
      "submenu": [
        { "label": "Toggle Tree View", "command": "tree-view:toggle" }
      ]
    }
  ]
}

See #add for more information about adding menus directly.

Public API

Notificationsrc/notification.js:10

A notification to the user containing a message and type.

Event Subscription2

#::onDidDismiss(callback)

PublicL46

Invoke the given callback when the notification is dismissed.

ArgumentDescription
callback
Function
to be called when the notification is dismissed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDisplay(callback)

PublicL59

Invoke the given callback when the notification is displayed.

ArgumentDescription
callback
Function
to be called when the notification is displayed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

Methods3

#::getType()

PublicL77
Returns

Stringtype.

#::getMessage()

PublicL87
Returns

Stringmessage.

#::dismiss()

ExtendedL114

Dismisses the notification, removing it from the UI. Calling this programmatically will call all callbacks added via onDidDismiss.

Public API

NotificationManagersrc/notification-manager.js:14

A notification manager used to create Notifications to be shown to the user.

An instance of this class is always available as the lumine.notifications global.

Events3

#::onDidAddNotification(callback)

PublicL34

Invoke the given callback after a notification has been added.

ArgumentDescription
callback
Function
to be called after the notification is added.
notification
The Notification that was added.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidClearNotifications(callback)

PublicL47

Invoke the given callback after the notifications have been cleared.

ArgumentDescription
callback
Function
to be called after the notifications are cleared.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidBeep(callback)

PublicL59

Invoke the given callback whenever #beep is called.

Returns

Disposableon which .dispose() can be called to unsubscribe.

Adding Notifications7

#::addSuccess(message, options)

PublicL85

Add a success notification.

ArgumentDescription
message
A String message
optionsoptional
An Object with the following keys:
buttonsoptional
An Array of Object where each Object has the following options:
classNameoptional
String
a class name to add to the button’s default class name (btn btn-success).
onDidClickoptional
Function
callback to call when the button has been clicked. The context will be set to the NotificationElement instance.
text
String
inner text for the button
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

Notificationthat was added.

#::addHint(message, options)

PublicL115

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.

ArgumentDescription
message
A String message
optionsoptional
An Object with the following keys:
buttonsoptional
An Array of Object where each Object has the following options:
classNameoptional
String
a class name to add to the button’s default class name (btn).
onDidClickoptional
Function
callback to call when the button has been clicked. The context will be set to the NotificationElement instance.
text
String
inner text for the button
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

Notificationthat was added.

#::addInfo(message, options)

PublicL137

Add an informational notification.

ArgumentDescription
message
A String message
optionsoptional
An Object with the following keys:
buttonsoptional
An Array of Object where each Object has the following options:
classNameoptional
String
a class name to add to the button’s default class name (btn btn-info).
onDidClickoptional
Function
callback to call when the button has been clicked. The context will be set to the NotificationElement instance.
text
String
inner text for the button
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

Notificationthat was added.

#::addWarning(message, options)

PublicL159

Add a warning notification.

ArgumentDescription
message
A String message
optionsoptional
An Object with the following keys:
buttonsoptional
An Array of Object where each Object has the following options:
classNameoptional
String
a class name to add to the button’s default class name (btn btn-warning).
onDidClickoptional
Function
callback to call when the button has been clicked. The context will be set to the NotificationElement instance.
text
String
inner text for the button
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

Notificationthat was added.

#::addError(message, options)

PublicL182

Add an error notification.

ArgumentDescription
message
A String message
optionsoptional
An Object with the following keys:
buttonsoptional
An Array of Object where each Object has the following options:
classNameoptional
String
a class name to add to the button’s default class name (btn btn-error).
onDidClickoptional
Function
callback to call when the button has been clicked. The context will be set to the NotificationElement instance.
text
String
inner text for the button
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

Notificationthat was added.

#::addFatalError(message, options)

PublicL205

Add a fatal error notification.

ArgumentDescription
message
A String message
optionsoptional
An Object with the following keys:
buttonsoptional
An Array of Object where each Object has the following options:
classNameoptional
String
a class name to add to the button’s default class name (btn btn-error).
onDidClickoptional
Function
callback to call when the button has been clicked. The context will be set to the NotificationElement instance.
text
String
inner text for the button
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

Notificationthat was added.

#::beep()

PublicL225

Request audible or visual attention from notification consumers.

Getting Notifications1

#::getNotifications()

PublicL241

Get all the notifications.

Returns

Arrayof Notifications.

Managing Notifications1

#::clear()

PublicL255

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)

EssentialL79

Invoke the given callback when all packages have been activated.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

Native Module Compatibility3

#::isCompatible()

ExtendedL1160

Are all native modules depended on by this package correctly compiled against the current version of Lumine?

Incompatible packages cannot be activated.

Returns

Booleantrue if compatible, false if incompatible.

#::rebuild()

ExtendedL1181

Rebuild native modules in this package’s dependencies for the current version of Lumine.

Returns

Promisethat resolves with an object containing code, stdout, and stderr properties based on the results of running lumine -p rebuild on the package.

#::getBuildFailureOutput()

ExtendedL1204

If a previous rebuild failed, get the contents of stderr.

Returns

Stringor 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)

PublicL147

Invoke the given callback when all packages have been loaded.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidActivateInitialPackages(callback)

PublicL160

Invoke the given callback when all packages have been activated.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidActivatePackage(callback)

PublicL182

Invoke the given callback when a package is activated.

ArgumentDescription
callback
A Function to be invoked when a package is activated.
package
The Package that was activated.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDeactivatePackage(callback)

PublicL196

Invoke the given callback when a package is deactivated.

ArgumentDescription
callback
A Function to be invoked when a package is deactivated.
package
The Package that was deactivated.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidLoadPackage(callback)

PublicL210

Invoke the given callback when a package is loaded.

ArgumentDescription
callback
A Function to be invoked when a package is loaded.
package
The Package that was loaded.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidUnloadPackage(callback)

PublicL224

Invoke the given callback when a package is unloaded.

ArgumentDescription
callback
A Function to be invoked when a package is unloaded.
package
The Package that was unloaded.
Returns

Disposableon which .dispose() can be called to unsubscribe.

Package system data1

#::getPackageDirPaths()

PublicL240

Get the paths being used to look for packages.

Returns

Arrayof String directory paths.

General package data2

#::resolvePackagePath(name)

PublicL257

Resolve the given package name to a path on disk.

ArgumentDescription
name
The String package name.
Returns

Stringfolder path or undefined if it could not be resolved.

#::isBundledPackage(name)

PublicL318

Is the package with the given name bundled with Lumine?

ArgumentDescription
name
The String package name.
Returns

Boolean

Enabling and disabling packages3

#::enablePackage(name)

PublicL335

Enable the package with the given name.

ArgumentDescription
name
The String package name.
Returns

Packagethat was enabled or null if it isn’t loaded.

#::disablePackage(name)

PublicL352

Disable the package with the given name.

ArgumentDescription
name
The String package name.
Returns

Packagethat was disabled or null if it isn’t loaded.

#::isPackageDisabled(name)

PublicL369

Is the package with the given name disabled?

ArgumentDescription
name
The String package name.
Returns

Boolean

Accessing active packages4

#::getActivePackages()

PublicL383

Get an Array of all the active Packages.

#::getActivePackage(name)

PublicL396

Get the active Package with the given name.

ArgumentDescription
name
The String package name.
Returns

Packageor undefined.

#::isPackageActive(name)

PublicL409

Is the Package with the given name active?

ArgumentDescription
name
The String package name.
Returns

Boolean

#::hasActivatedInitialPackages()

PublicL419
Returns

Booleanindicating whether package activation has occurred.

Accessing loaded packages4

#::getLoadedPackages()

PublicL433

Get an Array of all the loaded Packages

#::getLoadedPackage(name)

PublicL453

Get the loaded Package with the given name.

ArgumentDescription
name
The String package name.
Returns

Packageor undefined.

#::isPackageLoaded(name)

PublicL466

Is the package with the given name loaded?

ArgumentDescription
name
The String package name.
Returns

Boolean

#::hasLoadedInitialPackages()

PublicL476
Returns

Booleanindicating whether package loading has occurred.

Accessing available packages6

#::getAvailablePackagePaths()

PublicL490
Returns

Arrayof Strings of all the available package paths.

#::getAvailablePackageNames()

PublicL500
Returns

Arrayof Strings of all the available package names.

#::getAvailablePackageMetadata()

PublicL510
Returns

Arrayof Strings of all the available package metadata.

#::getAvailablePackages(options)

PublicL529
ArgumentDescription
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

ArrayAvailable package descriptors that own their names, sorted by name.

#::getAvailablePackage(name)

PublicL544

Get the available package that owns the given name.

Returns

Object|undefinedpackage descriptor or undefined.

#::refreshPackageIndex()

PublicL560

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)

PublicL216

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.

ArgumentDescription
callback
Function
to be called when the pane is resized.
flexScale
Number
representing the pane’s flex-grow; ability for a flex item to grow if necessary.
Returns

Disposableon which ‘.dispose()’ can be called to unsubscribe.

#::observeFlexScale(callback)

PublicL231

Invoke the given callback with the current and future values of getFlexScale.

ArgumentDescription
callback
Function
to be called with the current and future values of the getFlexScale property.
flexScale
Number
representing the panes flex-grow; ability for a flex item to grow if necessary.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidActivate(callback)

PublicL248

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.

ArgumentDescription
callback
Function
to be called when the pane is activated.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onWillDestroy(callback)

PublicL261

Invoke the given callback before the pane is destroyed.

ArgumentDescription
callback
Function
to be called before the pane is destroyed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDestroy(callback)

PublicL274

Invoke the given callback when the pane is destroyed.

ArgumentDescription
callback
Function
to be called when the pane is destroyed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeActive(callback)

PublicL289

Invoke the given callback when the value of the #isActive property changes.

ArgumentDescription
callback
Function
to be called when the value of the #isActive property changes.
active
Boolean
indicating whether the pane is active.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeActive(callback)

PublicL307

Invoke the given callback with the current and future values of the #isActive property.

ArgumentDescription
callback
Function
to be called with the current and future values of the #isActive property.
active
Boolean
indicating whether the pane is active.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidAddItem(callback)

PublicL324

Invoke the given callback when an item is added to the pane.

ArgumentDescription
callback
Function
to be called when items are added.
event
Object
with the following keys:
item
The added pane item.
index
Number
indicating where the item is located.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidRemoveItem(callback)

PublicL340

Invoke the given callback when an item is removed from the pane.

ArgumentDescription
callback
Function
to be called when items are removed.
event
Object
with the following keys:
item
The removed pane item.
index
Number
indicating where the item was located.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onWillRemoveItem(callback)

PublicL355

Invoke the given callback before an item is removed from the pane.

ArgumentDescription
callback
Function
to be called before items are removed.
event
Object
with the following keys:
item
The pane item to be removed.
index
Number
indicating where the item is located.

#::onDidMoveItem(callback)

PublicL372

Invoke the given callback when an item is moved within the pane.

ArgumentDescription
callback
Function
to be called when items are moved.
event
Object
with the following keys:
item
The removed pane item.
oldIndex
Number
indicating where the item was located.
newIndex
Number
indicating where the item is now located.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeItems(callback)

PublicL386

Invoke the given callback with all current and future items.

ArgumentDescription
callback
Function
to be called with current and future items.
item
An item that is present in #getItems at the time of subscription or that is added at some later time.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeActiveItem(callback)

PublicL404

Invoke the given callback when the value of #getActiveItem changes.

ArgumentDescription
callback
Function
to be called when the active item changes.
activeItem
The current active item.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeActiveItem(callback)

PublicL419

Invoke the given callback with the current and future values of #getActiveItem.

ArgumentDescription
callback
Function
to be called with the current and future active items.
activeItem
The current active item.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onWillDestroyItem(callback)

PublicL436

Invoke the given callback before items are destroyed.

ArgumentDescription
callback
Function
to be called before items are destroyed.
event
Object
with the following keys:
item
The item that will be destroyed.
index
The location of the item.
Returns

Disposableon which .dispose() can be called to unsubscribe.

Items29

#::getItems()

PublicL479

Get the items in this pane.

Returns

Arrayof items.

#::getActiveItem()

PublicL491

Get the active pane item in this pane.

Returns

*pane item.

#::itemAtIndex(index)

PublicL541
ArgumentDescription
index
Number
Returns

*The item at the index, or null when no item exists there.

#::activateNextRecentlyUsedItem()

PublicL551

Makes the next item in the itemStack active.

#::activatePreviousRecentlyUsedItem()

PublicL567

Makes the previous item in the itemStack active.

#::moveActiveItemToTopOfStack()

PublicL585

Moves the active item to the end of the item stack once a modifier key (typically Ctrl) is lifted.

#::activateNextItem()

PublicL596

Makes the next item active.

#::activatePreviousItem()

PublicL611

Makes the previous item active.

#::moveItemRight()

PublicL630

Move the active tab to the right.

#::moveItemLeft()

PublicL643

Move the active tab to the left

#::getActiveItemIndex()

PublicL657

Get the index of the active item.

Returns

Number

#::activateItemAtIndex(index)

PublicL669

Activate the item at the given index.

ArgumentDescription
index
Number

#::activateItem(item, options = {})

PublicL685

Make the given item active, causing it to be displayed by the pane’s view.

ArgumentDescription
item
The item to activate
optionsoptional
Object
pendingoptional
Boolean
indicating that the item should be added in a pending state if it does not yet exist in the pane. Existing pending items in a pane are replaced with new pending items when they are opened.

#::addItem(item, options = {})

PublicL708

Add the given item to the pane.

ArgumentDescription
item
The item to add. It can be a model with an associated view or a view.
optionsoptional
Object
indexoptional
Number
indicating the index at which to add the item. If omitted, the item is added after the current active item.
pendingoptional
Boolean
indicating that the item should be added in a pending state. Existing pending items in a pane are replaced with new pending items when they are opened.
Returns

*added item.

#::togglePendingItem()

PublicL800

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)

PublicL831

Add the given items to the pane.

ArgumentDescription
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
Number
index at which to add the items. If omitted, the item is # added after the current active item.
Returns

Arrayof added items.

#::moveItem(item, newIndex)

PublicL899

Move the given item to the given index.

ArgumentDescription
item
The item to move.
newIndex
Number
indicating the index to which to move the item.

#::moveItemToPane(item, pane, index)

PublicL916

Move the given item to the given index on another pane.

ArgumentDescription
item
The item to move.
pane
Pane
to which to move the item.
index
Number
indicating the index to which to move the item in the given pane.

#::destroyActiveItem()

PublicL929

Destroy the active item and activate the next item.

Returns

Promisethat resolves when the item is destroyed.

#::destroyItem(item, force)

asyncPublicL950

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.

ArgumentDescription
item
Item to destroy
forceoptional
Boolean
Destroy the item without prompting to save it, even if the item’s isPermanentDockItem method returns true.
Returns

Promisethat resolves with a Boolean indicating whether or not the item was destroyed.

#::destroyItems()

PublicL998

Destroy all items.

#::destroyInactiveItems()

PublicL1008

Destroy all items except for the active item.

#::saveActiveItem(nextAction)

PublicL1118

Save the active item.

#::saveActiveItemAs(nextAction)

PublicL1132

Prompt the user for a location and save the active item with the path they select.

ArgumentDescription
nextActionoptional
Function
which will be called after the item is successfully saved.
Returns

Promisethat resolves when the save is complete

#::saveItem(item, nextAction)

PublicL1146

Save the given item.

ArgumentDescription
item
The item to save.
nextActionoptional
Function
which will be called with no argument after the item is successfully saved, or with the error if it failed. The return value will be that of nextAction or undefined if it was not provided.
Returns

Promisethat resolves when the save is complete, or rejects if the save could not be completed.

#::saveItemAs(item, nextAction)

asyncPublicL1212

Prompt the user for a location and save the active item with the path they select.

ArgumentDescription
item
The item to save.
nextActionoptional
Function
which will be called with no argument after the item is successfully saved, or with the error if it failed. The return value will be that of nextAction or undefined if it was not provided.

#::saveItems()

asyncPublicL1244

Save all modified items in this pane.

Returns

Promisethat resolves when all items have been saved.

#::itemForURI(uri)

PublicL1261
ArgumentDescription
uri
String
containing a URI.
Returns

*|undefinedfirst item that matches the given URI or undefined if none exists.

#::activateItemForURI(uri)

PublicL1280

Activate the first item that matches the given URI.

ArgumentDescription
uri
String
containing a URI.
Returns

Booleanindicating whether an item matching the URI was found.

Lifecycle4

#::isActive()

PublicL1308

Determine whether the pane is active.

Returns

Boolean

#::activate()

PublicL1318

Makes this pane the active pane, causing it to gain focus.

#::destroy()

PublicL1344

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()

PublicL1379

Determine whether this pane has been destroyed.

Returns

Boolean

Splitting4

#::splitLeft(params)

PublicL1399

Create a new pane to the left of this pane.

ArgumentDescription
paramsoptional
Object
with the following keys:
itemsoptional
Array
of items to add to the new pane.
copyActiveItemoptional
Boolean
true will copy the active item into the new split pane
activateoptional
Boolean
false will leave the currently active pane active instead of activating the new pane. Defaults to true.
Returns

Panenew Pane.

#::splitRight(params)

PublicL1415

Create a new pane to the right of this pane.

ArgumentDescription
paramsoptional
Object
with the following keys:
itemsoptional
Array
of items to add to the new pane.
copyActiveItemoptional
Boolean
true will copy the active item into the new split pane
activateoptional
Boolean
false will leave the currently active pane active instead of activating the new pane. Defaults to true.
Returns

Panenew Pane.

#::splitUp(params)

PublicL1431

Creates a new pane above the receiver.

ArgumentDescription
paramsoptional
Object
with the following keys:
itemsoptional
Array
of items to add to the new pane.
copyActiveItemoptional
Boolean
true will copy the active item into the new split pane
activateoptional
Boolean
false will leave the currently active pane active instead of activating the new pane. Defaults to true.
Returns

Panenew Pane.

#::splitDown(params)

PublicL1447

Creates a new pane below the receiver.

ArgumentDescription
paramsoptional
Object
with the following keys:
itemsoptional
Array
of items to add to the new pane.
copyActiveItemoptional
Boolean
true will copy the active item into the new split pane
activateoptional
Boolean
false will leave the currently active pane active instead of activating the new pane. Defaults to true.
Returns

Panenew Pane.

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()

PublicL47

Destroy and remove this panel from the UI.

Event Subscription2

#::onDidChangeVisible(callback)

PublicL80

Invoke the given callback when the pane hidden or shown.

ArgumentDescription
callback
Function
to be called when the pane is destroyed.
visible
Boolean
true when the panel has been shown
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDestroy(callback)

PublicL94

Invoke the given callback when the pane is destroyed.

ArgumentDescription
callback
Function
to be called when the pane is destroyed.
panel
Panel
this panel
Returns

Disposableon which .dispose() can be called to unsubscribe.

Panel Details5

#::getItem()

PublicL108
Returns

*panel’s item.

#::getPriority()

PublicL118
Returns

Numberindicating this panel’s priority.

#::isVisible()

PublicL132
Returns

Booleantrue when the panel is visible.

#::hide()

PublicL142

Hide this panel

#::show(options)

PublicL158

Show this panel.

ArgumentDescription
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 } = {})

ExperimentalL72

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.

ArgumentDescription
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
Object
Registration options.
priorityoptional, default: 0
Number
The order in which providers are consulted, highest first. Ties preserve registration order.
Returns

DisposableA disposable that unregisters the provider.

#::handlePaste(context)

ExperimentalL113

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.

ArgumentDescription
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

Booleantrue 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:

  • rootPath String specifies the absolute path to the root of the filesystem content to watch.
  • options Control the watcher’s behavior:
    • realPaths Boolean whether to report the real path on disk for each event. Default true; false reports paths that descend from rootPath even where symlinks point elsewhere.
  • eventCallback Function to be called each time a batch of filesystem events is observed. Each event object has the keys:
    • action, a String describing the filesystem action that occurred, one of "created", "updated", "deleted", or "renamed";
    • path, a String containing the absolute path to the filesystem entry that was acted upon;
    • oldPath (for renamed events only), a String containing the filesystem entry’s former absolute path.

Methods3

#::getStartPromise()

ExtendedL773

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

Promisethat 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)

ExtendedL815

Invoke a Function when any errors related to this watcher are reported.

ArgumentDescription
callback
Function
to be called when an error occurs.
err
An Error describing the failure condition.
Returns

Disposable

#::dispose()

ExtendedL1003

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)

PublicL38

Convert any point-compatible object to a Point.

ArgumentDescription
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

PointA point based on the given object.

Comparison9

#.min(point1, point2)

PublicL65
ArgumentDescription
point1
point2
Returns

Pointgiven Point that occurs earlier in the buffer.

#.max(point1, point2)

PublicL83
ArgumentDescription
point1
point2
Returns

Pointgiven Point that occurs later in the buffer.

#.assertValid(point)

PublicL100

Ensure the given Point is valid by throwing a TypeError if either its row or its column is not an integer.

#::compare(other)

PublicL248
ArgumentDescription
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)

PublicL272
ArgumentDescription
other
A Point or point-compatible Array.
Returns

Booleanindicating whether this point has the same row and column as the given Point or point-compatible Array.

#::isLessThan(other)

PublicL287
ArgumentDescription
other
A Point or point-compatible Array.
Returns

Booleanindicating whether this point precedes the given Point or point-compatible Array.

#::isLessThanOrEqual(other)

PublicL298
ArgumentDescription
other
A Point or point-compatible Array.
Returns

Booleanindicating whether this point precedes or is equal to the given Point or point-compatible Array.

#::isGreaterThan(other)

PublicL309
ArgumentDescription
other
A Point or point-compatible Array.
Returns

Booleanindicating whether this point follows the given Point or point-compatible Array.

#::isGreaterThanOrEqual(other)

PublicL320
ArgumentDescription
other
A Point or point-compatible Array.
Returns

Booleanindicating whether this point follows or is equal to the given Point or point-compatible Array.

Construction3

#new Point(row = 0, column = 0)

PublicL119

Construct a Point object.

ArgumentDescription
row
Number
row
column
Number
column

#::copy()

PublicL130
Returns

Pointnew Point with the same row and column.

#::negate()

PublicL140
Returns

Pointnew Point with the row and column negated.

Operations3

#::freeze()

PublicL156

Make this point immutable and return itself.

Returns

Pointimmutable version of this Point.

#::translate(other)

PublicL170

Build and return a new point by adding the rows and columns of the given point.

ArgumentDescription
other
A Point whose row and column will be added to this point’s row and column to build the returned point.
Returns

Point

#::traverse(other)

PublicL200

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]

ArgumentDescription
other
A Point providing the rows and columns to traverse by.
Returns

Point

Conversion3

#::toArray()

PublicL358
Returns

Arrayarray of this point’s row and column.

#::serialize()

PublicL368
Returns

Arrayarray of this point’s row and column.

#::toString()

PublicL378
Returns

Stringstring representation of the point.

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)

PublicL217

Invoke the given callback when the project paths change.

ArgumentDescription
callback
Function
to be called after the project paths change.
projectPaths
An Array of String project paths.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidAddBuffer(callback)

PublicL232

Invoke the given callback when a text buffer is added to the project.

ArgumentDescription
callback
Function
to be called when a text buffer is added.
buffer
A TextBuffer item.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeBuffers(callback)

PublicL247

Invoke the given callback with all current and future text buffers in the project.

ArgumentDescription
callback
Function
to be called with current and future text buffers.
buffer
A TextBuffer item.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeFiles(callback)

ExtendedL297

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.

ArgumentDescription
callback
Function
to 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
String
describing the filesystem action that occurred. One of "created", "updated", or "deleted".
path
String
containing the absolute path to the filesystem entry that was acted upon.
Returns

Disposableto manage this event subscription.

Accessing the git repository2

#::repositoryForDirectory(directory)

PublicL317

Get the repository for a given directory asynchronously.

  • null if no repository can be created for the given directory.
ArgumentDescription
directory
Directory
for which to get a GitRepository.
Returns

Promisethat resolves with either: * GitRepository if a repository can be created for the given directory

#::repositoryForPath(filePath)

PublicL339

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.

  • null if no repository can be created for the given path.
ArgumentDescription
filePath
String
path of a file or directory.
Returns

Promisethat resolves with either: * GitRepository if a repository can be created for the given path

Managing Paths10

#::getPaths()

PublicL390

Get an Array of Strings containing the paths of the project’s directories.

#::setPaths(projectPaths, options = {})

PublicL411

Set the paths of the project’s directories.

ArgumentDescription
projectPaths
Array
of 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)

asyncPublicL483

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.open with newWindow for 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.
ArgumentDescription
projectPaths
Array
of String paths to the directories the window should have open.
Returns

Promisethat 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 = {})

PublicL500

Add a path to the project’s list of root paths

ArgumentDescription
projectPath
String
The 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 = {})

PublicL585

Add multiple paths to the project’s list of root paths, emitting a single did-change-paths event after all paths are added.

ArgumentDescription
projectPaths
An Array of String paths to add.
options
An optional Object passed to #addPath for each path.

#::getWatcherPromise(projectPath)

ExtendedL633

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.

ArgumentDescription
projectPath
String
One of the project’s root directories.
Returns

Promisethat 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)

PublicL648

remove a path from the project’s list of root paths.

ArgumentDescription
projectPath
String
The path to remove.

#::getDirectories()

PublicL686

Get an Array of Directorys associated with this project.

#::relativizePath(fullPath)

PublicL733

Get the path to the project directory that contains the given path, and the relative path from that project directory to the given path.

  • projectPath The String path to the project directory that contains the given path, or null if none is found.
  • relativePath String The relative path from the project directory to the given path.
ArgumentDescription
fullPath
String
An absolute path.
Returns

Arraywith two elements:

#::contains(pathToCheck)

PublicL777

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
ArgumentDescription
pathToCheck
String
path
Returns

Booleanwhether the path is inside the project’s root directory.

Crawling files8

#::crawl(options = {})

PublicL814

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;
ArgumentDescription
optionsoptional
Object
didFindPaths
Function
called 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
String
glob scoping the crawl. ** means “everything”.
ignoredNames
an Array of String globs to exclude. Defaults to core.ignoredNames.
followSymlinks
Boolean
whether to descend into symlinked directories. Defaults to core.followSymlinks.
excludeVcsIgnoredPaths
Boolean
whether to honor VCS ignore files. Defaults to core.excludeVcsIgnoredPaths. Only takes effect inside a repository — a directory with no .git above it lists everything.
sort
Boolean
whether to return paths in a stable order. Costs ripgrep its parallel walk, so only ask when the order is observable.
Returns

Promisewith a cancel() method that resolves the crawl early.

#::observeFilePaths(callback)

PublicL877

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.

ArgumentDescription
callback
Function
to 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

Disposableon which .dispose() can be called to unsubscribe.

#::getFilePaths()

PublicL910

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

Arrayof String absolute paths.

#::getFilePathsForRoot(root)

PublicL927

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.

ArgumentDescription
root
String|Directory
a project root path, or its Directory.
Returns

Arrayof String absolute paths, empty for a path that is not a project root.

#::hasFilePath(filePath)

PublicL947

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.

ArgumentDescription
filePath
String
an absolute path.
Returns

Boolean

#::getFilePathCount()

PublicL961

How many files are indexed.

Cheaper than getFilePaths().length, which materializes the array.

Returns

Number

#::isIndexing()

PublicL976

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 = {})

PublicL999

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.

ArgumentDescription
optionsoptional
Object
rootPaths
An Array of String roots to re-crawl. Defaults to all of them.
Returns

Promisethat 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)

PublicL47

Convert any range-compatible object to a Range.

ArgumentDescription
object
This can be an object that’s already a Range, in which case it’s simply returned, or an array containing two Points or point-compatible arrays.
copy
An optional boolean indicating whether to force the copying of objects that are already ranges.
Returns

RangeA range based on the given object.

#new Range(pointA, pointB)

PublicL148

Construct a Range object

ArgumentDescription
pointA
Point
or Point compatible Array (default: [0,0])
pointB
Point
or Point compatible Array (default: [0,0])

#::copy()

PublicL177
Returns

Rangenew range with the same start and end positions.

#::negate()

PublicL187
Returns

Rangenew range with the start and end positions negated.

Serialization and Deserialization2

#.deserialize(array)

PublicL127

Call this with the result of Range#serialize to construct a new Range.

ArgumentDescription
array
Array
of params to pass to the #constructor

#::serialize()

PublicL201
Returns

Objectplain JavaScript object representation of the range.

Range Details4

#::isEmpty()

PublicL217

Is the start position of this range equal to the end position?

Returns

Boolean

#::isSingleLine()

PublicL227
Returns

Booleanindicating whether this range starts and ends on the same row.

#::getRowCount()

PublicL239

Get the number of rows in this range.

Returns

Number

#::getRows()

PublicL249
Returns

Arrayarray of all rows in the range.

Operations4

#::freeze()

PublicL266

Freezes the range and its start and end point so it becomes immutable and returns itself.

Returns

Rangeimmutable version of this Range

#::union(otherRange)

PublicL279
ArgumentDescription
otherRange
A Range or range-compatible Array
Returns

Rangenew range that contains this range and the given range.

#::translate(startDelta, endDelta)

PublicL296

Build and return a new range by translating this range’s start and end points by the given delta(s).

ArgumentDescription
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

Range

#::traverse(delta)

PublicL315

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.

ArgumentDescription
delta
A Point containing the rows and columns to traverse to derive the new range.
Returns

Range

Comparison8

#::compare(other)

PublicL332

Compare two Ranges

ArgumentDescription
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)

PublicL349
ArgumentDescription
other
A Range or range-compatible Array.
Returns

Booleanindicating whether this range has the same start and end points as the given Range or range-compatible Array.

#::coversSameRows(other)

PublicL364
ArgumentDescription
other
A Range or range-compatible Array.
Returns

Booleanindicating whether this range starts and ends on the same row as the argument.

#::intersectsWith(otherRange, exclusive)

PublicL378

Determines whether this range intersects with the argument.

ArgumentDescription
otherRange
A Range or range-compatible Array
exclusiveoptional
Boolean
indicating whether to exclude endpoints when testing for intersection. Defaults to false.
Returns

Boolean

#::containsRange(otherRange, exclusive)

PublicL397
ArgumentDescription
otherRange
A Range or range-compatible Array
exclusiveoptional
Boolean
including that the containment should be exclusive of endpoints. Defaults to false.
Returns

Booleanindicating whether this range contains the given range.

#::containsPoint(point, exclusive)

PublicL410
ArgumentDescription
point
A Point or point-compatible Array
exclusiveoptional
Boolean
including that the containment should be exclusive of endpoints. Defaults to false.
Returns

Booleanindicating whether this range contains the given point.

#::intersectsRow(row)

PublicL426
ArgumentDescription
row
Row Number
Returns

Booleanindicating whether this range intersects the given row Number.

#::intersectsRowRange(startRow, endRow)

PublicL438
ArgumentDescription
startRow
Number
start row
endRow
Number
end row
Returns

Booleanindicating whether this range intersects the row range indicated by the given startRow and endRow Numbers.

Conversion1

#::toString()

PublicL470
Returns

Stringstring 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()

EssentialL272

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

GitRepositoryor null when the active item belongs to none.

#::getActiveRepositoryContext()

PublicL294

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.

  • repository The active GitRepository, or null.
  • workingDirectory The String directory the context applies to, or null when no file-backed item is focused.
  • pinned A Boolean, true while a manual selection holds.
Returns

Objectfrozen Object.

#::isActiveRepositoryPinned()

PublicL310

Whether the active repository is pinned to a manual selection.

Returns

Boolean

#::onDidChangeActiveRepository(callback)

PublicL326

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.

ArgumentDescription
callback
Function
called with the context #getActiveRepositoryContext
Returns

DisposableA subscription that can be disposed to unsubscribe.

#::observeActiveRepository(callback)

EssentialL343

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.

ArgumentDescription
callback
Function
called with the context #getActiveRepositoryContext
Returns

DisposableA subscription that can be disposed to unsubscribe.

#::setActiveRepository(repository, { pin = false } = {})

PublicL361

Select the active repository manually.

Throws a TypeError if the repository is unregistered or destroyed.

ArgumentDescription
repository
The GitRepository to activate, or null to clear any pin and recompute the active repository from the workspace.
optionsoptional
Object
Activation options.
pinoptional, default: false
Boolean
Keep the selection until it is cleared instead of following the next pane-item change.

#::setActiveRepositoryForPath(filePath, { pin = false } = {})

asyncPublicL392

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.

ArgumentDescription
filePath
The String path to resolve.
optionsoptional
Object
Activation options.
pinoptional, default: false
Boolean
Keep the selection as in #setActiveRepository.
Returns

Promisethat resolves to the GitRepository, or to null when the path is not in one.

Accessing Repositories3

#::getSnapshot()

ExtendedL608

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.

  • version A Number.
  • repositories A frozen Array of GitRepository.
Returns

Objectfrozen Object.

#::getById(id)

ExtendedL639

Look a repository up by the id the registry gave it.

ArgumentDescription
id
The String id.
Returns

GitRepositoryor null if nothing is registered under it.

Event Subscription9

#::observeRepositories(callback)

EssentialL657

Invoke the callback with every registered repository, now and in the future.

ArgumentDescription
callback
Function
called with each GitRepository.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidAddRepository(callback)

PublicL671

Invoke the callback when a repository is registered.

ArgumentDescription
callback
Function
called with the new GitRepository.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidRemoveRepository(callback)

PublicL687

Invoke the callback when a repository is removed.

Release anything keyed on the repository here: it is destroyed once nothing holds it any more.

ArgumentDescription
callback
Function
called with the removed GitRepository.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChange(callback)

ExtendedL711

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.

ArgumentDescription
callback
Function
called 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

Disposableon which .dispose() can be called to unsubscribe.

#::onDidStartRescan(callback)

ExtendedL725

Invoke the callback when a rescan of the project roots begins.

ArgumentDescription
callback
Function
called with a frozen Object.
id
A Number identifying this rescan.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidFinishRescan(callback)

ExtendedL742

Invoke the callback when a rescan finishes, whether or not it succeeded.

ArgumentDescription
callback
Function
called 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

Disposableon which .dispose() can be called to unsubscribe.

#::onDidQueueOperation(callback)

ExtendedL756

Invoke the callback when an operation is queued behind another on the same repository.

ArgumentDescription
callback
Function
called with an operation snapshot; see #getPendingOperations.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidStartOperation(callback)

ExtendedL769

Invoke the callback when an operation starts running.

ArgumentDescription
callback
Function
called with an operation snapshot; see #getPendingOperations.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidFinishOperation(callback)

ExtendedL783

Invoke the callback when an operation finishes, whether or not it succeeded.

ArgumentDescription
callback
Function
called with an operation snapshot; see #getPendingOperations.
Returns

Disposableon which .dispose() can be called to unsubscribe.

Resolving Paths5

#::getForPath(filePath)

EssentialL807

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.

ArgumentDescription
filePath
The String path to look up.
Returns

GitRepositoryor null.

#::resolveForPath(filePath)

asyncPublicL857

The repository a path belongs to, discovering and registering one if it is not known yet.

ArgumentDescription
filePath
The String path to resolve.
Returns

Promisethat resolves to a GitRepository, or to null when the path is not in one.

#::resolveForPathSync(filePath)

ExtendedL878

#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.

ArgumentDescription
filePath
The String path to resolve.
Returns

GitRepositoryor null.

#::resolveDirectory(directory)

asyncExtendedL896

The repository for a Directory, discovering and registering one if it is not known yet.

ArgumentDescription
directory
The Directory to resolve.
Returns

Promisethat resolves to a GitRepository, or to null.

#::resolveDirectorySync(directory)

ExtendedL910

#resolveDirectory, synchronously. Reads the filesystem.

ArgumentDescription
directory
The Directory to resolve.
Returns

GitRepositoryor null.

Managing Repositories4

#::retain(repository, source = "pin")

PublicL934

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.

ArgumentDescription
repository
The GitRepository to hold.
sourceoptional
A String label for the hold, for debugging.
Returns

Disposablethat releases the hold.

#::runOperation(repository, operation)

asyncExtendedL962

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.

ArgumentDescription
repository
The GitRepository to work with.
operation
An async Function called with the repository.
Returns

Promisefor whatever the operation returned.

#::add(filePath, { persist = true } = {})

asyncPublicL1602

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.

  • repository The GitRepository.
  • dispose A Function that releases it.
ArgumentDescription
filePath
The String path inside the repository to add.
optionsoptional
Object
Registration options.
persistoptional, default: true
Boolean
Remember the repository across window reloads. Pass false to keep it for this session only.
Returns

Promisethat resolves to an Object, or to null when the path is not in a repository.

#::forget(repository)

PublicL1633

Drop every manual hold #add placed on a repository.

The repository stays registered while a project root or an open buffer still owns it.

ArgumentDescription
repository
The GitRepository to forget.
Returns

Booleantrue if the repository was registered.

Operations5

#::addOperationProvider(provider, { fallback = false } = {})

PublicL1000

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.

ArgumentDescription
provider
The Object implementing the operations.
optionsoptional
Object
Provider options.
fallbackoptional, default: false
Boolean
Put the provider last so later registrations take precedence.
Returns

Disposablethat removes the provider and everything it implemented.

#::getOperations(repository)

PublicL1042

The operations available on a repository.

ArgumentDescription
repository
Returns

Objectof operation functions, or null when no provider has claimed the repository.

#::canPerformOperation(repository, operationName)

EssentialL1060

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.

ArgumentDescription
repository
operationName
The String name of the operation, such as "commit".
Returns

Boolean

#::getOperationCapabilities(repository)

PublicL1073

Every operation any provider can perform on a repository.

ArgumentDescription
repository
Returns

Arrayfrozen Array of String operation names.

#::getPendingOperations(repository)

PublicL1115

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.

  • id A Number identifying the operation.
  • name The String operation name.
  • status A String, "queued" or "running".
  • workingDirectory The String directory it runs in, or null.
  • queuedAt The Number timestamp it was queued at.
  • startedAt The Number timestamp it started at, or null.
ArgumentDescription
repository
The GitRepository it runs on, or null.
Returns

Arrayfrozen Array of frozen Objects.

Creating Repositories4

#::getWorkspaceOperationCapabilities()

PublicL1149

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

Arrayfrozen Array of String operation names.

#::canPerformWorkspaceOperation(operationName)

PublicL1165

Whether a repository-creating operation can be performed.

ArgumentDescription
operationName
A String, "initialize" or "clone".
Returns

Boolean

#::initialize(directoryPath, options)

PublicL1243

Create a repository in a directory and register it.

ArgumentDescription
directoryPath
The String directory to initialize.
optionsoptional
Object
passed through to the provider.
Returns

Promisethat 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)

PublicL1258

Clone a remote into a directory and register the result.

ArgumentDescription
remoteUrl
The String URL to clone.
destinationPath
The String directory to clone into.
optionsoptional
Object
passed through to the provider.
Returns

Promisethat resolves to the new GitRepository, and rejects the same way #initialize does.

Running Git3

#::canExecuteGitCommands()

PublicL1181

Whether any provider can run raw Git commands.

Returns

Boolean

#::executeGit(args, workingDirectory, options)

ExtendedL1200

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.

ArgumentDescription
args
An Array of String arguments, without the leading git.
workingDirectory
The String directory to run in.
optionsoptional
Object
passed through to the provider.
Returns

Promisefor 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()

ExtendedL1225

The Git binary the active provider runs.

Returns

Stringpath, 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)

ExtendedL20

Subscribe before an unhandled renderer error is reported.

Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidThrowError(callback)

ExtendedL32

Subscribe after an unhandled renderer error is reported.

Returns

Disposableon which .dispose() can be called to unsubscribe.

#::whenShellEnvironmentLoaded()

ExtendedL44

Wait until the current renderer has loaded its shell environment.

Returns

Promisethat resolves once environment loading is complete.

#::getShellLoadTime()

ExtendedL57
Returns

Number|nullThe 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.

See the scopes and scope descriptor guide for more information.

Construction and Destruction2

#new ScopeDescriptor({ scopes })

PublicL47

Create a ScopeDescriptor object.

ArgumentDescription
object
Object
Scope data.
scopes
Array<String>
The ordered syntax scopes.

#::getScopesArray()

PublicL57
Returns

Arrayof 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()

asyncExtendedL64

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

Promiseresolving to a Boolean.

#::get(key)

asyncEssentialL128

Read a secret.

ArgumentDescription
key
The String key it was stored under.
Returns

Promisethat 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)

asyncEssentialL167

Store a secret.

ArgumentDescription
key
The String key to store it under.
value
The String to store. null or undefined deletes the key, as #delete would.
Returns

Promisethat resolves once the value is written.

#::delete(key)

asyncPublicL199

Forget a secret.

Deleting a key that was never stored is not an error and emits nothing.

ArgumentDescription
key
The String key to remove.
Returns

Promisethat resolves once the key is gone.

Event Subscription1

#::onDidChange(callback)

PublicL225

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.

ArgumentDescription
callback
Function
called with an Object.
key
The String key that changed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

Extended API

Selectionsrc/selection.js:14

Represents a selection in the TextEditor.

Event Subscription2

#::onDidChangeRange(callback)

ExtendedL59

Calls your callback when the selection was moved.

ArgumentDescription
callback
Function
event
Object
oldBufferRange
oldScreenRange
newBufferRange
newScreenRange
selection
Selection
that triggered the event
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDestroy(callback)

ExtendedL72

Calls your callback when the selection was destroyed

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

Managing the selection range5

#::getScreenRange()

PublicL86
Returns

Rangescreen Range for the selection.

#::setScreenRange(screenRange, options)

PublicL99

Modifies the screen range for the selection.

ArgumentDescription
screenRange
The new Range to use.
optionsoptional
Object
options matching those found in #setBufferRange.

#::getBufferRange()

PublicL109
Returns

Rangebuffer Range for the selection.

#::setBufferRange(bufferRange, options = {})

PublicL125

Modifies the buffer Range for the selection.

ArgumentDescription
bufferRange
The new Range to select.
optionsoptional
Object
with the keys:
reversed
Boolean
indicating whether to set the selection in a reversed orientation.
preserveFolds
if true, the fold settings are preserved after the selection moves.
autoscroll
Boolean
indicating whether to autoscroll to the new range. Defaults to true if this is the most recently added selection, false otherwise.

#::getBufferRowRange()

PublicL146
Returns

Array<Number>The starting and ending buffer rows highlighted by the selection.

Info about the selection6

#::isEmpty()

PublicL180

Determines if the selection contains anything.

#::isReversed()

PublicL193

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()

PublicL203
Returns

Booleanwhether the selection is a single line or not.

#::getText()

PublicL213
Returns

Stringtext in the selection.

#::intersectsBufferRange(bufferRange)

PublicL226

Identifies if a selection intersects with a given buffer range.

ArgumentDescription
bufferRange
A Range to check against.
Returns

Boolean

#::intersectsWith(otherSelection, exclusive)

PublicL247

Identifies if a selection intersects with another selection.

ArgumentDescription
otherSelection
A Selection to check against.
Returns

Boolean

Modifying the selected range28

#::clear(options)

PublicL264

Clears the selection, moving the marker to the head.

ArgumentDescription
optionsoptional
Object
with the following keys:
autoscroll
Boolean
indicating whether to autoscroll to the new range. Defaults to true if this is the most recently added selection, false otherwise.

#::selectToScreenPosition(position, options)

PublicL282

Selects the text from the current cursor position to a given screen position.

ArgumentDescription
position
An instance of Point, with a given row and column.

#::selectToBufferPosition(position)

PublicL317

Selects the text from the current cursor position to a given buffer position.

ArgumentDescription
position
An instance of Point, with a given row and column.

#::selectRight(columnCount)

PublicL329

Selects the text one position right of the cursor.

ArgumentDescription
columnCountoptional
Number
number of columns to select (default: 1)

#::selectLeft(columnCount)

PublicL341

Selects the text one position left of the cursor.

ArgumentDescription
columnCountoptional
Number
number of columns to select (default: 1)

#::selectUp(rowCount)

PublicL353

Selects all the text one position above the cursor.

ArgumentDescription
rowCountoptional
Number
number of rows to select (default: 1)

#::selectDown(rowCount)

PublicL365

Selects all the text one position below the cursor.

ArgumentDescription
rowCountoptional
Number
number of rows to select (default: 1)

#::selectToTop()

PublicL376

Selects all the text from the current cursor position to the top of the buffer.

#::selectToBottom()

PublicL387

Selects all the text from the current cursor position to the bottom of the buffer.

#::selectAll()

PublicL397

Selects all the text in the buffer.

#::selectToBeginningOfLine()

PublicL408

Selects all the text from the current cursor position to the beginning of the line.

#::selectToFirstCharacterOfLine()

PublicL419

Selects all the text from the current cursor position to the first character of the line.

#::selectToEndOfLine()

PublicL430

Selects all the text from the current cursor position to the end of the screen line.

#::selectToEndOfBufferLine()

PublicL441

Selects all the text from the current cursor position to the end of the buffer line.

#::selectToBeginningOfWord()

PublicL452

Selects all the text from the current cursor position to the beginning of the word.

#::selectToEndOfWord()

PublicL463

Selects all the text from the current cursor position to the end of the word.

#::selectToBeginningOfNextWord()

PublicL474

Selects all the text from the current cursor position to the beginning of the next word.

#::selectToPreviousWordBoundary()

PublicL484

Selects text to the previous word boundary.

#::selectToNextWordBoundary()

PublicL494

Selects text to the next word boundary.

#::selectToPreviousSubwordBoundary()

PublicL504

Selects text to the previous subword boundary.

#::selectToNextSubwordBoundary()

PublicL514

Selects text to the next subword boundary.

#::selectToBeginningOfNextParagraph()

PublicL525

Selects all the text from the current cursor position to the beginning of the next paragraph.

#::selectToBeginningOfPreviousParagraph()

PublicL536

Selects all the text from the current cursor position to the beginning of the previous paragraph.

#::selectSubword(options = {})

PublicL548

Modifies the selection to encompass the current subword.

ArgumentDescription
optionsoptional, default: {}
No description.
Returns

Range

#::selectWord(options = {})

PublicL563

Modifies the selection to encompass the current word.

ArgumentDescription
optionsoptional, default: {}
No description.
Returns

Range

#::expandOverWord(options)

PublicL581

Expands the newest selection to include the entire word on which the cursors rests.

#::selectLine(row, options)

PublicL598

Selects an entire line in the buffer.

ArgumentDescription
row
The line Number to select (default: the row of the cursor).

#::expandOverLine(options)

PublicL628

Expands the newest selection to include the entire line on which the cursor currently rests.

It also includes the newline character.

Modifying the selected text23

#::insertText(text, options = {})

PublicL682

Replaces text at the current selection.

ArgumentDescription
text
A String representing the text to add
optionsoptional
Object
with keys:
select
If true, selects the newly added text.
autoIndent
If true, indents all inserted text appropriately.
autoIndentNewline
If true, indent newline appropriately.
autoDecreaseIndent
If true, decreases indent level appropriately (for example, when a closing bracket is inserted).
preserveTrailingLineIndentation
By default, when pasting multiple lines, Lumine attempts to preserve the relative indent level between the first line and trailing lines, even if the indent level of the first line has changed from the copied text. If this option is true, this behavior is suppressed. level between the first lines and the trailing lines.
normalizeLineEndingsoptional
Boolean
(default: true)
undo
Deprecated If skip, skips the undo stack for this operation. This property is deprecated. Call groupLastChanges() on the TextBuffer afterward instead.
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::backspace(options = {})

PublicL770

Removes the first character before the selection if the selection is empty otherwise it deletes the selection.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::deleteToPreviousWordBoundary(options = {})

PublicL787

Removes the selection or, if nothing is selected, then all characters from the start of the selection back to the previous word boundary.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::deleteToNextWordBoundary(options = {})

PublicL804

Removes the selection or, if nothing is selected, then all characters from the start of the selection up to the next word boundary.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::deleteToBeginningOfWord(options = {})

PublicL820

Removes from the start of the selection to the beginning of the current word if the selection is empty otherwise it deletes the selection.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::deleteToBeginningOfLine(options = {})

PublicL836

Removes from the beginning of the line which the selection begins on all the way through to the end of the selection.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::delete(options = {})

PublicL856

Removes the selection or the next character after the start of the selection if the selection is empty.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::deleteToEndOfLine(options = {})

PublicL874

If the selection is empty, removes all text from the cursor to the end of the line. If the cursor is already at the end of the line, it removes the following newline. If the selection isn’t empty, only deletes the contents of the selection.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::deleteToEndOfWord(options = {})

PublicL896

Removes the selection or all characters from the start of the selection to the end of the current word if nothing is selected.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::deleteToBeginningOfSubword(options = {})

PublicL912

Removes the selection or all characters from the start of the selection to the end of the current word if nothing is selected.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::deleteToEndOfSubword(options = {})

PublicL928

Removes the selection or all characters from the start of the selection to the end of the current word if nothing is selected.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::deleteSelectedText(options = {})

PublicL943

Removes only the selected text.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::deleteLine(options = {})

PublicL961

Removes the line at the beginning of the selection if the selection is empty unless the selection spans multiple lines in which case all lines are removed.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::joinLines(options = {})

PublicL996

Joins the current line with the one below it. Lines will be separated by a single space.

If there selection spans more than one line, all the lines are joined together.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::outdentSelectedRows(options = {})

PublicL1060

Removes one level of indent from the currently selected rows.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::autoIndentSelectedRows(options = {})

PublicL1086

Sets the indentation level of all selected rows to values suggested by the relevant grammars.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::toggleLineComments(options = {})

PublicL1104

Wraps the selected lines in comments if they aren’t currently part of a comment.

Removes the comment if they are currently wrapped in a comment.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::cutToEndOfLine(maintainClipboard, options = {})

PublicL1123

Cuts the selection until the end of the screen line.

ArgumentDescription
maintainClipboard
Boolean
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::cutToEndOfBufferLine(maintainClipboard, options = {})

PublicL1139

Cuts the selection until the end of the buffer line.

ArgumentDescription
maintainClipboard
Boolean
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

#::cut(maintainClipboard = false, fullLine = false, bypassReadOnly = false, clipboard = this.editor.constructor.clipboard)

PublicL1155

Copies the selection to the clipboard and then deletes it.

ArgumentDescription
maintainClipboard
Boolean
(default: false) See #copy
fullLine
Boolean
(default: false) See #copy
bypassReadOnly
Boolean
(default: false) Must be true to modify text within a read-only editor.
clipboardoptional, default: this.editor.constructor.clipboard
No description.

#::copy(maintainClipboard = false, fullLine = false, clipboard = this.editor.constructor.clipboard)

PublicL1175

Copies the current selection to the clipboard.

ArgumentDescription
maintainClipboard
Boolean
if true, a specific metadata property is created to store each content copied to the clipboard. The clipboard text still contains the concatenation of the clipboard with the current selection. (default: false)
fullLine
Boolean
if true, the copied text will always be pasted at the beginning of the line containing the cursor, regardless of the cursor’s horizontal position. (default: false)
clipboardoptional, default: this.editor.constructor.clipboard
No description.

#::fold()

PublicL1214

Creates a fold containing the current selection.

#::indentSelectedRows(options = {})

PublicL1286

If the selection spans multiple rows, indent all of them.

ArgumentDescription
optionsoptional
Object
with the keys:
bypassReadOnlyoptional
Boolean
Must be true to modify text within a read-only editor. (default: false)

Managing multiple selections3

#::addSelectionBelow()

PublicL1306

Moves the selection down one row.

#::addSelectionAbove()

PublicL1341

Moves the selection up one row.

#::merge(otherSelection, options = {})

PublicL1380

Combines the given selection into this selection and then destroys the given selection.

ArgumentDescription
otherSelection
A Selection to merge with.
optionsoptional
Object
options matching those found in #setBufferRange.

Comparing to other selections1

#::compare(otherSelection)

PublicL1410

Compare this selection’s buffer range to another selection’s buffer range.

See Range#compare for more details.

ArgumentDescription
otherSelection
A Selection to compare against

Public API

ServiceHubsrc/service-hub.js:151

Methods4

#::provide(keyPath, version, service)

PublicL169

Provide a service by invoking the callback of all current and future consumers matching the given service name and version range.

ArgumentDescription
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

Disposableon which .dispose() can be called to remove the provided service.

#::consume(keyPath, versionRange, callback)

PublicL233

Consume a service by invoking the given callback for all current and future provided services matching the given service name and version range.

ArgumentDescription
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

Disposableon 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()

PublicL282

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

Arrayof {keyPath, versionRange}.

#::clear()

PublicL298

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)

PublicL20

Move an item to the operating system trash.

Returns

Promisethat resolves when the operation completes.

#::showItemInFolder(filePath)

PublicL32

Reveal a path in the operating system file browser.

Returns

Promisethat resolves when the request completes.

#::openPath(filePath)

PublicL44

Open a path with its operating system default application.

Returns

Promiseresolving to Electron’s result string.

#::openExternal(url)

PublicL56

Open a URL with its operating system default handler.

Returns

Promisethat 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)

ExtendedL43

Invoke callback for all current and future style elements.

ArgumentDescription
callback
Function
that 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

Disposableon which .dispose() can be called to cancel the subscription.

#::onDidAddStyleElement(callback)

ExtendedL63

Invoke callback when a style element is added.

ArgumentDescription
callback
Function
that 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

Disposableon which .dispose() can be called to cancel the subscription.

#::onDidRemoveStyleElement(callback)

ExtendedL77

Invoke callback when a style element is removed.

ArgumentDescription
callback
Function
that is called with style elements.
styleElement
An HTMLStyleElement instance.
Returns

Disposableon which .dispose() can be called to cancel the subscription.

#::onDidUpdateStyleElement(callback)

ExtendedL93

Invoke callback when an existing style element is updated.

ArgumentDescription
callback
Function
that 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

Disposableon which .dispose() can be called to cancel the subscription.

Reading Style Elements1

#::getStyleElements()

ExtendedL107

Get all loaded style elements.

Paths1

#::getUserStyleSheetPath()

ExtendedL217

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)

PublicL58

A helper method to easily launch and run a task once.

ArgumentDescription
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)

PublicL81

Creates a task. You should probably use {.once}

ArgumentDescription
taskPath
The String path to the CoffeeScript/JavaScript file that exports a single Function to execute.

#::start(...args)

PublicL150

Starts the task.

Throws an error if this task has already been terminated or if sending a message to the child process fails.

ArgumentDescription
...args
...*
Arguments passed to the function exported by the task script.
callbackoptional
Function
Called when the task completes.

#::send(message)

PublicL178

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.

ArgumentDescription
message
The message to send to the task.

#::on(eventName, callback)

PublicL211

Call a function when an event is emitted by the child process

ArgumentDescription
eventName
The String name of the event to handle.
callback
The Function to call when the event is emitted.
Returns

Disposablethat can be used to stop listening for the event.

#::terminate()

PublicL232

Forcefully stop the running task.

No more events are emitted once this method is called.

Returns

Booleanindicating whether the task was terminated.

#::cancel()

PublicL252

Cancel the running task and emit an event if it was canceled.

Returns

Booleanindicating 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)

PublicL89

Create a new buffer with the given params.

ArgumentDescription
params
Object
or 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)

PublicL170

Create a new buffer backed by the given file path.

ArgumentDescription
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
String
The file’s encoding.
shouldDestroyOnFileDeleteoptional
A Function that returns a Boolean indicating whether the buffer should be destroyed if its file is deleted.
Returns

Promisethat resolves with a TextBuffer instance.

#.loadSync(filePath, params)

PublicL199

Create a new buffer backed by the given file path. For better performance, use TextBuffer.load instead.

ArgumentDescription
filePath
The String file path.
params
An Object with the following properties:
encodingoptional
String
The file’s encoding.
shouldDestroyOnFileDeleteoptional
A Function that returns a Boolean indicating whether the buffer should be destroyed if its file is deleted.
Returns

TextBufferinstance.

#.deserialize(params)

asyncPublicL221

Restore a TextBuffer based on an earlier state created using the TextBuffer.serialize method.

ArgumentDescription
params
An Object returned from TextBuffer.serialize
Returns

Promisethat resolves with a TextBuffer instance.

Event Subscription18

#::onWillChange(callback)

PublicL354

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.

ArgumentDescription
callback
Function
to be called when the buffer changes.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChange(callback)

PublicL376

Invoke the given callback synchronously when a transaction finishes with a list of all the changes in the transaction.

ArgumentDescription
callback
Function
to be called when a transaction in which textual changes occurred is completed.
event
Object
with 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
Array
of Objects summarizing the aggregated changes that occurred during the transaction. See Working With Aggregated Changes in the description of the TextBuffer class for details.
oldRange
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

Disposableon which .dispose() can be called to unsubscribe.

#::onDidStopChanging(callback)

PublicL411

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.

ArgumentDescription
callback
Function
to be called when the buffer stops changing.
event
Object
with 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

Disposableon which .dispose() can be called to unsubscribe.

#::onDidConflict(callback)

PublicL425

Invoke the given callback when the in-memory contents of the buffer become in conflict with the contents of the file on disk.

ArgumentDescription
callback
Function
to be called when the buffer enters conflict.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeModified(callback)

PublicL439

Invoke the given callback if the value of #isModified changes.

ArgumentDescription
callback
Function
to be called when #isModified changes.
modified
Boolean
indicating whether the buffer is modified.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidUpdateMarkers(callback)

PublicL465

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 ::onDidChange observers are not notified.
  • TextBuffer::onDidChange observers are notified.
  • Marker::onDidChange observers are notified.
  • TextBuffer::onDidUpdateMarkers observers are notified.

Basically, this method gives you a way to take action after both a buffer change and all associated marker changes.

ArgumentDescription
callback
Function
to be called after markers are updated.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidCreateMarker(callback)

PublicL479

Invoke the given callback when a marker is created.

ArgumentDescription
callback
Function
to be called when a marker is created.
marker
Marker
that was created.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangePath(callback)

PublicL493

Invoke the given callback when the value of #getPath changes.

ArgumentDescription
callback
Function
to be called when the path changes.
path
String
representing the buffer’s current path on disk.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeEncoding(callback)

PublicL507

Invoke the given callback when the value of #getEncoding changes.

ArgumentDescription
callback
Function
to be called when the encoding changes.
encoding
String
character set encoding of the buffer.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onWillSave(callback)

PublicL520

Invoke the given callback before the buffer is saved to disk.

ArgumentDescription
callback
Function
to be called before the buffer is saved. If this function returns a Promise, then the buffer will not be saved until the promise resolves.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidSave(callback)

PublicL535

Invoke the given callback after the buffer is saved to disk.

ArgumentDescription
callback
Function
to be called after the buffer is saved.
event
Object
with the following keys:
path
The path to which the buffer was saved.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDelete(callback)

PublicL549

Invoke the given callback after the file backing the buffer is deleted.

ArgumentDescription
callback
Function
to be called after the buffer is deleted.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onWillReload(callback)

PublicL563

Invoke the given callback before the buffer is reloaded from the contents of its file on disk.

ArgumentDescription
callback
Function
to be called before the buffer is reloaded.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidReload(callback)

PublicL577

Invoke the given callback after the buffer is reloaded from the contents of its file on disk.

ArgumentDescription
callback
Function
to be called after the buffer is reloaded.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDestroy(callback)

PublicL590

Invoke the given callback when the buffer is destroyed.

ArgumentDescription
callback
Function
to be called when the buffer is destroyed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onWillThrowWatchError(callback)

PublicL607

Invoke the given callback when there is an error in watching the file.

ArgumentDescription
callback
Function
callback
errorObject
Object
error
Object
the error object
handle
Function
call this to indicate you have handled the error. The error will not be thrown if this function is called.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::getStoppedChangingDelay()

PublicL620

Get the number of milliseconds that will elapse without a change before #onDidStopChanging observers are invoked following a change.

Returns

Number

File Details9

#::isModified()

PublicL639

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()

PublicL665

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()

PublicL684

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()

PublicL698

Get the path of the associated file.

Returns

String

#::setPath(filePath)

PublicL710

Set the path for the buffer’s associated file.

ArgumentDescription
filePath
A String representing the new file path

#::setFile(file)

ExperimentalL730

Set a custom File object as the buffer’s backing store.

ArgumentDescription
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")

PublicL753

Sets the character set encoding for this buffer.

ArgumentDescription
encoding
The String encoding to use (default: ‘utf8’).

#::getEncoding()

PublicL776
Returns

Stringencoding of this buffer.

#::getUri()

PublicL796

Get the path of the associated file.

Returns

String

Reading Text12

#::isEmpty()

PublicL822

Determine whether the buffer is empty.

Returns

Boolean

#::getText()

PublicL835

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)

PublicL853

Get the text in a range.

ArgumentDescription
range
Returns

String

#::getLines()

PublicL865

Get the text of all lines in the buffer, without their line endings.

Returns

Arrayof Strings.

#::getLastLine()

PublicL878

Get the text of the last line of the buffer, without its line ending.

Returns

String

#::lineForRow(row)

PublicL892

Get the text of the line at the given 0-indexed row, without its line ending.

ArgumentDescription
row
A Number representing the row.
Returns

String

#::lineEndingForRow(row)

PublicL905

Get the line ending for the given 0-indexed row.

ArgumentDescription
row
A Number indicating the row.
Returns

StringThe 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)

PublicL919

Get the length of the line for the given 0-indexed row, without its line ending.

ArgumentDescription
row
A Number indicating the row.
Returns

Number

#::isRowBlank(row)

PublicL932

Determine if the given row contains only whitespace.

ArgumentDescription
row
A Number representing a 0-indexed row.
Returns

Boolean

#::previousNonBlankRow(startRow)

PublicL945

Given a row, find the first preceding row that’s not blank.

ArgumentDescription
startRow
A Number identifying the row to start checking at.
Returns

Numberor null if there’s no preceding non-blank row.

#::nextNonBlankRow(startRow)

PublicL963

Given a row, find the next row that’s not blank.

ArgumentDescription
startRow
A Number identifying the row to start checking at.
Returns

Numberor null if there’s no next non-blank row.

#::hasAstral()

ExtendedL979
Returns

BooleanWhether the buffer contains astral-plane Unicode characters encoded as surrogate pairs.

Mutating Text8

#::setText(text)

PublicL1001

Replace the entire contents of the buffer with the given text.

ArgumentDescription
text
A String
Returns

Rangespanning the new buffer contents.

#::setTextViaDiff(text)

PublicL1014

Replace the current buffer contents by applying a diff based on the given text.

ArgumentDescription
text
A String containing the new buffer contents.

#::setTextInRange(range, newText, options)

PublicL1097

Set the text in the given range.

ArgumentDescription
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

Rangeof the inserted text.

#::insert(position, text, options)

PublicL1154

Insert text at the given position.

ArgumentDescription
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

Rangeof the inserted text.

#::append(text, options)

PublicL1170

Append text to the end of the buffer.

ArgumentDescription
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

Rangeof the inserted text

#::delete(range)

PublicL1263

Delete the text in the given range.

ArgumentDescription
range
A Range in which to delete. The range is clipped before deleting.
Returns

Rangeempty Range starting at the start of deleted range.

#::deleteRow(row)

PublicL1276

Delete the line associated with a specified 0-indexed row.

ArgumentDescription
row
A Number representing the row to delete.
Returns

Rangeof the deleted text.

#::deleteRows(startRow, endRow)

PublicL1293

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.

ArgumentDescription
startRow
A Number representing the first row to delete.
endRow
A Number representing the last row to delete, inclusive.
Returns

Rangeof the deleted text.

Markers9

#::addMarkerLayer(options)

PublicL1343

Create a layer to contain a set of related markers.

ArgumentDescription
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

MarkerLayer

#::getMarkerLayer(id)

PublicL1358

Get a MarkerLayer by id.

ArgumentDescription
id
The id of the marker layer to retrieve.
Returns

MarkerLayeror undefined if no layer exists with the given id.

#::getDefaultMarkerLayer()

PublicL1373

Get the default MarkerLayer.

All Marker APIs not tied to an explicit layer interact with this default layer.

Returns

MarkerLayer

#::markRange(range, properties)

PublicL1393

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.

ArgumentDescription
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
Boolean
Creates the marker in a reversed orientation. (default: false)
invalidateoptional
String
Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility: * 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
Boolean
indicating whether insertions at the start or end of the marked range should be interpreted as happening outside the marker. Defaults to false, except when using the inside invalidation strategy or when the marker has no tail, in which case it defaults to true. Explicitly assigning this option overrides behavior in all circumstances.
Returns

Marker

#::markPosition(position, options)

PublicL1410

Create a Marker at the given position with no tail in the default marker layer.

ArgumentDescription
position
Point
or point-compatible Array
optionsoptional
An Object with the following keys:
invalidateoptional
String
Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility: * 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
Boolean
indicating whether insertions at the start or end of the marked range should be interpreted as happening outside the marker. Defaults to false, except when using the inside invalidation strategy or when the marker has no tail, in which case it defaults to true. Explicitly assigning this option overrides behavior in all circumstances.
Returns

Marker

#::getMarkers()

PublicL1422

Get all existing markers on the default marker layer.

Returns

Arrayof Markers.

#::getMarker(id)

PublicL1435

Get an existing marker by its id from the default marker layer.

ArgumentDescription
id
Number
id of the marker to retrieve
Returns

Marker

#::findMarkers(params)

PublicL1461

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.

ArgumentDescription
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

Arrayof Markers.

#::getMarkerCount()

PublicL1473

Get the number of markers in the default marker layer.

Returns

Number

History10

#::undo(options)

PublicL1533

Undo the last operation. If a transaction is in progress, aborts it.

ArgumentDescription
optionsoptional
Object
selectionsMarkerLayeroptional
Restore snapshot of selections marker layer to given selectionsMarkerLayer.
Returns

Booleanof whether or not a change was made.

#::redo(options)

PublicL1562

Redo the last operation

ArgumentDescription
optionsoptional
Object
selectionsMarkerLayeroptional
Restore snapshot of selections marker layer to given selectionsMarkerLayer.
Returns

Booleanof whether or not a change was made.

#::transact(options, fn)

PublicL1600

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.

ArgumentDescription
optionsoptional
Object
fn
A Function to call inside the transaction.
groupingIntervaloptional
Number
Milliseconds for which this transaction remains open for grouping. A subsequent transaction committed in that interval is merged with it for undo and redo.
selectionsMarkerLayeroptional
MarkerLayer
Skip snapshots for other selection marker layers.

#::abortTransaction()

PublicL1651

Abort the currently running transaction

Only intended to be called within the fn option to #transact

#::clearUndoStack()

PublicL1661

Clear the undo stack.

#::createCheckpoint(options)

PublicL1676

Create a pointer to the current state of the buffer for use with #revertToCheckpoint and #groupChangesSinceCheckpoint.

ArgumentDescription
optionsoptional
Object
selectionsMarkerLayeroptional
When provided, skip taking snapshot for other selections markerLayers except given one.
Returns

Numbercheckpoint id value.

#::revertToCheckpoint(checkpoint, options)

PublicL1699

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

ArgumentDescription
checkpoint
Number
id of the checkpoint to revert to.
optionsoptional
Object
selectionsMarkerLayeroptional
Restore snapshot of selections marker layer to given selectionsMarkerLayer.
Returns

BooleanWhether the operation succeeded.

#::groupChangesSinceCheckpoint(checkpoint, options)

PublicL1733

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.

ArgumentDescription
checkpoint
Number
id of the checkpoint to group changes since.
optionsoptional
Object
selectionsMarkerLayeroptional
When provided, skip taking snapshot for other selections markerLayers except given one.
Returns

Booleanindicating whether the operation succeeded.

#::groupLastChanges()

PublicL1751

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

Booleanindicating whether the operation succeeded.

#::getChangesSinceCheckpoint(checkpoint)

PublicL1773

If the given checkpoint is no longer present in the undo history, this method will return an empty Array.

  • oldRange The Range of the deleted text in the text as it existed when the checkpoint was created.
  • newRange: The Range of the inserted text in the current text.
  • oldText: A String representing the deleted text.
  • newText: A String representing the inserted text.
ArgumentDescription
checkpoint
Number
id of the checkpoint to get changes since.
Returns

Array<Object>Changes since the checkpoint. See Working With Aggregated Changes in the TextBuffer class description for the fields.

Search And Replace16

#::scan(regex, options = {}, iterator)

PublicL1809

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.

ArgumentDescription
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
Number
default 0; The number of lines before the matched line to include in the results object.
trailingContextLineCount
Number
default 0; The number of lines after the matched line to include in the results object.
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)

PublicL1838

Scan regular expression matches in the entire buffer in reverse order, calling the given iterator function on each match.

ArgumentDescription
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
Number
default 0; The number of lines before the matched line to include in the results object.
trailingContextLineCount
Number
default 0; The number of lines after the matched line to include in the results object.
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)

PublicL1868

Scan regular expression matches in a given range , calling the given iterator function on each match.

ArgumentDescription
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
Number
default 0; The number of lines before the matched line to include in the results object.
trailingContextLineCount
Number
default 0; The number of lines after the matched line to include in the results object.
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)

PublicL1933

Scan regular expression matches in a given range in reverse order, calling the given iterator function on each match.

ArgumentDescription
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
Number
default 0; The number of lines before the matched line to include in the results object.
trailingContextLineCount
Number
default 0; The number of lines after the matched line to include in the results object.
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)

PublicL1952

Replace all regular expression matches in the entire buffer.

ArgumentDescription
regex
A RegExp representing the matches to be replaced.
replacementText
A String representing the text to replace each match.
Returns

Numberrepresenting the number of replacements made.

#::find(regex)

ExperimentalL1979

Asynchronously search the buffer for a given regex.

ArgumentDescription
regex
A RegExp to search for.
Returns

Promisethat resolves with the first Range of text that matches the given regex.

#::findInRange(regex, range)

ExperimentalL1993

Asynchronously search a given range of the buffer for a given regex.

ArgumentDescription
regex
A RegExp to search for.
range
A Range to search within.
Returns

Promisethat resolves with the first Range of text that matches the given regex.

#::findSync(regex)

ExperimentalL2006

Search the buffer for a given regex.

ArgumentDescription
regex
A RegExp to search for.
Returns

Rangefirst Range of text that matches the given regex.

#::findInRangeSync(regex, range)

ExperimentalL2020

Search a given range of the buffer for a given regex.

ArgumentDescription
regex
A RegExp to search for.
range
A Range to search within.
Returns

Rangefirst Range of text that matches the given regex.

#::findAll(regex)

ExperimentalL2033

Asynchronously search the buffer for a given regex.

ArgumentDescription
regex
A RegExp to search for.
Returns

Promisethat resolves with an Array containing every Range of text that matches the given regex.

#::findAllInRange(regex, range)

ExperimentalL2047

Asynchronously search a given range of the buffer for a given regex.

ArgumentDescription
regex
A RegExp to search for.
range
A Range to search within.
Returns

Promisethat resolves with an Array containing every Range of text that matches the given regex.

#::findAllSync(regex)

ExperimentalL2060

Run an regexp search on the buffer

ArgumentDescription
regex
A RegExp to search for.
Returns

Arraycontaining every Range of text that matches the given regex.

#::findAllInRangeSync(regex, range)

ExperimentalL2074

Search a given range of the buffer for a given regex.

ArgumentDescription
regex
A RegExp to search for.
range
A Range to search within.
Returns

Arraycontaining every Range of text that matches the given regex.

#::findAndMarkAllInRangeSync(markerLayer, regex, range, options = {})

ExperimentalL2090

Search a given range of the buffer for a given regex. Store the matching ranges in the given marker layer.

ArgumentDescription
markerLayer
A MarkerLayer to populate.
regex
A RegExp to search for.
range
A Range to search within.
optionsoptional, default: {}
No description.
Returns

Arrayof Markers representing the matches.

#::findWordsWithSubsequence(query, extraWordCharacters, maxCount)

ExperimentalL2120

Find fuzzy match suggestions in the buffer

ArgumentDescription
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

Arraycontaining every SubsequenceMatch of text that matches the given query.

#::findWordsWithSubsequenceInRange(query, extraWordCharacters, maxCount, range)

ExperimentalL2136

Find fuzzy match suggestions in the buffer in a given range

ArgumentDescription
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

Arraycontaining every SubsequenceMatch of text that matches the given query in the given range.

Buffer Range Details12

#::getLineCount()

PublicL2164

Get the number of lines in the buffer.

Returns

Number

#::getLastRow()

PublicL2176

Get the last 0-indexed row in the buffer.

Returns

Number

#::getFirstPosition()

PublicL2188

Get the first position in the buffer, which is always [0, 0].

Returns

Point

#::getEndPosition()

PublicL2201

Get the maximal position in the buffer, where new text would be appended.

Returns

Point

#::getLength()

PublicL2211

Get the length of the buffer’s text.

#::getMaxCharacterIndex()

PublicL2223

Get the length of the buffer in characters.

Returns

Number

#::rangeForRow(row, includeNewline)

PublicL2237

Get the range for the given row

ArgumentDescription
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

Range

#::characterIndexForPosition(position)

PublicL2259

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.

ArgumentDescription
position
A Point or point-compatible Array.
Returns

Number

#::positionForCharacterIndex(offset)

PublicL2275

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.

ArgumentDescription
offset
A Number.
Returns

Point

#::clipRange(range)

PublicL2291

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).

ArgumentDescription
range
A Range or range-compatible Array to clip.
Returns

Rangegiven Range if it is already in bounds, or a new clipped Range if the given range is out-of-bounds.

#::clipPosition(position, options)

PublicL2314

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)

ArgumentDescription
position
A Point or point-compatible Array.
Returns

Pointnew Point if the given position is invalid, otherwise returns the given position.

Buffer Operations3

#::save()

PublicL2353

Save the buffer.

Returns

Promisethat resolves when the save has completed.

#::saveAs(filePath)

PublicL2366

Save the buffer at a specific path.

ArgumentDescription
filePath
The path to save at.
Returns

Promisethat resolves when the save has completed.

#::reload()

PublicL2447

Reload the file’s content from disk.

Returns

Promisethat resolves when the load is complete.

Display Layers3

#::getLanguageMode()

ExperimentalL2483

Get the language mode associated with this buffer.

Returns

Objectlanguage mode Object (See TextBuffer#setLanguageMode for its interface).

#::setLanguageMode(languageMode)

ExperimentalL2509

Set the language mode for this buffer.

ArgumentDescription
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
String
The deleted text
oldRange
The Range of the deleted text before the change took place.
newText
String
The 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)

ExperimentalL2538

Call the given callback whenever the buffer’s language mode changes.

ArgumentDescription
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

Disposablethat can be used to stop the callback from being called.

Private Utility Methods1

#::getFileWatchStartPromise()

ExperimentalL2941
Returns

Promisethat 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)

EssentialL909

Calls your callback when the buffer’s title has changed.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangePath(callback)

EssentialL922

Calls your callback when the buffer’s path, and therefore title, has changed.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChange(callback)

EssentialL940

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.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidStopChanging(callback)

EssentialL955

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.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeCursorPosition(callback)

EssentialL976

Calls your callback when a Cursor is moved. If there are multiple cursors, your callback will be called for each cursor.

ArgumentDescription
callback
Function
event
Object
oldBufferPosition
oldScreenPosition
newBufferPosition
newScreenPosition
textChanged
Boolean
cursor
Cursor
that triggered the event
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeSelectionRange(callback)

EssentialL995

Calls your callback when a selection’s screen range changes.

ArgumentDescription
callback
Function
event
Object
oldBufferRange
oldScreenRange
newBufferRange
newScreenRange
selection
Selection
that triggered the event
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeSoftWrapped(callback)

ExtendedL1008

Calls your callback when soft wrap was enabled or disabled.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeOvertypeMode(callback)

ExtendedL1023

Calls your callback when overtype (overwrite) mode is enabled or disabled for this editor.

ArgumentDescription
callback
Function
overtypeMode
Boolean
indicating the new state.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeEncoding(callback)

ExtendedL1036

Calls your callback when the buffer’s encoding has changed.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeGrammar(callback)

ExtendedL1052

Calls your callback when the grammar that interprets and colorizes the text has been changed. Immediately calls your callback with the current grammar.

ArgumentDescription
callback
Function
grammar
Grammar
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeGrammar(callback)

ExtendedL1068

Calls your callback when the grammar that interprets and colorizes the text has been changed.

ArgumentDescription
callback
Function
grammar
Grammar
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeModified(callback)

ExtendedL1083

Calls your callback when the result of #isModified changes.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidConflict(callback)

ExtendedL1097

Calls your callback when the buffer’s underlying file changes on disk at a moment when the result of #isModified is true.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDelete(callback)

ExtendedL1111

Calls your callback when the buffer’s underlying file is deleted on disk.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onWillInsertText(callback)

ExtendedL1127

Calls your callback before text has been inserted.

ArgumentDescription
callback
Function
event
event Object
text
String
text to be inserted
cancel
Function
Call to prevent the text from being inserted
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidInsertText(callback)

ExtendedL1142

Calls your callback after text has been inserted.

ArgumentDescription
callback
Function
event
event Object
text
String
text to be inserted
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidSave(callback)

EssentialL1157

Invoke the given callback after the buffer is saved to disk.

ArgumentDescription
callback
Function
to be called after the buffer is saved.
event
Object
with the following keys:
path
The path to which the buffer was saved.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDestroy(callback)

EssentialL1170

Invoke the given callback when the editor is destroyed.

ArgumentDescription
callback
Function
to be called when the editor is destroyed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeCursors(callback)

ExtendedL1185

Calls your callback when a Cursor is added to the editor. Immediately calls your callback for each existing cursor.

ArgumentDescription
callback
Function
cursor
Cursor
that was added
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidAddCursor(callback)

ExtendedL1200

Calls your callback when a Cursor is added to the editor.

ArgumentDescription
callback
Function
cursor
Cursor
that was added
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidRemoveCursor(callback)

ExtendedL1214

Calls your callback when a Cursor is removed from the editor.

ArgumentDescription
callback
Function
cursor
Cursor
that was removed
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeSelections(callback)

ExtendedL1229

Calls your callback when a Selection is added to the editor. Immediately calls your callback for each existing selection.

ArgumentDescription
callback
Function
selection
Selection
that was added
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidAddSelection(callback)

ExtendedL1244

Calls your callback when a Selection is added to the editor.

ArgumentDescription
callback
Function
selection
Selection
that was added
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidRemoveSelection(callback)

ExtendedL1258

Calls your callback when a Selection is removed from the editor.

ArgumentDescription
callback
Function
selection
Selection
that was removed
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeDecorations(callback)

ExtendedL1273

Calls your callback with each Decoration added to the editor. Calls your callback immediately for any existing decorations.

ArgumentDescription
callback
Function
decoration
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidAddDecoration(callback)

ExtendedL1287

Calls your callback when a Decoration is added to the editor.

ArgumentDescription
callback
Function
decoration
Decoration
that was added
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidRemoveDecoration(callback)

ExtendedL1301

Calls your callback when a Decoration is removed from the editor.

ArgumentDescription
callback
Function
decoration
Decoration
that was removed
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangePlaceholderText(callback)

ExtendedL1322

Calls your callback when the placeholder text is changed.

ArgumentDescription
callback
Function
placeholderText
String
new text
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeGutters(callback)

EssentialL1442

Calls your callback when a Gutter is added to the editor. Immediately calls your callback for each existing gutter.

ArgumentDescription
callback
Function
gutter
Gutter
that currently exists/was added.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidAddGutter(callback)

EssentialL1456

Calls your callback when a Gutter is added to the editor.

ArgumentDescription
callback
Function
gutter
Gutter
that was added.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidRemoveGutter(callback)

EssentialL1470

Calls your callback when a Gutter is removed from the editor.

ArgumentDescription
callback
Function
name
The name of the Gutter that was removed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

Buffer1

File Details9

#::getTitle()

EssentialL1522

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()

EssentialL1541

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,

  • filename when it is the only editing buffer with this file name.
  • filename — unique-dir-prefix when other buffers have this file name.
Returns

String

#::getPath()

EssentialL1637
Returns

Stringpath of this editor’s text buffer.

#::getEncoding()

ExtendedL1657
Returns

Stringcharacter set encoding of this editor’s text buffer.

#::setEncoding(encoding)

ExtendedL1670

Set the character set encoding to use in this editor’s text buffer.

ArgumentDescription
encoding
The String character set encoding name such as ‘utf8’

#::isModified()

EssentialL1680
Returns

Booleantrue if this editor has been modified.

#::isDeleted()

EssentialL1690
Returns

Booleantrue 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()

EssentialL1706

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

Booleantrue 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()

EssentialL1716
Returns

Booleantrue if this editor has no content.

File Operations2

#::saveAs(filePath)

EssentialL1746

Saves the editor’s text buffer as the given path.

See TextBuffer#saveAs for more details.

ArgumentDescription
filePath
A String path.

Reading Text9

#::getText()

EssentialL1785
Returns

Stringrepresenting the entire contents of the editor.

#::getTextInBufferRange(range)

EssentialL1798

Get the text in the given Range in buffer coordinates.

ArgumentDescription
range
A Range or range-compatible Array.
Returns

String

#::getLineCount()

EssentialL1808
Returns

Numberrepresenting the number of lines in the buffer.

#::getScreenLineCount()

EssentialL1818
Returns

Numberrepresenting the number of screen lines in the editor. This accounts for folds.

#::getLastBufferRow()

EssentialL1832
Returns

Numberrepresenting the last zero-indexed buffer row number of the editor.

#::getLastScreenRow()

EssentialL1842
Returns

Numberrepresenting the last zero-indexed screen row number of the editor.

#::lineTextForBufferRow(bufferRow)

EssentialL1853
ArgumentDescription
bufferRow
A Number representing a zero-indexed buffer row.
Returns

Stringrepresenting the contents of the line at the given buffer row.

#::lineTextForScreenRow(screenRow)

EssentialL1864
ArgumentDescription
screenRow
A Number representing a zero-indexed screen row.
Returns

Stringrepresenting the contents of the line at the given screen row.

#::getCurrentParagraphBufferRange()

EssentialL1985

Get the Range of the paragraph surrounding the most recently added cursor.

Returns

Range

Mutating Text25

#::setText(text, options = {})

EssentialL2003

Replaces the entire contents of the buffer with the given String.

ArgumentDescription
text
String
Text to replace the buffer contents with.
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor.

#::setTextInBufferRange(range, text, options = {})

EssentialL2022

Set the text in the given Range in buffer coordinates.

ArgumentDescription
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
Boolean
Must be true to modify a read-only editor. (default: false)
Returns

Rangeof the newly-inserted text.

#::insertText(text, options = {})

EssentialL2037

For each selection, replace the selected text with the given text.

ArgumentDescription
text
A String representing the text to insert.
optionsoptional
Returns

Rangewhen the text has been inserted. Returns a Boolean false when the text has not been inserted.

#::insertNewline(options = {})

EssentialL2074

For each selection, replace the selected text with a newline.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::delete(options = {})

EssentialL2088

For each selection, if the selection is empty, delete the character following the cursor. Otherwise delete the selected text.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::backspace(options = {})

EssentialL2103

For each selection, if the selection is empty, delete the character preceding the cursor. Otherwise delete the selected text.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::mutateSelectedText(fn, groupingInterval = 0)

ExtendedL2119

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.

ArgumentDescription
fn
A Function that will be called once for each Selection. The first argument will be a Selection and the second argument will be the Number index of that selection.
groupingIntervaloptional, default: 0
No description.

#::transpose(options = {})

ExtendedL2485

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.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::upperCase(options = {})

ExtendedL2512

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.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::lowerCase(options = {})

ExtendedL2529

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.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::toggleLineCommentsInSelection(options = {})

ExtendedL2545

Toggle line comments for rows intersecting selections.

If the current grammar doesn’t support comments, does nothing.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::collapseBlankLines(options = {})

ExtendedL2575

Reduce every run of blank lines in the buffer to a single blank line.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::collapseContentSpaces(options = {})

ExtendedL2598

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.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::insertNewlineBelow(options = {})

ExtendedL2618

For each cursor, insert a newline at beginning the following line.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::insertNewlineAbove(options = {})

ExtendedL2635

For each cursor, insert a newline at the end of the preceding line.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::deleteToBeginningOfWord(options = {})

ExtendedL2668

For each selection, if the selection is empty, delete all characters of the containing word that precede the cursor. Otherwise delete the selected text.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::deleteToPreviousWordBoundary(options = {})

ExtendedL2683

Similar to #deleteToBeginningOfWord, but deletes only back to the previous word boundary.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::deleteToNextWordBoundary(options = {})

ExtendedL2698

Similar to #deleteToEndOfWord, but deletes only up to the next word boundary.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::deleteToBeginningOfSubword(options = {})

ExtendedL2714

For each selection, if the selection is empty, delete all characters of the containing subword following the cursor. Otherwise delete the selected text.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::deleteToEndOfSubword(options = {})

ExtendedL2730

For each selection, if the selection is empty, delete all characters of the containing subword following the cursor. Otherwise delete the selected text.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::deleteToBeginningOfLine(options = {})

ExtendedL2746

For each selection, if the selection is empty, delete all characters of the containing line that precede the cursor. Otherwise delete the selected text.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::deleteToEndOfLine(options = {})

ExtendedL2763

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.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::deleteToNextLineContent(options = {})

ExtendedL2781

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.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::deleteToEndOfWord(options = {})

ExtendedL2841

For each selection, if the selection is empty, delete all characters of the containing word following the cursor. Otherwise delete the selected text.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::deleteLine(options = {})

ExtendedL2855

Delete all lines intersecting selections.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

History7

#::undo(options = {})

EssentialL2897

Undo the last change.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::redo(options = {})

EssentialL2914

Redo the last change.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor. (default: false)

#::transact(groupingInterval, fn)

ExtendedL2936

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.

ArgumentDescription
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()

ExtendedL2953

Abort an open transaction, undoing any operations performed so far within the transaction.

#::revertToCheckpoint(checkpoint)

ExtendedL2986

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

ArgumentDescription
checkpoint
The checkpoint to revert to.
Returns

BooleanWhether the operation succeeded.

#::groupChangesSinceCheckpoint(checkpoint)

ExtendedL3003

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.

ArgumentDescription
checkpoint
The checkpoint from which to group changes.
Returns

Booleanindicating whether the operation succeeded.

TextEditor Coordinates8

#::screenPositionForBufferPosition(bufferPosition, options)

EssentialL3027

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.

ArgumentDescription
bufferPosition
A Point or Array of [row, column].
optionsoptional
An options object for #clipScreenPosition.
Returns

Point

#::bufferPositionForScreenPosition(screenPosition, options)

EssentialL3043

Convert a position in screen-coordinates to buffer-coordinates.

The position is clipped via #clipScreenPosition prior to the conversion.

ArgumentDescription
screenPosition
Point|Array<Number>
The screen position to convert.
optionsoptional
Object
Options for #clipScreenPosition.
Returns

Point

#::screenRangeForBufferRange(bufferRange, options)

EssentialL3056

Convert a range in buffer-coordinates to screen-coordinates.

ArgumentDescription
bufferRange
Range
in buffer coordinates to translate into screen coordinates.
Returns

Range

#::bufferRangeForScreenRange(screenRange)

EssentialL3072

Convert a range in screen-coordinates to buffer-coordinates.

ArgumentDescription
screenRange
Range
in screen coordinates to translate into buffer coordinates.
Returns

Range

#::clipBufferPosition(bufferPosition)

ExtendedL3102

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]`
ArgumentDescription
bufferPosition
The Point representing the position to clip.
Returns

Point

#::clipBufferRange(range)

ExtendedL3116

Clip the start and end of the given range to valid positions in the buffer. See #clipBufferPosition for more information.

ArgumentDescription
range
The Range to clip.
Returns

Range

#::clipScreenPosition(screenPosition, options)

ExtendedL3145

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]`
ArgumentDescription
screenPosition
The Point representing the position to clip.
optionsoptional
Object
clipDirection
String
If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'.
Returns

PointThe clipped screen position.

#::clipScreenRange(screenRange, options)

ExtendedL3160

Clip the start and end of the given range to valid positions on screen. See #clipScreenPosition for more information.

ArgumentDescription
screenRange
The Range to clip.
optionsoptional
See #clipScreenPosition options.
Returns

Range

Decorations7

#::decorateMarker(marker, decorationParams)

EssentialL3236

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 class to the lines overlapping the rows spanned by the marker.
  • line-number: Adds the given CSS class to the line numbers overlapping the rows spanned by the marker
  • text: Injects spans into all text overlapping the marked range, then adds the given class or style to these spans. Use this to manipulate the foreground color or styling of text in a range.
  • highlight: Creates an absolutely-positioned .highlight div 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 the position property.
  • gutter: Tracks a DisplayMarker in a Gutter. Gutter decorations are created by calling Gutter#decorateMarker on the desired Gutter instance.
  • block: Positions the view associated with the given item before or after the row of the given DisplayMarker, depending on the position property. Block decorations at the same screen row are ordered by their order property.
  • 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.
ArgumentDescription
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

Decorationcreated Decoration object.

#::decorateMarkerLayer(markerLayer, decorationParams)

EssentialL3252

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.

ArgumentDescription
markerLayer
decorationParams
The same parameters that are passed to TextEditor#decorateMarker, except the type cannot be overlay or gutter.
Returns

LayerDecoration

#::getDecorations(propertyFilter)

ExtendedL3284

Get all decorations.

ArgumentDescription
propertyFilteroptional
An Object containing key value pairs that the returned decorations’ properties must match.
Returns

Arrayof Decorations.

#::getLineDecorations(propertyFilter)

ExtendedL3297

Get all decorations of type ‘line’.

ArgumentDescription
propertyFilteroptional
An Object containing key value pairs that the returned decorations’ properties must match.
Returns

Arrayof Decorations.

#::getLineNumberDecorations(propertyFilter)

ExtendedL3310

Get all decorations of type ‘line-number’.

ArgumentDescription
propertyFilteroptional
An Object containing key value pairs that the returned decorations’ properties must match.
Returns

Arrayof Decorations.

#::getHighlightDecorations(propertyFilter)

ExtendedL3323

Get all decorations of type ‘highlight’.

ArgumentDescription
propertyFilteroptional
An Object containing key value pairs that the returned decorations’ properties must match.
Returns

Arrayof Decorations.

#::getOverlayDecorations(propertyFilter)

ExtendedL3336

Get all decorations of type ‘overlay’.

ArgumentDescription
propertyFilteroptional
An Object containing key value pairs that the returned decorations’ properties must match.
Returns

Arrayof Decorations.

Markers11

#::markBufferRange(bufferRange, options)

EssentialL3360

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.

ArgumentDescription
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
Boolean
Whether to store this marker’s range before and after each change in the undo history. This allows the marker’s position to be restored more accurately for certain undo/redo operations, but uses more time and memory. (default: false)
reversedoptional
Boolean
Creates the marker in a reversed orientation. (default: false)
invalidateoptional
String
Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility: * 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

DisplayMarker

#::markScreenRange(screenRange, options)

EssentialL3380

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.

ArgumentDescription
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
Boolean
Whether to store this marker’s range before and after each change in the undo history. This allows the marker’s position to be restored more accurately for certain undo/redo operations, but uses more time and memory. (default: false)
reversedoptional
Boolean
Creates the marker in a reversed orientation. (default: false)
invalidateoptional
String
Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility: * 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

DisplayMarker

#::markBufferPosition(bufferPosition, options)

EssentialL3397

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.

ArgumentDescription
bufferPosition
A Point or point-compatible Array
optionsoptional
An Object with the following keys:
invalidateoptional
String
Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility: * 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

DisplayMarker

#::markScreenPosition(screenPosition, options)

EssentialL3415

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.

ArgumentDescription
screenPosition
A Point or point-compatible Array
optionsoptional
An Object with the following keys:
invalidateoptional
String
Determines the rules by which changes to the buffer invalidate the marker. (default: ‘overlap’) It can be any of the following strategies, in order of fragility: * 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
String
If 'backward', clips before an invalid position; if 'forward', clips after it; if 'closest', uses the nearest valid position. Defaults to 'closest'.
Returns

DisplayMarkerThe new marker.

#::findMarkers(params)

EssentialL3438

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.

ArgumentDescription
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
Only include markers containing this Point or Array of [row, column] in buffer coordinates.
Returns

Arrayof DisplayMarkers

#::getMarker(id)

ExtendedL3451

Get the DisplayMarker on the default layer for the given marker id.

ArgumentDescription
id
Number
id of the marker

#::getMarkerCount()

ExtendedL3474

Get the number of markers in the default marker layer.

Returns

Number

#::addMarkerLayer(options)

EssentialL3494

Create a marker layer to group related markers.

ArgumentDescription
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

DisplayMarkerLayer

#::getMarkerLayer(id)

EssentialL3507

Get a DisplayMarkerLayer by id.

ArgumentDescription
id
The id of the marker layer to retrieve.
Returns

DisplayMarkerLayeror undefined if no layer exists with the given id.

Cursors34

#::getCursorBufferPosition()

EssentialL3539

Get the position of the most recently added cursor in buffer coordinates.

Returns

Point

#::getCursorBufferPositions()

EssentialL3551

Get the position of all the cursor positions in buffer coordinates.

Returns

Arrayof Points in the order they were added

#::setCursorBufferPosition(position, options)

EssentialL3567

Move the cursor to the given position in buffer coordinates.

If there are multiple cursors, they will be consolidated to a single cursor.

ArgumentDescription
position
A Point or Array of [row, column]
optionsoptional
An Object containing the following keys:
autoscroll
Determines whether the editor scrolls to the new cursor’s position. Defaults to true.

#::getCursorAtScreenPosition(position)

EssentialL3580

Get a Cursor at given screen coordinates Point

ArgumentDescription
position
A Point or Array of [row, column]
Returns

Cursor|undefinedfirst matched Cursor or undefined

#::getCursorScreenPosition()

EssentialL3596

Get the position of the most recently added cursor in screen coordinates.

Returns

Point

#::getCursorScreenPositions()

EssentialL3608

Get the position of all the cursor positions in screen coordinates.

Returns

Arrayof Points in the order the cursors were added

#::setCursorScreenPosition(position, options)

EssentialL3624

Move the cursor to the given position in screen coordinates.

If there are multiple cursors, they will be consolidated to a single cursor.

ArgumentDescription
position
A Point or Array of [row, column]
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)

EssentialL3637

Add a cursor at the given position in buffer coordinates.

ArgumentDescription
bufferPosition
A Point or Array of [row, column]
Returns

Cursor

#::addCursorAtScreenPosition(screenPosition, options)

EssentialL3654

Add a cursor at the position in screen coordinates.

ArgumentDescription
screenPosition
A Point or Array of [row, column]
Returns

Cursor

#::hasMultipleCursors()

EssentialL3668
Returns

Booleanindicating whether or not there are multiple cursors.

#::moveUp(lineCount)

EssentialL3680

Move every cursor up one row in screen coordinates.

ArgumentDescription
lineCountoptional
Number
number of lines to move

#::moveDown(lineCount)

EssentialL3692

Move every cursor down one row in screen coordinates.

ArgumentDescription
lineCountoptional
Number
number of lines to move

#::moveLeft(columnCount)

EssentialL3704

Move every cursor left one column.

ArgumentDescription
columnCountoptional
Number
number of columns to move (default: 1)

#::moveRight(columnCount)

EssentialL3718

Move every cursor right one column.

ArgumentDescription
columnCountoptional
Number
number of columns to move (default: 1)

#::moveToBeginningOfLine()

EssentialL3730

Move every cursor to the beginning of its line in buffer coordinates.

#::moveToBeginningOfScreenLine()

EssentialL3740

Move every cursor to the beginning of its line in screen coordinates.

#::moveToFirstCharacterOfLine()

EssentialL3750

Move every cursor to the first non-whitespace character of its line.

#::moveToEndOfLine()

EssentialL3760

Move every cursor to the end of its line in buffer coordinates.

#::moveToEndOfScreenLine()

EssentialL3770

Move every cursor to the end of its line in screen coordinates.

#::moveToBeginningOfWord()

EssentialL3780

Move every cursor to the beginning of its surrounding word.

#::moveToEndOfWord()

EssentialL3790

Move every cursor to the end of its surrounding word.

#::moveToTop()

ExtendedL3804

Move every cursor to the top of the buffer.

If there are multiple cursors, they will be merged into a single cursor.

#::moveToBottom()

ExtendedL3816

Move every cursor to the bottom of the buffer.

If there are multiple cursors, they will be merged into a single cursor.

#::moveToBeginningOfNextWord()

ExtendedL3826

Move every cursor to the beginning of the next word.

#::moveToPreviousWordBoundary()

ExtendedL3836

Move every cursor to the previous word boundary.

#::moveToNextWordBoundary()

ExtendedL3846

Move every cursor to the next word boundary.

#::moveToPreviousSubwordBoundary()

ExtendedL3856

Move every cursor to the previous subword boundary.

#::moveToNextSubwordBoundary()

ExtendedL3866

Move every cursor to the next subword boundary.

#::moveToBeginningOfNextParagraph()

ExtendedL3876

Move every cursor to the beginning of the next paragraph.

#::moveToBeginningOfPreviousParagraph()

ExtendedL3886

Move every cursor to the beginning of the previous paragraph.

#::getCursorsOrderedByBufferPosition()

ExtendedL3932

Get all Cursors, ordered by their position in the buffer instead of the order in which they were added.

Returns

Arrayof Selections.

Selections42

#::getSelectedText()

EssentialL3994

Get the selected text of the most recently added selection.

Returns

String

#::getSelectedBufferRange()

EssentialL4007

Get the Range of the most recently added selection in buffer coordinates.

Returns

Range

#::getSelectedBufferRanges()

EssentialL4021

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

Arrayof Ranges.

#::setSelectedBufferRange(bufferRange, options)

EssentialL4037

Set the selected range in buffer coordinates. If there are multiple selections, they are reduced to a single selection with the given range.

ArgumentDescription
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 = {})

EssentialL4053

Set the selected ranges in buffer coordinates. If there are multiple selections, they are replaced by new selections with the given ranges.

ArgumentDescription
bufferRanges
An Array of Ranges or range-compatible Arrays.
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()

EssentialL4083

Get the Range of the most recently added selection in screen coordinates.

Returns

Range

#::getSelectedScreenRanges()

EssentialL4097

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

Arrayof Ranges.

#::setSelectedScreenRange(screenRange, options)

EssentialL4112

Set the selected range in screen coordinates. If there are multiple selections, they are reduced to a single selection with the given range.

ArgumentDescription
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 = {})

EssentialL4130

Set the selected ranges in screen coordinates. If there are multiple selections, they are replaced by new selections with the given ranges.

ArgumentDescription
screenRanges
An Array of Ranges or range-compatible Arrays.
optionsoptional
An Object of options:
reversed
A Boolean indicating whether to create the selection in a reversed orientation.

#::addSelectionForBufferRange(bufferRange, options = {})

EssentialL4163

Add a selection for the given range in buffer coordinates.

ArgumentDescription
bufferRange
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

Selectionadded Selection.

#::addSelectionForScreenRange(screenRange, options = {})

EssentialL4191

Add a selection for the given range in screen coordinates.

ArgumentDescription
screenRange
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

Selectionadded Selection.

#::selectToBufferPosition(position)

EssentialL4206

Select from the current cursor position to the given position in buffer coordinates.

This method may merge selections that end up intersecting.

ArgumentDescription
position
An instance of Point, with a given row and column.

#::selectToScreenPosition(position, options)

EssentialL4225

Select from the current cursor position to the given position in screen coordinates.

This method may merge selections that end up intersecting.

ArgumentDescription
position
An instance of Point, with a given row and column.

#::selectUp(rowCount)

EssentialL4247

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.

ArgumentDescription
rowCountoptional
Number
number of rows to select (default: 1)

#::selectDown(rowCount)

EssentialL4263

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.

ArgumentDescription
rowCountoptional
Number
number of rows to select (default: 1)

#::selectLeft(columnCount)

EssentialL4279

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.

ArgumentDescription
columnCountoptional
Number
number of columns to select (default: 1)

#::selectRight(columnCount)

EssentialL4295

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.

ArgumentDescription
columnCountoptional
Number
number of columns to select (default: 1)

#::selectToTop()

EssentialL4308

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()

EssentialL4321

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()

EssentialL4333

Select all text in the buffer.

This method merges multiple selections into a single selection.

#::selectToBeginningOfLine()

EssentialL4346

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()

EssentialL4361

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()

EssentialL4374

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()

EssentialL4387

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()

EssentialL4400

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()

ExtendedL4413

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()

ExtendedL4428

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()

EssentialL4440

For each cursor, select the containing line.

This method merges selections on successive lines.

#::selectWordsContainingCursors()

EssentialL4450

Select the word surrounding each cursor.

#::selectSubwordsContainingCursors()

ExtendedL4460

Select the subword surrounding each cursor.

#::selectToPreviousWordBoundary()

ExtendedL4475

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()

ExtendedL4488

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()

ExtendedL4501

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()

ExtendedL4514

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()

ExtendedL4529

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()

ExtendedL4542

For each selection, select the syntax node that contains that selection.

#::selectMarker(marker)

ExtendedL4584

Select the range of the given marker if it is valid.

ArgumentDescription
marker
Returns

Range|undefinedselected Range or undefined if the marker is invalid.

#::getSelectionsOrderedByBufferPosition()

ExtendedL4634

Get all Selections, ordered by their position in the buffer instead of the order in which they were added.

Returns

Arrayof Selections.

#::selectionIntersectsBufferRange(bufferRange)

ExtendedL4648

Determine if a given range in buffer coordinates intersects a selection.

ArgumentDescription
bufferRange
A Range or range-compatible Array.
Returns

Boolean

Searching and Replacing3

#::scan(regex, options = {}, iterator)

EssentialL4854

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.

ArgumentDescription
regex
A RegExp to search for.
optionsoptional
Object
iterator
A Function that’s called on each match
leadingContextLineCount
Number
default 0; The number of lines before the matched line to include in the results object.
trailingContextLineCount
Number
default 0; The number of lines after the matched line to include in the results object.
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)

EssentialL4879

Scan regular expression matches in a given range, calling the given iterator function on each match.

ArgumentDescription
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)

EssentialL4899

Scan regular expression matches in a given range in reverse order, calling the given iterator function on each match.

ArgumentDescription
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()

EssentialL4913
Returns

Booleanindicating whether softTabs are enabled for this editor.

#::setSoftTabs(softTabs)

EssentialL4925

Enable or disable soft tabs for this editor.

ArgumentDescription
softTabs
A Boolean

#::toggleSoftTabs()

EssentialL4941

Toggle soft tabs for this editor

#::getTabLength()

EssentialL4953

Get the on-screen length of tab characters.

Returns

Number

#::setTabLength(tabLength)

EssentialL4966

Set the on-screen length of tab characters. Setting this to a Number This will override the language.tabLength setting.

ArgumentDescription
tabLength
Number
length of a single tab. Setting to null will fallback to using the language.tabLength config setting

#::usesSoftTabs()

ExtendedL4994

Determine if the buffer uses hard or soft tabs.

Returns

Boolean|undefinedtrue for leading spaces, false for a leading hard tab (\t), or undefined when no non-comment line has leading whitespace.

#::getTabText()

ExtendedL5020

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()

EssentialL5045

Determine whether lines in this editor are soft-wrapped.

Returns

Boolean

#::setSoftWrapped(softWrapped)

EssentialL5058

Enable or disable soft wrapping for this editor.

ArgumentDescription
softWrapped
A Boolean
Returns

Boolean

#::toggleSoftWrapped()

EssentialL5075

Toggle soft wrapping for this editor

Returns

Boolean

#::isOvertypeMode()

EssentialL5089

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)

EssentialL5102

Enable or disable overtype (overwrite) mode for this editor.

ArgumentDescription
overtypeMode
A Boolean.
Returns

Boolean

#::toggleOvertypeMode()

EssentialL5119

Toggle overtype (overwrite) mode for this editor.

Returns

Boolean

#::applyOvertype()

ExtendedL5135

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()

EssentialL5150

Gets the column at which column will soft wrap

Indentation6

#::indentationForBufferRow(bufferRow)

EssentialL5180

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.

ArgumentDescription
bufferRow
A Number indicating the buffer row.
Returns

Number

#::setIndentationForBufferRow(bufferRow, newLevel, { preserveLeadingWhitespace } = {})

EssentialL5201

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.

ArgumentDescription
bufferRow
A Number indicating the buffer row.
newLevel
A Number indicating the new indentation level.
optionsoptional
Object
Indentation options.
preserveLeadingWhitespaceoptional, default: false
Boolean
Preserve whitespace already at the beginning of the line.

#::indentSelectedRows(options = {})

ExtendedL5227

Indent rows intersecting selections by one level.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor.

#::outdentSelectedRows(options = {})

ExtendedL5241

Outdent rows intersecting selections by one level.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor.

#::indentLevelForLine(line)

ExtendedL5260

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.

ArgumentDescription
line
A String representing a line of text.
Returns

Number

#::autoIndentSelectedRows(options = {})

ExtendedL5286

Indent rows intersecting selections based on the grammar’s suggested indent level.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor.

Grammars2

#::getGrammar()

EssentialL5326

Get the current Grammar of this editor.

#::onDidTokenize(callback)

ExperimentalL5348

Get a notification when async tokenization is completed.

Managing Syntax Scopes6

#::getRootScopeDescriptor()

EssentialL5362
Returns

ScopeDescriptorthat 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)

EssentialL5381

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"]

ArgumentDescription
bufferPosition
A Point or Array of [row, column].
Returns

ScopeDescriptor

#::syntaxTreeScopeDescriptorForBufferPosition(bufferPosition)

EssentialL5407

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

ArgumentDescription
bufferPosition
A Point or Array of [row, column].
Returns

ScopeDescriptor

#::bufferRangeForScopeAtCursor(scopeSelector)

ExtendedL5427

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").

ArgumentDescription
scopeSelector
String
selector. e.g. '.source.ruby'
Returns

Range

#::bufferRangeForScopeAtPosition(scopeSelector, bufferPosition)

ExtendedL5445

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()).

ArgumentDescription
scopeSelector
String
selector. e.g. '.source.ruby'
bufferPosition
A Point or Array of [row, column]
Returns

Range

#::isBufferRowCommented(bufferRow)

ExtendedL5457

Determine if the given row is entirely a comment

Clipboard Operations5

#::copySelectedText(clipboard = this.constructor.clipboard)

EssentialL5492

For each selection, copy the selected text.

ArgumentDescription
clipboardoptional, default: this.constructor.clipboard
No description.

#::cutSelectedText(options = {})

EssentialL5531

For each selection, cut the selected text.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor.

#::pasteText(options = {})

EssentialL5559

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.

ArgumentDescription
optionsoptional

#::cutToEndOfLine(options = {})

EssentialL5658

For each selection, if the selection is empty, cut all characters of the containing screen line following the cursor. Otherwise cut the selected text.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor.

#::cutToEndOfBufferLine(options = {})

EssentialL5678

For each selection, if the selection is empty, cut all characters of the containing buffer line following the cursor. Otherwise cut the selected text.

ArgumentDescription
optionsoptional
Object
bypassReadOnlyoptional
Boolean
Must be true to modify a read-only editor.

Folds14

#::foldCurrentRow()

EssentialL5701

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()

EssentialL5716

Unfold the most recent cursor’s row by one level.

#::foldBufferRow(bufferRow)

EssentialL5733

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.

ArgumentDescription
bufferRow
A Number.

#::unfoldBufferRow(bufferRow)

EssentialL5766

Unfold all folds containing the given row in buffer coordinates.

ArgumentDescription
bufferRow
A Number

#::foldSelectedLines()

ExtendedL5777

For each selection, fold the rows it intersects.

#::foldAll()

ExtendedL5789

Fold all foldable lines.

#::unfoldAll()

ExtendedL5805

Unfold all existing folds.

#::foldAllAtIndentLevel(level)

ExtendedL5819

Fold all foldable lines at the given indent level.

ArgumentDescription
level
A Number starting at 0.

#::isFoldableAtBufferRow(bufferRow)

ExtendedL5841

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.

ArgumentDescription
bufferRow
A Number
Returns

Boolean

#::isFoldableAtScreenRow(screenRow)

ExtendedL5857

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.

ArgumentDescription
screenRow
A Number
Returns

Boolean

#::toggleFoldAtBufferRow(bufferRow)

ExtendedL5868

Fold the given buffer row if it isn’t currently folded, and unfold it otherwise.

#::isFoldedAtCursorRow()

ExtendedL5884

Determine whether the most recently added cursor’s row is folded.

Returns

Boolean

#::isFoldedAtBufferRow(bufferRow)

ExtendedL5897

Determine whether the given row in buffer coordinates is folded.

ArgumentDescription
bufferRow
A Number
Returns

Boolean

#::isFoldedAtScreenRow(screenRow)

ExtendedL5914

Determine whether the given row in screen coordinates is folded.

ArgumentDescription
screenRow
A Number
Returns

Boolean

Gutters3

#::addGutter(options)

EssentialL5978

Add a custom Gutter.

ArgumentDescription
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
Boolean
specifying whether the gutter is visible initially after being created. (default: true)
typeoptional
String
specifying the type of gutter to create. 'decorated' gutters are useful as a destination for decorations created with Gutter#decorateMarker. 'line-number' gutters.
classoptional
String
added to the CSS classnames of the gutter’s root DOM element.
labelFnoptional
Function
called by a 'line-number' gutter to generate the label for each line number element. Should return a String that will be used to label the corresponding line.
lineData
an Object containing information about each line to label.
bufferRow
Number
indicating the zero-indexed buffer index of this line.
screenRow
Number
indicating the zero-indexed screen index.
foldable
Boolean
that is true if a fold may be created here.
softWrapped
Boolean
if this screen row is the soft-wrapped continuation of the same buffer row.
maxDigits
Number
the maximum number of digits necessary to represent any known screen row.
onMouseDownoptional
Function
to be called when a mousedown event is received by a line-number element within this type: 'line-number' Gutter. If unspecified, the default behavior is to select the clicked buffer row.
lineData
an Object containing information about the line that’s being clicked.
bufferRow
Number
of the originating line element
screenRow
Number
onMouseMoveoptional
Function
to be called when a mousemove event occurs on a line-number element within within this type: 'line-number' Gutter.
lineData
an Object containing information about the line that’s being clicked.
bufferRow
Number
of the originating line element
screenRow
Number
Returns

Gutternewly-created Gutter.

#::getGutters()

EssentialL5990

Get this editor’s gutters.

Returns

Arrayof Gutters.

#::gutterWithName(name)

EssentialL6006

Get the gutter with the given name.

Returns

Gutteror null if no gutter exists for the given name.

Scrolling the TextEditor4

#::scrollToCursorPosition(options)

EssentialL6025

Scroll the editor to reveal the most recently added cursor if it is off-screen.

ArgumentDescription
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)

EssentialL6044

Scrolls the editor to the given buffer position.

ArgumentDescription
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)

EssentialL6062

Scrolls the editor to the given screen position.

ArgumentDescription
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 = {})

ExtendedL6079

Scrolls the editor to the given screen range.

ArgumentDescription
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()

ExperimentalL6126

Is auto-indentation enabled for this editor?

Returns

Boolean

#::shouldAutoIndentOnPaste()

ExperimentalL6138

Is auto-indentation on paste enabled for this editor?

Returns

Boolean

#::getScrollPastEnd()

ExperimentalL6150

Does this editor allow scrolling past the last line?

Returns

Boolean

#::getScrollSensitivity()

ExperimentalL6167

How fast does the editor scroll in response to mouse wheel movements?

Returns

Numberpositive Number.

#::getSmoothScrolling()

ExperimentalL6179

Are mouse wheel and scroll command movements animated?

Returns

Boolean

#::getWheelSmoothness()

ExperimentalL6193

How gradually does the editor glide toward the target position when scrolling with the mouse wheel?

Returns

Numberpositive Number.

#::getCommandSmoothness()

ExperimentalL6207

How gradually does the editor glide when scrolling via the scroll commands?

Returns

Numberpositive Number.

#::getAltWheelMultiplier()

ExperimentalL6221

Speed multiplier applied to wheel scrolling while holding alt.

Returns

Numberpositive Number.

#::getScrollCommandDistance()

ExperimentalL6235

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

Numberpositive Number.

#::getSoftWrapDebounceInterval()

ExperimentalL6248

How long (in milliseconds) to wait for the editor width to settle before re-wrapping soft-wrapped lines. 0 re-wraps immediately.

Returns

Numbernon-negative Number.

#::doesShowLineNumbers()

ExperimentalL6260

Are line numbers enabled for this editor?

Returns

Boolean

#::getUndoGroupingInterval()

ExperimentalL6273

Get the time interval within which text editing operations are grouped together in the editor’s undo history.

Returns

Numbertime interval Number in milliseconds.

#::getNonWordCharacters(position)

ExperimentalL6286

Get the characters that are not considered part of words, for the purpose of word-based cursor movements.

Returns

Stringcontaining the non-word characters.

TextEditor Rendering2

#::getPlaceholderText()

EssentialL6351

Retrieves the greyed out placeholder of a mini editor.

Returns

String

#::setPlaceholderText(placeholderText)

EssentialL6364

Set the greyed out placeholder of a mini editor. Placeholder text will be displayed when the editor has no content.

ArgumentDescription
placeholderText
String
text that is displayed when the editor has no content.

Language Mode Delegated Methods1

#::getCommentDelimitersForBufferPosition(point)

PublicL6835

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, a String representing a line comment delimiter. (If undefined, there is no known line comment delimiter for the given buffer position.)

  • block: If present, a two-item Array containing Strings representing the starting and ending block comment delimiters. (If undefined, there are no known block comment delimiters for the given buffer position.)

Returns

ObjectInformation about the appropriate comment delimiters at the buffer position.

Essential API

TextEditorElementsrc/text-editor-element.js:4

Methods8

#::getNextUpdatePromise()

ExtendedL69

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()

ExtendedL167

get the width of an x character displayed in this element.

Returns

Numberof pixels.

#::scrollToTop()

EssentialL233

Scrolls the editor to the top.

#::scrollToBottom()

EssentialL243

Scrolls the editor to the bottom.

#::pixelPositionForBufferPosition(bufferPosition)

ExtendedL266

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.

ArgumentDescription
bufferPosition
A Point-like object that represents a buffer position.
Returns

Objectwith two values: top and left, representing the pixel position.

#::pixelPositionForScreenPosition(screenPosition)

ExtendedL285

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.

ArgumentDescription
screenPosition
A Point-like object that represents a buffer position.
Returns

Objectwith two values: top and left, representing the pixel position.

#::invalidateBlockDecorationDimensions(blockDecoration)

ExperimentalL352

Invalidate the passed block Decoration's dimensions, forcing them to be recalculated and the surrounding content to be adjusted on the next animation frame.

ArgumentDescription
blockDecoration
Decoration
The block decoration whose dimensions should be recalculated.

#::pinScrollAnchorToBlockDecoration(blockDecoration)

ExperimentalL373

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.

ArgumentDescription
blockDecoration
Decoration
the decoration being interactively sized
Returns

Disposableends 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" } = {})

EssentialL142

Register a TextEditor, so that features written against the registry reach it.

Throws a TypeError if role is not one of those three.

ArgumentDescription
editor
The TextEditor to register.
optionsoptional
Object
Registration options.
roleoptional, default: "document"
"document"|"fragment"|"background"
The editor role. See TextEditorRegistry for the behavior of each.
Returns

Disposableon 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)

PublicL181

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.

ArgumentDescription
editor
The TextEditor to remove.
Returns

Booleantrue if the editor was registered, false if it was not.

#::roleFor(editor)

PublicL202

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.

ArgumentDescription
editor
The TextEditor to look up.
Returns

Stringrole, or null if the editor is not registered.

Accessing Editors2

#::getEditors()

PublicL222

Get every registered editor.

This is a snapshot. Use #observe to keep up with editors registered later.

Returns

Arrayof TextEditors.

#::getActiveTextEditor()

EssentialL242

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

TextEditoror null if focus is not in one.

Event Subscription2

#::observe(callback)

EssentialL272

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.

ArgumentDescription
callback
Function
to be called with each TextEditor.
editor
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidRemoveEditor(callback)

PublicL293

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.

ArgumentDescription
callback
Function
to be called with each removed TextEditor.
editor
The TextEditor that was removed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

Configuration1

#::maintainConfig(editor)

PublicL321

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.

ArgumentDescription
editor
The TextEditor whose configuration will be maintained.
Returns

Disposablethat 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)

EssentialL139

Invoke callback when style sheet changes associated with updating the list of active themes have completed.

ArgumentDescription
callback
Function
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeThemePacks(callback)

PublicL151

Invoke callback when a theme pack is registered or removed.

Returns

Disposableon which .dispose() can be called to unsubscribe.

Accessing Available Themes5

#::registerThemePack({ name, light, dark } = {})

PublicL178

Register a named light/dark theme pack.

A pack groups the complete theme stacks for both appearance modes.

ArgumentDescription
themePack
Object
The theme pack.
name
String
Its user-facing name.
light
Array<String>
Theme packages for light mode.
dark
Array<String>
Theme packages for dark mode.
Returns

Disposablethat removes the pack.

#::getThemePacks()

PublicL215
Returns

Array<Object>registered theme packs sorted by their user-facing names.

#::isThemePackActive(themePack)

PublicL225
Returns

Booleanwhether both configured mode pairs match themePack.

#::getActiveThemePack()

PublicL245
Returns

Object|undefinedregistered pack matching both configured mode pairs.

#::setThemePack(themePack)

PublicL255

Configure both appearance modes from themePack.

Accessing Loaded Themes2

#::getLoadedThemeNames()

PublicL278
Returns

Arrayof Strings of all the loaded theme names.

#::getLoadedThemes()

PublicL288
Returns

Arrayof all the loaded themes.

Accessing Active Themes2

#::getActiveThemeNames()

PublicL302
Returns

Arrayof Strings of all the active theme names.

#::getActiveThemes()

PublicL312
Returns

Arrayof all the active themes.

Managing Enabled Themes1

#::getEnabledThemeNames()

PublicL375

Get the enabled theme names from the config.

Returns

Arrayarray of theme names in the order that they should be activated.

Private1

#::updateAppearance(mutate)

PublicL843

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.

ArgumentDescription
mutate
Function
applying the change to the document.
Returns

Promisethat 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)

EssentialL113

Add a tooltip to the given element.

ArgumentDescription
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

Disposableon which .dispose() can be called to remove the tooltip.

#::addComposite(target, entries)

EssentialL135

Add several tooltip entries that are displayed together.

ArgumentDescription
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

Disposableon which .dispose() can be called to remove the composite tooltip.

#::findTooltips(target)

ExtendedL254

Find the tooltips that have been applied to the given element.

ArgumentDescription
target
The HTMLElement to find tooltips on.
Returns

Arrayof 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()

ExtendedL153

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, a String representing a line comment delimiter. (If undefined, there is no known line comment delimiter for the given buffer position.)
  • block: If present, a two-item Array containing Strings representing the starting and ending block comment delimiters. (If undefined, there are no known block comment delimiters for the given buffer position.)
Returns

Objectwith the following properties:

#::getLanguageSync()

ExtendedL192

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()

asyncExtendedL205

Retrieves the Tree-sitter language instance associated with this grammar.

Returns

Promisethat 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)

ExtendedL471

Given a kind of query, retrieves a Tree-sitter Query object in async fashion.

ArgumentDescription
queryType
A String describing the query type: typically one of highlightsQuery, foldsQuery, tagsQuery, or indentsQuery, but could be any other custom type.
Returns

Promisethat resolves to a Tree-sitter Query object.

#::createQuery(queryContents)

asyncExtendedL523

Creates an arbitrary query from this grammar. Package authors and end users can use queries for whatever purposes they like.

ArgumentDescription
queryContents
A String representing the entire contents of a query file. Can contain any number of queries.
Returns

Promisethat will resolve to a Tree-sitter Query object.

#::createQuerySync(queryContents)

ExtendedL541

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.

ArgumentDescription
queryContents
A String representing the entire contents of a query file. Can contain any number of queries.
Returns

ObjectTree-sitter Query object.

#::onDidChangeQuery(callback)

ExtendedL618

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.
ArgumentDescription
callback
Function
data
Object
filePath
String
The path to the query file on disk.
queryType
String
The type of query file, as denoted by its configuration key in the grammar file. Usually one of highlightsQuery, indentsQuery, foldsQuery, or tagsQuery.

#::onDidChangeQueryFile(callback)

ExtendedL630

Calls callback when any of this grammar’s queries change.

Alias of #onDidChangeQuery.

#::onDidLoadQueryFiles(callback)

ExtendedL647

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:

#::onDidAddInjectionPoint(callback)

ExtendedL662

Calls callback when an injection point is added to this grammar.

#::onDidRemoveInjectionPoint(callback)

ExtendedL677

Calls callback when an injection point is removed from this grammar.

#::addInjectionPoint(injectionPoint)

ExtendedL733

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.

ArgumentDescription
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
Boolean
controlling whether the injection range should include the ranges of the content node’s children. Defaults to false, meaning that the range of each of this node’s children will be “subtracted” from the injection range, and the remainder will be parsed as if those ranges of the buffer do not exist.
includeAdjacentWhitespaceoptional
Boolean
controlling whether the injection range should include whitespace that occurs between content nodes. Defaults to false. When true, if two injection ranges are separated from one another by only whitespace, that whitespace will be added to the injection range, and the ranges will be consolidated.
newlinesBetweenoptional
Boolean
controlling whether the injection range should include any newline characters that may exist in between injection ranges. Defaults to false. Grammars like ERB and EJS need this so that they do not interpret two different embedded code sections on different lines as occurring on the same line.
coverShallowerScopesoptional
Boolean
controlling whether the injection should prevent the parent grammar (and any of its ancestors) from applying scope boundaries within its injection range(s). Defaults to false.
languageScopeoptional
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)

EssentialL67

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)
ArgumentDescription
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

DisposabletextEditorElement }) ```; on which .dispose() can be called to remove the added provider.

#::getView(object)

EssentialL124

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

  1. Is the object an instance of HTMLElement? If true, return the object.
  2. Does the object have a method named getElement that returns an instance of HTMLElement? If true, return that value.
  3. Does the object have a property named element with a value which is an instance of HTMLElement? If true, return the property value.
  4. Is the object a jQuery object, indicated by the presence of a jquery property? If true, return the root DOM element (i.e. object[0]).
  5. 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

HTMLElementDOM 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()

PublicL25
Returns

Numberstable numeric id of the current Lumine window.

#::onWillDestroy(callback)

ExtendedL37

Subscribe before the current editor window is destroyed.

Returns

Disposableon which .dispose() can be called to unsubscribe.

#::whenLoaded()

ExtendedL49

Wait until the current editor window has finished loading.

Returns

Promiseresolving to the load time in milliseconds.

#::isDevMode()

PublicL62

Determine whether the current window is in development mode.

#::isSafeMode()

PublicL72

Determine whether the current window is in safe mode.

#::isSpecMode()

PublicL82

Determine whether the current window is running specs.

#::isHeadless()

ExtendedL92

Determine whether the current window is running headlessly.

#::getInitialPaths()

ExtendedL102
Returns

Array<String>paths supplied when the current window was opened.

#::getLoadTime()

PublicL112
Returns

Number|nullThe completed window load time in milliseconds, or null before loading completes.

#::getStartupMarkers()

PublicL122
Returns

Objectstartup timing markers for the current window.

#::getState()

PublicL132
Returns

Promise<Object>A serializable state snapshot with id, position, size, maximized, fullScreen, and visible fields.

#::getSize()

PublicL142
Returns

Promise<Object>The current content size as {width, height}.

#::setSize(width, height)

PublicL156

Set the content size.

ArgumentDescription
width
A finite Number in pixels.
height
A finite Number in pixels.
Returns

Promisethat resolves when the request is applied.

#::getPosition()

PublicL166
Returns

Promise<Object>The current screen position as {x, y}.

#::setPosition(x, y)

PublicL180

Set the current screen position.

ArgumentDescription
x
A finite Number in pixels.
y
A finite Number in pixels.
Returns

Promisethat resolves when the request is applied.

#::center()

PublicL192

Center the current window on its display.

Returns

Promisethat resolves when the request is applied.

#::focus()

PublicL204

Focus the current window.

Returns

Promisethat resolves when the request is applied.

#::show()

PublicL216

Show the current window and restore its focus policy.

Returns

Promisethat resolves when the request is applied.

#::hide()

PublicL228

Hide the current window.

Returns

Promisethat resolves when the request is applied.

#::close()

PublicL240

Close the current window.

Returns

Promisethat resolves when the close request is accepted.

#::reload()

PublicL252

Reload the current window.

Returns

Promisethat resolves after the reloaded renderer reports ready.

#::minimize()

PublicL264

Minimize the current window.

Returns

Promisethat resolves when the request is applied.

#::maximize()

PublicL276

Maximize the current window.

Returns

Promisethat resolves when the request is applied.

#::unmaximize()

PublicL288

Restore a maximized window.

Returns

Promisethat resolves when the request is applied.

#::isMaximized()

PublicL300

Determine whether the current window is maximized.

Returns

Promiseresolving to a Boolean.

#::isFullScreen()

PublicL312

Determine whether the current window is full screen.

Returns

Promiseresolving to a Boolean.

#::isVisible()

PublicL324

Determine whether the current window is visible.

Returns

Promiseresolving to a Boolean.

#::setFullScreen(fullScreen = false)

PublicL337

Enter or leave full-screen mode.

ArgumentDescription
fullScreen
A Boolean indicating the desired state.
Returns

Promisethat resolves when the request is applied.

#::toggleFullScreen()

asyncPublicL349

Toggle full-screen mode.

Returns

Promisethat resolves when the request is applied.

#::pickFolder()

PublicL361

Ask the user to select one or more folders.

Returns

Promiseresolving to an Array of paths, or null on cancellation.

#::showSaveDialog(options = {})

PublicL374

Show a save dialog owned by the current window.

ArgumentDescription
options
Serializable Electron save-dialog options.
Returns

Promiseresolving to Electron’s serializable save-dialog result.

#::confirm(options)

EssentialL387

Show a non-blocking confirmation dialog owned by the current window.

Returns

Promiseresolving to the selected button index.

#::downloadURL(url)

PublicL400

Start a download in the current window.

ArgumentDescription
url
The String URL to download.
Returns

Promisethat resolves when the download is started.

#::getPrimaryDisplayWorkAreaSize()

PublicL410
Returns

Promise<Object>The primary display’s available work-area size as {width, height}.

#::setAutoHideMenuBar(autoHide)

PublicL422

Control whether the menu bar hides automatically.

Returns

Promisethat resolves when the request is applied.

#::setMenuBarVisibility(visible)

PublicL434

Show or hide the menu bar.

Returns

Promisethat resolves when the request is applied.

#::openDevTools()

asyncPublicL446

Open the current window’s developer tools.

Returns

Promisethat resolves when the request is applied.

#::closeDevTools()

asyncPublicL459

Close the current window’s developer tools.

Returns

Promisethat resolves when the request is applied.

#::toggleDevTools()

asyncPublicL472

Toggle the current window’s developer tools.

Returns

Promisethat resolves when the request is applied.

#::executeJavaScriptInDevTools(code)

PublicL485

Evaluate JavaScript in the current window’s developer tools.

Returns

Promisethat resolves after evaluation, or immediately when developer tools are closed.

#::broadcast(eventName, ...args)

PublicL499

Send a serializable event to every other registered Lumine window.

ArgumentDescription
eventName
A non-empty String event name.
...args
Structured-cloneable values delivered to subscribers.
Returns

Promisethat resolves after the event is sent.

#::onDidReceive(eventName, callback)

PublicL514

Subscribe to named events broadcast by other Lumine windows.

Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidEnterFullScreen(callback)

PublicL529

Invoke callback after entering full-screen mode.

Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidLeaveFullScreen(callback)

PublicL541

Invoke callback after leaving full-screen mode.

Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidMaximize(callback)

PublicL553

Invoke callback after the window is maximized.

Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidUnmaximize(callback)

PublicL565

Invoke callback after a maximized window is restored.

Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidFocus(callback)

PublicL577

Invoke callback when the window gains focus.

Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidBlur(callback)

PublicL589

Invoke callback when the window loses focus.

Returns

Disposableon 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 = {})

asyncExtendedL625

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.

ArgumentDescription
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

Promisethat resolves once they are empty.

Event Subscription22

#::observeTextEditors(callback)

EssentialL971

Invoke the given callback with all current and future text editors in the workspace.

ArgumentDescription
callback
Function
to 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

Disposableon which .dispose() can be called to unsubscribe.

#::observePaneItems(callback)

EssentialL989

Invoke the given callback with all current and future panes items in the workspace.

ArgumentDescription
callback
Function
to be called with current and future pane items.
item
An item that is present in #getPaneItems at the time of subscription or that is added at some later time.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeActivePaneItem(callback)

EssentialL1010

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.

ArgumentDescription
callback
Function
to be called when the active pane item changes.
item
The active pane item.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidStopChangingActivePaneItem(callback)

EssentialL1031

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.

ArgumentDescription
callback
Function
to be called when the active pane item stops changing.
item
The active pane item.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeActiveTextEditor(callback)

EssentialL1046

Invoke the given callback when a text editor becomes the active text editor and when there is no longer an active text editor.

ArgumentDescription
callback
Function
to be called when the active text editor changes.
editor
The active TextEditor or undefined if there is no longer an active text editor.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeActivePaneItem(callback)

EssentialL1061

Invoke the given callback with the current active pane item and with all future active pane items in the workspace.

ArgumentDescription
callback
Function
to be called when the active pane item changes.
item
The current active pane item.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeActiveTextEditor(callback)

EssentialL1078

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.

ArgumentDescription
callback
Function
to be called when the active text editor changes.
editor
The active TextEditor or undefined if there is not an active text editor.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeActiveFileTextEditor(callback)

ExtendedL1095

Invoke the given callback when the editor holding the active item’s file content changes. See #getActiveFileTextEditor.

ArgumentDescription
callback
Function
to be called when the resolved editor changes.
editor
The resolved TextEditor or undefined.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeActiveFileTextEditor(callback)

ExtendedL1110

Invoke the given callback with the current and all future editors holding the active item’s file content. See #getActiveFileTextEditor.

ArgumentDescription
callback
Function
to be called when the resolved editor changes.
editor
The resolved TextEditor or undefined.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeActiveEmbeddedTextEditor(callback)

ExtendedL1127

Invoke the given callback when the editor being edited inside the active item changes. See #getActiveEmbeddedTextEditor.

ArgumentDescription
callback
Function
to be called when the resolved editor changes.
editor
The resolved TextEditor or undefined.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeActiveEmbeddedTextEditor(callback)

ExtendedL1142

Invoke the given callback with the current and all future editors being edited inside the active item. See #getActiveEmbeddedTextEditor.

ArgumentDescription
callback
Function
to be called when the resolved editor changes.
editor
The resolved TextEditor or undefined.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidOpen(callback)

EssentialL1164

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.

ArgumentDescription
callback
Function
to be called whenever an item is opened.
event
Object
with the following keys:
uri
String
representing the opened URI. Could be undefined.
item
The opened item.
pane
The pane in which the item was opened.
index
The index of the opened item on its pane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidAddPane(callback)

ExtendedL1179

Invoke the given callback when a pane is added to the workspace.

ArgumentDescription
callback
Function
to be called when panes are added.
event
Object
with the following keys:
pane
The added pane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onWillDestroyPane(callback)

ExtendedL1197

Invoke the given callback before a pane is destroyed in the workspace.

ArgumentDescription
callback
Function
to be called before panes are destroyed.
event
Object
with the following keys:
pane
The pane to be destroyed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDestroyPane(callback)

ExtendedL1215

Invoke the given callback when a pane is destroyed in the workspace.

ArgumentDescription
callback
Function
to be called when panes are destroyed.
event
Object
with the following keys:
pane
The destroyed pane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observePanes(callback)

ExtendedL1232

Invoke the given callback with all current and future panes in the workspace.

ArgumentDescription
callback
Function
to be called with current and future panes.
pane
A Pane that is present in #getPanes at the time of subscription or that is added at some later time.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeActivePane(callback)

ExtendedL1248

Invoke the given callback when the active pane changes.

ArgumentDescription
callback
Function
to be called when the active pane changes.
pane
A Pane that is the current return value of #getActivePane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeActivePane(callback)

ExtendedL1263

Invoke the given callback with the current active pane and when the active pane changes.

ArgumentDescription
callback
Function
to be called with the current and future active panes.
pane
A Pane that is the current return value of #getActivePane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidAddPaneItem(callback)

ExtendedL1282

Invoke the given callback when a pane item is added to the workspace.

ArgumentDescription
callback
Function
to be called when pane items are added.
event
Object
with the following keys:
item
The added pane item.
pane
Pane
containing the added item.
index
Number
indicating the index of the added item in its pane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onWillDestroyPaneItem(callback)

ExtendedL1302

Invoke the given callback when a pane item is about to be destroyed, before the user is prompted to save it.

ArgumentDescription
callback
Function
to be called before pane items are destroyed. If this function returns a Promise, then the item will not be destroyed until the promise resolves.
event
Object
with the following keys:
item
The item to be destroyed.
pane
Pane
containing the item to be destroyed.
index
Number
indicating the index of the item to be destroyed in its pane.
Returns

Disposableon which .dispose can be called to unsubscribe.

#::onDidDestroyPaneItem(callback)

ExtendedL1321

Invoke the given callback when a pane item is destroyed.

ArgumentDescription
callback
Function
to be called when pane items are destroyed.
event
Object
with the following keys:
item
The destroyed item.
pane
Pane
containing the destroyed item.
index
Number
indicating the index of the destroyed item in its pane.
Returns

Disposableon which .dispose can be called to unsubscribe.

#::onDidAddTextEditor(callback)

ExtendedL1341

Invoke the given callback when a text editor is added to the workspace.

ArgumentDescription
callback
Function
to be called when text editors are added.
event
Object
with the following keys:
textEditor
TextEditor
that was added.
pane
Pane
containing the added text editor.
index
Number
indicating the index of the added text editor in its pane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

Opening8

#::open(itemOrURI, options = {})

asyncEssentialL1370

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.

ArgumentDescription
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
A Boolean indicating whether to call Pane#activate on containing pane. Defaults to true.
activateItem
A Boolean indicating whether to call Pane#activateItem on containing pane. Defaults to true.
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

Promisethat resolves to the TextEditor for the file URI.

#::hide(itemOrURI)

EssentialL1599

Search the workspace for items matching the given URI and hide them.

ArgumentDescription
itemOrURI
The item to hide or a String containing the URI of the item to hide.
Returns

Booleanindicating whether any items were found (and hidden).

#::toggle(itemOrURI)

EssentialL1638

Search the workspace for items matching the given URI. If any are found, hide them. Otherwise, open the URL.

ArgumentDescription
itemOrURIoptional
The item to toggle or a String containing the URI of the item to toggle.
Returns

PromisePromise that resolves when the item is shown or hidden.

#::createItemForURI(uri, options)

asyncPublicL1760

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.

ArgumentDescription
uri
A String containing a URI.
Returns

Promisethat resolves to the TextEditor (or other item) for the given URI.

#::isTextEditor(object)

PublicL1849
ArgumentDescription
object
An Object you want to perform the check against.
Returns

Booleanthat is true if object is a TextEditor.

#::buildTextEditor(params)

ExtendedL1861

Create a new text editor.

Returns

TextEditor

#::buildSelectList(props)

EssentialL1899

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.

ArgumentDescription
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)

EssentialL1925

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.

ArgumentDescription
props
An Object describing the dialog, including didConfirm(query), didCancel() and didChangeQuery(query).
Returns

InputDialogView

Modal flow6

#::popModal()

EssentialL1957

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

Booleanfalse when there is no step to go back to.

#::popModalTo(index)

EssentialL1970

Jump back to an earlier step of the modal breadcrumb trail.

ArgumentDescription
index
The zero-based trail position to return to, as reported by #getModalTrail. The breadcrumb strip wires its crumbs to this.
Returns

Booleanfalse when the index is not an earlier step.

#::getModalTrail()

EssentialL1982

The current modal breadcrumb trail.

Returns

Arrayof String labels, root first; empty when no flow is active.

#::onDidChangeModalTrail(callback)

ExtendedL1996

Invoke the given callback whenever the modal breadcrumb trail changes — a step is entered, the flow goes back, or the trail ends.

ArgumentDescription
callback
Function
receiving the trail as #getModalTrail reports it.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::reopenItem()

PublicL2009

Asynchronously reopens the last-closed item’s URI if it hasn’t already been reopened.

Returns

Promisethat is resolved when the item is opened

#::addOpener(opener)

PublicL2056

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.

ArgumentDescription
opener
A Function to be called when a path is being opened.
Returns

Disposableon which .dispose() can be called to remove the opener.

Pane Items9

#::getPaneItems()

EssentialL2079

Get all pane items in the workspace.

Returns

Arrayof items.

#::getActivePaneItem()

EssentialL2091

Get the active Pane's active item.

Returns

Objectpane item Object.

#::getTextEditors()

EssentialL2103

Get all text editors in the workspace, if they are pane items.

Returns

Arrayof TextEditors.

#::getActiveTextEditor()

EssentialL2132

Get the workspace center’s active item if it is a TextEditor.

Returns

TextEditoror undefined if the workspace center’s current active item is not a TextEditor.

#::getActiveFileTextEditor()

ExtendedL2153

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

TextEditoror undefined when the active item holds no file content.

#::getActiveEmbeddedTextEditor()

ExtendedL2182

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

TextEditoror undefined when nothing editable is active.

#::saveActivePaneItem()

ExtendedL2220

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()

ExtendedL2238

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()

ExtendedL2263

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()

ExtendedL2279

Get the most recently focused pane container.

Returns

Dockor the WorkspaceCenter.

#::getPanes()

ExtendedL2291

Get all panes in the workspace.

Returns

Arrayof Panes.

#::activateNextPane()

ExtendedL2317

Make the next pane active.

#::activatePreviousPane()

ExtendedL2327

Make the previous pane active.

#::paneContainerForURI(uri)

ExtendedL2341

Get the first pane container that contains an item with the given URI.

ArgumentDescription
uri
String
uri
Returns

Dockthe WorkspaceCenter, or undefined if no item exists with the given URI.

#::paneContainerForItem(item)

ExtendedL2354

Get the first pane container that contains the given item.

ArgumentDescription
item
the Item that the returned pane container must contain.
Returns

Dockthe WorkspaceCenter, or undefined if no pane container contains the given item.

#::paneForURI(uri)

ExtendedL2367

Get the first Pane that contains an item with the given URI.

ArgumentDescription
uri
String
uri
Returns

Paneor undefined if no item exists with the given URI.

#::paneForItem(item)

ExtendedL2385

Get the Pane containing the given item.

ArgumentDescription
item
the Item that the returned pane must contain.
Returns

Paneor undefined if no pane exists for the given item.

#::closeActivePaneItemOrEmptyPaneOrWindow()

ExtendedL2412

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

#::getLeftDock()

EssentialL2503

Get the Dock to the left of the editor window.

#::getRightDock()

EssentialL2513

Get the Dock to the right of the editor window.

#::getBottomDock()

EssentialL2523

Get the Dock below the editor window.

#::beginLayoutDrag()

ExtendedL2562

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

Disposableon 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()

EssentialL2576

Get an Array of all the panel items at the bottom of the editor window.

#::addBottomPanel(options)

EssentialL2592

Adds a panel item to the bottom of the editor window.

ArgumentDescription
options
Object
item
Your panel content. It can be DOM element, a jQuery element, or a model with a view registered via ViewRegistry#addViewProvider. We recommend the latter. See ViewRegistry#addViewProvider for more information.
visibleoptional
Boolean
false if you want the panel to initially be hidden (default: true)
priorityoptional
Number
Determines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100)
Returns

Panel

#::getLeftPanels()

EssentialL2602

Get an Array of all the panel items to the left of the editor window.

#::addLeftPanel(options)

EssentialL2618

Adds a panel item to the left of the editor window.

ArgumentDescription
options
Object
item
Your panel content. It can be DOM element, a jQuery element, or a model with a view registered via ViewRegistry#addViewProvider. We recommend the latter. See ViewRegistry#addViewProvider for more information.
visibleoptional
Boolean
false if you want the panel to initially be hidden (default: true)
priorityoptional
Number
Determines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100)
Returns

Panel

#::getRightPanels()

EssentialL2628

Get an Array of all the panel items to the right of the editor window.

#::addRightPanel(options)

EssentialL2644

Adds a panel item to the right of the editor window.

ArgumentDescription
options
Object
item
Your panel content. It can be DOM element, a jQuery element, or a model with a view registered via ViewRegistry#addViewProvider. We recommend the latter. See ViewRegistry#addViewProvider for more information.
visibleoptional
Boolean
false if you want the panel to initially be hidden (default: true)
priorityoptional
Number
Determines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100)
Returns

Panel

#::getTopPanels()

EssentialL2654

Get an Array of all the panel items at the top of the editor window.

#::addTopPanel(options)

EssentialL2670

Adds a panel item to the top of the editor window above the tabs.

ArgumentDescription
options
Object
item
Your panel content. It can be DOM element, a jQuery element, or a model with a view registered via ViewRegistry#addViewProvider. We recommend the latter. See ViewRegistry#addViewProvider for more information.
visibleoptional
Boolean
false if you want the panel to initially be hidden (default: true)
priorityoptional
Number
Determines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100)
Returns

Panel

#::getHeaderPanels()

EssentialL2680

Get an Array of all the panel items in the header.

#::addHeaderPanel(options)

EssentialL2696

Adds a panel item to the header.

ArgumentDescription
options
Object
item
Your panel content. It can be DOM element, a jQuery element, or a model with a view registered via ViewRegistry#addViewProvider. We recommend the latter. See ViewRegistry#addViewProvider for more information.
visibleoptional
Boolean
false if you want the panel to initially be hidden (default: true)
priorityoptional
Number
Determines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100)
Returns

Panel

#::getFooterPanels()

EssentialL2706

Get an Array of all the panel items in the footer.

#::addFooterPanel(options)

EssentialL2722

Adds a panel item to the footer.

ArgumentDescription
options
Object
item
Your panel content. It can be DOM element, a jQuery element, or a model with a view registered via ViewRegistry#addViewProvider. We recommend the latter. See ViewRegistry#addViewProvider for more information.
visibleoptional
Boolean
false if you want the panel to initially be hidden (default: true)
priorityoptional
Number
Determines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100)
Returns

Panel

#::getModalPanels()

EssentialL2732

Get an Array of all the modal panel items

#::addModalPanel(options = {})

EssentialL2751

Adds a panel item as a modal dialog.

ArgumentDescription
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
Boolean
false if you want the panel to initially be hidden (default: true)
priorityoptional
Number
Determines stacking order. Lower priority items are forced closer to the edges of the window. (default: 100)
autoFocusoptional
Boolean|Element
true if you want modal focus managed for you by Lumine. Lumine will automatically focus on this element or your modal panel’s first tabbable element when the modal opens and will restore the previously selected element when the modal closes. Lumine will also automatically restrict user tab focus within your modal while it is open. (default: false)
restoreFocusoptional
Boolean
false if you want to manage focus restoration yourself. By default, when a modal panel is hidden, focus returns to the element that was focused before the modal opened — or, for chained modals, before the first modal in the chain opened. (default: true)
crumboptional
String
the label this panel carries on the modal breadcrumb trail. Used when the panel is shown as a flow step without an explicit label — panel.show({crumb: true}) — and when a step shown on top of this panel adopts it as the trail root. See Panel#show.
Returns

Panel

#::panelForItem(item)

EssentialL2762
ArgumentDescription
item
Item the panel contains
Returns

Panelassociated with the given item. Returns null when the item has no panel.

Searching and Replacing3

#::scan(regex, options = {}, iterator)

PublicL2823

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.

ArgumentDescription
regex
RegExp
to search with.
optionsoptional
Object
iterator
Function
callback on each file found.
paths
An Array of glob patterns to search within. (See note below for multi-root projects.)
includeVcsIgnoredPaths
Boolean
default false; Whether to include paths excluded by VCS ignore files, regardless of the core preference.
onPathsSearchedoptional
Function
to be periodically called with number of paths searched.
leadingContextLineCount
Number
default 0; The number of lines before the matched line to include in the results object.
trailingContextLineCount
Number
default 0; The number of lines after the matched line to include in the results object.
Returns

Promisewith a cancel() method that will cancel all of the underlying searches that were started as part of this scan.

#::replace(regex, replacementText, filePaths, iterator)

PublicL3144

Performs a replace across all the specified files in the project.

ArgumentDescription
regex
A RegExp to search with.
replacementText
String
to 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
Object
with keys filePath and replacements.
Returns

Promise

#::filePathMatchesPatterns(filePath, rawPatterns)

ExperimentalL3215

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.

ArgumentDescription
filePath
String
representing the absolute path to a file in the project. (Any external path will automatically return false.)
rawPatterns
Array
of strings that describe glob patterns. Identical to (and uses the same glob semantics as) the options.paths argument of #scan.
Returns

Booleanboolean 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)

EssentialL66

Invoke the given callback with all current and future text editors in the workspace center.

ArgumentDescription
callback
Function
to 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

Disposableon which .dispose() can be called to unsubscribe.

#::observePaneItems(callback)

EssentialL84

Invoke the given callback with all current and future panes items in the workspace center.

ArgumentDescription
callback
Function
to be called with current and future pane items.
item
An item that is present in #getPaneItems at the time of subscription or that is added at some later time.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeActivePaneItem(callback)

EssentialL103

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.

ArgumentDescription
callback
Function
to be called when the active pane item changes.
item
The active pane item.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidStopChangingActivePaneItem(callback)

EssentialL124

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.

ArgumentDescription
callback
Function
to be called when the active pane item stops changing.
item
The active pane item.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeActivePaneItem(callback)

EssentialL139

Invoke the given callback with the current active pane item and with all future active pane items in the workspace center.

ArgumentDescription
callback
Function
to be called when the active pane item changes.
item
The current active pane item.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidAddPane(callback)

ExtendedL155

Invoke the given callback when a pane is added to the workspace center.

ArgumentDescription
callback
Function
to be called when panes are added.
event
Object
with the following keys:
pane
The added pane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onWillDestroyPane(callback)

ExtendedL171

Invoke the given callback before a pane is destroyed in the workspace center.

ArgumentDescription
callback
Function
to be called before panes are destroyed.
event
Object
with the following keys:
pane
The pane to be destroyed.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidDestroyPane(callback)

ExtendedL187

Invoke the given callback when a pane is destroyed in the workspace center.

ArgumentDescription
callback
Function
to be called when panes are destroyed.
event
Object
with the following keys:
pane
The destroyed pane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observePanes(callback)

ExtendedL202

Invoke the given callback with all current and future panes in the workspace center.

ArgumentDescription
callback
Function
to be called with current and future panes.
pane
A Pane that is present in #getPanes at the time of subscription or that is added at some later time.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidChangeActivePane(callback)

ExtendedL216

Invoke the given callback when the active pane changes.

ArgumentDescription
callback
Function
to be called when the active pane changes.
pane
A Pane that is the current return value of #getActivePane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::observeActivePane(callback)

ExtendedL231

Invoke the given callback with the current active pane and when the active pane changes.

ArgumentDescription
callback
Function
to be called with the current and future active panes.
pane
A Pane that is the current return value of #getActivePane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onDidAddPaneItem(callback)

ExtendedL249

Invoke the given callback when a pane item is added to the workspace center.

ArgumentDescription
callback
Function
to be called when pane items are added.
event
Object
with the following keys:
item
The added pane item.
pane
Pane
containing the added item.
index
Number
indicating the index of the added item in its pane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

#::onWillDestroyPaneItem(callback)

ExtendedL267

Invoke the given callback when a pane item is about to be destroyed, before the user is prompted to save it.

ArgumentDescription
callback
Function
to be called before pane items are destroyed.
event
Object
with the following keys:
item
The item to be destroyed.
pane
Pane
containing the item to be destroyed.
index
Number
indicating the index of the item to be destroyed in its pane.
Returns

Disposableon which .dispose can be called to unsubscribe.

#::onDidDestroyPaneItem(callback)

ExtendedL284

Invoke the given callback when a pane item is destroyed.

ArgumentDescription
callback
Function
to be called when pane items are destroyed.
event
Object
with the following keys:
item
The destroyed item.
pane
Pane
containing the destroyed item.
index
Number
indicating the index of the destroyed item in its pane.
Returns

Disposableon which .dispose can be called to unsubscribe.

#::onDidAddTextEditor(callback)

ExtendedL302

Invoke the given callback when a text editor is added to the workspace center.

ArgumentDescription
callback
Function
to be called when panes are added.
event
Object
with the following keys:
textEditor
TextEditor
that was added.
pane
Pane
containing the added text editor.
index
Number
indicating the index of the added text editor in its pane.
Returns

Disposableon which .dispose() can be called to unsubscribe.

Pane Items4

#::getPaneItems()

EssentialL322

Get all pane items in the workspace center.

Returns

Arrayof items.

#::getActivePaneItem()

EssentialL334

Get the active Pane's active item.

Returns

Objectpane item Object.

#::getTextEditors()

EssentialL346

Get all text editors in the workspace center.

Returns

Arrayof TextEditors.

Panes4

#::getPanes()

ExtendedL386

Get all panes in the workspace center.

Returns

Arrayof Panes.

#::getActivePane()

ExtendedL398

Get the active Pane.

Returns

Pane

#::activateNextPane()

ExtendedL408

Make the next pane active.

#::activatePreviousPane()

ExtendedL418

Make the previous pane active.

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.

ArgumentDescription
content
HTMLFragment
The HTML Node/Fragment to apply syntax highlighting on. Will modify the original object.
givenOpts
object
Optional Arguments:
syntaxScopeNameFunc
function
A function that can be called with any given language ID from a code block scope, and returns the grammar source id that should be used to perform syntax highlighting.
renderMode
string
Whether we are rendering a document fragment or a full document. Valid values: “full”, “fragment”.
grammar
object
The grammar of the source file. Carryover from original markdown-preview functionality.
autoWidth
boolean
Whether the editors standing in for code blocks size themselves to their longest line (“fragment” mode only). A code block otherwise takes the width its container gives it, which is nothing at all when the container is sized by its content — a tooltip, a popover. Pass true there.

#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.

ArgumentDescription
content
string
The 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.

ArgumentDescription
selector
A String selector such as "source.js", or an Array of the parts it is made of. An empty selector matches everything.
Returns

Functiontaking 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”.

ArgumentDescription
text
string
The string to fold.
Returns

stringThe 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.

ArgumentDescription
content
string
The Markdown source material.
givenOpts
object
The optional arguments:
renderMode
string
Determines how the page is rendered. Valid values “full” or “fragment”.
html
boolean
Whether HTML tags should be allowed.
sanitize
boolean
If the page content should be saniized via DOMPurify.
sanitizeAllowUnknownProtocols
boolean
Controls DOMPurify’s own option of ‘ALLOW_UNKNOWN_PROTOCOLS’.
sanitizeAllowSelfClose
boolean
Controls DOMPurify’s own option of ‘ALLOW_SELF_CLOSE’
breaks
boolean
If newlines should always be converted into breaklines.
handleFrontMatter
boolean
Whether frontmatter data should processed and displayed.
useDefaultEmoji
boolean
Whether markdown-it-emoji should be enabled.
useGitHubHeadings
boolean
Whether markdown-it-github-headings should be enabled. False by default.
useTaskCheckbox
boolean
Whether markdown-it-task-checkbox should be enabled. True by default.
taskCheckboxDisabled
boolean
Controls markdown-it-task-checkbox disabled option. True by default.
taskCheckboxDivWrap
boolean
Controls markdown-it-task-checkbox divWrap option. False by default.
transformImageLinks
boolean
Attempt to resolve image URLs. True by default.
transformNonFqdnLinks
boolean
Attempt to resolve links that are not fully qualified domain names. True by default.
rootDomain
string
The root URL of the online resource. Useful when attempting to resolve any links on the page. Only works for online resources.
filePath
string
The local alternative to rootDomain. Used to resolve incomplete paths, but locally on the file system.
disableMode
string
The level of disabling of markdown features. none by default. But supports: “none”, “strict”
Returns

stringParsed HTML content.

#selectorMatchesAnyScope(selector, scopes)

Whether any of the given scopes matches a selector.

ArgumentDescription
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) invoke callback when the file is created or its contents change. Returns a Disposable.
  • onDidDelete(callback) invoke callback when the file is deleted (or renamed away from this path). Returns a Disposable.
  • onDidRename(callback) invoke callback with the new path when the file is renamed onto a sibling path. Returns a Disposable.
  • getStartPromise() a Promise that resolves once the watcher is armed.
  • dispose() stop watching and release the subscription.
ArgumentDescription
filePath
String
absolute path to the file to watch.
Returns

Objectwith:

#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()
ArgumentDescription
rootPath
String
specifies the absolute path to the root of the filesystem content to watch.
options
Control the watcher’s behavior:
eventCallback
Function
or other callable to be called each time a batch of filesystem events is observed.
realPaths
Boolean
Whether 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
Array
of objects that describe the events that have occurred.
action
String
describing 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
String
containing 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.

Link copied