Merge pull request #20900 from GlenCFL/atom-exports

atom: use exports over globals.
This commit is contained in:
Daniel Rosenwasser
2017-11-07 15:34:25 -08:00
committed by GitHub
38 changed files with 7715 additions and 5374 deletions
+2 -1
View File
@@ -1,8 +1,9 @@
import { Disposable } from "event-kit";
import KeymapManager = require("atom-keymap");
import * as ImportTest from "atom-keymap";
declare const element: HTMLElement;
declare let sub: EventKit.Disposable;
declare let sub: Disposable;
declare const event: KeyboardEvent;
// NPM Examples ===============================================================
+35 -23
View File
@@ -4,15 +4,17 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="event-kit" />
import { Disposable } from "event-kit";
declare global {
namespace AtomKeymap {
/** The event objects that are passed into the callbacks which the user provides to
/**
* The event objects that are passed into the callbacks which the user provides to
* specific API calls.
*/
namespace Events {
/** This custom subclass of CustomEvent exists to provide the ::abortKeyBinding
/**
* This custom subclass of CustomEvent exists to provide the ::abortKeyBinding
* method, as well as versions of the ::stopPropagation methods that record the
* intent to stop propagation so event bubbling can be properly simulated for
* detached elements.
@@ -70,12 +72,14 @@ declare global {
}
interface AddedKeystrokeResolver {
/** The currently resolved keystroke string. If your function returns a falsy
/**
* The currently resolved keystroke string. If your function returns a falsy
* value, this is how Atom will resolve your keystroke.
*/
keystroke: string;
/** The raw DOM 3 `KeyboardEvent` being resolved. See the DOM API documentation
/**
* The raw DOM 3 `KeyboardEvent` being resolved. See the DOM API documentation
* for more details.
*/
event: KeyboardEvent;
@@ -83,7 +87,8 @@ declare global {
/** The OS-specific name of the current keyboard layout. */
layoutName: string;
/** An object mapping DOM 3 `KeyboardEvent.code` values to objects with the
/**
* 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.
*/
@@ -91,7 +96,8 @@ declare global {
}
}
/** The option objects that the user is expected to fill out and provide to
/**
* The option objects that the user is expected to fill out and provide to
* specific API calls.
*/
namespace Options {
@@ -120,7 +126,8 @@ declare global {
/** Determines whether the given keystroke matches any contained within this binding. */
matches(keystroke: string): boolean;
/** Compare another KeyBinding to this instance.
/**
* Compare another KeyBinding to this instance.
* Returns <= -1 if the argument is considered lesser or of lower priority.
* Returns 0 if this binding is equivalent to the argument.
* Returns >= 1 if the argument is considered greater or of higher priority.
@@ -128,7 +135,8 @@ declare global {
compare(other: KeyBinding): number;
}
/** Allows commands to be associated with keystrokes in a context-sensitive way.
/**
* Allows commands to be associated with keystrokes in a context-sensitive way.
* In Atom, you can access a global instance of this object via `atom.keymaps`.
*/
interface KeymapManager {
@@ -143,29 +151,30 @@ declare global {
destroy(): void;
// Event Subscription
/** Invoke the given callback when one or more keystrokes completely match a key binding. */
/**
* Invoke the given callback when one or more keystrokes completely match a
* key binding.
*/
onDidMatchBinding(callback: (event: Events.FullKeybindingMatch) => void):
EventKit.Disposable;
Disposable;
/** Invoke the given callback when one or more keystrokes partially match a binding. */
onDidPartiallyMatchBindings(callback: (event: Events.PartialKeybindingMatch) =>
void): EventKit.Disposable;
void): Disposable;
/** Invoke the given callback when one or more keystrokes fail to match any bindings. */
onDidFailToMatchBinding(callback: (event: Events.FailedKeybindingMatch) =>
void): EventKit.Disposable;
void): Disposable;
/** Invoke the given callback when a keymap file is reloaded. */
onDidReloadKeymap(callback: (event: Events.KeymapLoaded) => void):
EventKit.Disposable;
onDidReloadKeymap(callback: (event: Events.KeymapLoaded) => void): Disposable;
/** Invoke the given callback when a keymap file is unloaded. */
onDidUnloadKeymap(callback: (event: Events.KeymapLoaded) => void):
EventKit.Disposable;
onDidUnloadKeymap(callback: (event: Events.KeymapLoaded) => void): Disposable;
/** Invoke the given callback when a keymap file not able to be loaded. */
onDidFailToReadFile(callback: (error: Events.FailedKeymapFileRead) => void):
EventKit.Disposable;
Disposable;
// Adding and Removing Bindings
/** Construct KeyBindings from an object grouping them by CSS selector. */
@@ -174,7 +183,7 @@ declare global {
/** Add sets of key bindings grouped by CSS selector. */
add(source: string, bindings: { [key: string]: { [key: string]: string }},
priority?: number): EventKit.Disposable;
priority?: number): Disposable;
// Accessing Bindings
/** Get all current key bindings. */
@@ -192,13 +201,15 @@ declare global {
loadKeymap(bindingsPath: string, options?: { watch?: boolean, priority?: number }):
void;
/** Cause the keymap to reload the key bindings file at the given path whenever
/**
* Cause the keymap to reload the key bindings file at the given path whenever
* it changes.
*/
watchKeymap(filePath: string, options?: { priority: number }): void;
// Managing Keyboard Events
/** Dispatch a custom event associated with the matching key binding for the
/**
* Dispatch a custom event associated with the matching key binding for the
* given `KeyboardEvent` if one can be found.
*/
handleKeyboardEvent(event: KeyboardEvent): void;
@@ -208,9 +219,10 @@ declare global {
/** Customize translation of raw keyboard events to keystroke strings. */
addKeystrokeResolver(resolver: (event: Events.AddedKeystrokeResolver) => string):
EventKit.Disposable;
Disposable;
/** Get the number of milliseconds allowed before pending states caused by
/**
* Get the number of milliseconds allowed before pending states caused by
* partial matches of multi-keystroke bindings are terminated.
*/
getPartialMatchTimeout(): number;
+1 -1
View File
@@ -8,7 +8,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+2 -30
View File
@@ -1,36 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
"class-name": true,
"indent": [true, "spaces", 4],
"jsdoc-format": true,
"max-line-length": [true, 110],
"quotemark": [true, "double", "avoid-escape"],
"trailing-comma": [true, {
"multiline": { "objects": "always", "arrays": "always", "functions": "never" },
"singleline": { "objects": "never", "arrays": "never", "functions": "never" }
}],
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-module",
"check-separator",
"check-type",
"check-typecast",
"check-rest-spread",
"check-preblock"
],
// Soon to be defaults.
"arrow-return-shorthand": [true, "multiline"],
"no-any": true,
"no-floating-promises": true,
"no-unbound-method": true,
"no-unsafe-any": true,
"number-literal-format": true,
"restrict-plus-operands": true,
"return-undefined": true,
"switch-final-break": true
"max-line-length": [true, 100],
"no-any": true
}
}
@@ -1,3 +1,4 @@
import { AtomEnvironment, TestRunnerParams } from "atom";
import { createRunner } from "atom-mocha-test-runner";
import defaultMochaRunner = require("atom-mocha-test-runner");
@@ -20,12 +21,12 @@ testRunner = createRunner({
testSuffixes: ["test.file"],
});
declare const atom: AtomCore.AtomEnvironment;
declare const atom: AtomEnvironment;
declare const blob: object;
declare let num: number;
async function runTests(): Promise<number> {
const runnerArgs: AtomCore.Structures.TestRunnerArgs = {
const runnerArgs: TestRunnerParams = {
testPaths: ["/var/test"],
logFile: "/var/log",
headless: false,
+4 -3
View File
@@ -5,7 +5,8 @@
// TypeScript Version: 2.3
/// <reference types="mocha" />
/// <reference types="atom" />
import { TestRunner } from "atom";
interface AtomMochaOptions {
/** Which reporter to use on the terminal. */
@@ -30,9 +31,9 @@ interface AtomMochaOptions {
// module.exports = createRunner()
// module.exports.createRunner = createRunner
// Which is what we're trying to model here.
interface TestRunnerExport extends AtomCore.TestRunner {
interface TestRunnerExport extends TestRunner {
createRunner(options?: AtomMochaOptions, mochaConfigFunction?:
(mocha: Mocha) => void): AtomCore.TestRunner;
(mocha: Mocha) => void): TestRunner;
}
declare const runner: TestRunnerExport;
+1 -1
View File
@@ -9,7 +9,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
+1 -29
View File
@@ -1,36 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
"class-name": true,
"indent": [true, "spaces", 4],
"jsdoc-format": true,
"max-line-length": [true, 100],
"quotemark": [true, "double", "avoid-escape"],
"trailing-comma": [true, {
"multiline": { "objects": "always", "arrays": "always", "functions": "never" },
"singleline": { "objects": "never", "arrays": "never", "functions": "never" }
}],
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-module",
"check-separator",
"check-type",
"check-typecast",
"check-rest-spread",
"check-preblock"
],
// Soon to be defaults.
"arrow-return-shorthand": [true, "multiline"],
"no-any": true,
"no-floating-promises": true,
"no-unbound-method": true,
"no-unsafe-any": true,
"number-literal-format": true,
"restrict-plus-operands": true,
"return-undefined": true,
"switch-final-break": true
"no-any": true
}
}
-60
View File
@@ -1,60 +0,0 @@
## Atom API Type Definitions
TypeScript type definitions for the [Atom Text Editor](https://atom.io/) public API, which is used to develop packages for the editor. Documentation for the public API can be found [here](https://atom.io/docs/api/v1.21.0/).
### Exports
#### The "atom" Variable
These definitions declare a global static variable named "atom" as ambient. Once these definitions have been referenced within your project, you will be able to access properties and member functions from the [AtomEnvironment](https://atom.io/docs/api/v1.21.0/AtomEnvironment) class off of this variable, as it is an instance of that class.
```ts
if (atom.inDevMode()) {}
```
#### The Atom Namespace
All of the types used by or referenced by the Atom public API have been pulled into the Atom namespace, providing a consistent and easy way to access each of them, without having to care about where that type actually lives within the Atom codebase.
```ts
function example(buffer: Atom.TextBuffer) {}
```
#### The AtomCore Namespace
All classes which are core to Atom itself have been provided under the AtomCore namespace.
```ts
function example(cursor: AtomCore.Cursor) {}
```
### Service Type Definitions
There are many services provided by other Atom packages that you may want to use within your own Atom package. We bundle type definitions for several of these services with these type definitions. All type definitions for services are available only through ES6 imports.
```ts
import { AutocompleteProvider } from "atom/autocomplete-plus";
let completionProvider: AutocompleteProvider;
```
The currently supported services are:
- [Autocomplete](https://github.com/atom/autocomplete-plus) (atom/autocomplete-plus)
- [Linter](https://github.com/atom/linter) (atom/linter)
- [Status Bar](https://github.com/atom/status-bar) (atom/status-bar)
### Exposing Private Methods and Properties
[Declaration Merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) can be used to augment any of the types used within Atom. As an example, if we wanted to reveal the private ```triggerActivationHook``` method within the PackageManager class, then we would create a file with the following contents:
```ts
// <<filename>>.d.ts
declare namespace AtomCore {
interface PackageManager {
triggerActivationHook(name: string): void;
triggerDeferredActivationHooks(): void;
}
}
```
Once this file is either referenced or included within your project, then this new member function would be freely usable on instances of the PackageManager class without TypeScript reporting errors.
+73 -77
View File
@@ -12,59 +12,59 @@ declare let regExp: RegExp;
declare let element: HTMLElement;
declare let elements: HTMLElement[];
declare const div: HTMLDivElement;
declare const keyboardEvent: KeyboardEvent;
declare const event: KeyboardEvent;
declare let buffer: TextBuffer.TextBuffer;
declare const color: AtomCore.Color;
declare let cursor: AtomCore.Cursor;
declare let cursors: AtomCore.Cursor[];
declare let decoration: AtomCore.Decoration;
declare let decorations: AtomCore.Decoration[];
declare let decorationLayerProps: AtomCore.Options.DecorationLayerProps;
declare let dir: PathWatcher.Directory;
declare let dirs: PathWatcher.Directory[];
declare let displayMarker: TextBuffer.DisplayMarker;
declare let displayMarkers: TextBuffer.DisplayMarker[];
declare let displayMarkerLayer: TextBuffer.DisplayMarkerLayer;
declare let dock: AtomCore.Dock;
declare let editor: AtomCore.TextEditor;
declare let editors: AtomCore.TextEditor[];
declare let emitter: EventKit.Emitter;
declare let file: PathWatcher.File;
declare let grammar: FirstMate.Grammar;
declare let grammars: FirstMate.Grammar[];
declare let gutter: AtomCore.Gutter;
declare let gutters: AtomCore.Gutter[];
declare let historyPaths: AtomCore.Structures.HistoryProject[];
declare let layerDecoration: AtomCore.LayerDecoration;
declare let marker: TextBuffer.Marker;
declare let markers: TextBuffer.Marker[];
declare let markerLayer: TextBuffer.MarkerLayer;
declare let notification: AtomCore.Notification;
declare let notifications: AtomCore.Notification[];
declare let pack: AtomCore.Package;
declare let packs: AtomCore.Package[];
declare let pane: AtomCore.Pane;
declare let panes: AtomCore.Pane[];
declare let paneContainer: AtomCore.Dock|AtomCore.WorkspaceCenter;
declare let panel: AtomCore.Panel;
declare let panels: AtomCore.Panel[];
declare let pos: TextBuffer.Point;
declare let posArr: TextBuffer.Point[];
declare let project: AtomCore.Project;
declare let range: TextBuffer.Range;
declare let ranges: TextBuffer.Range[];
declare let registry: FirstMate.GrammarRegistry;
declare let repository: AtomCore.GitRepository;
declare let repositories: AtomCore.GitRepository[];
declare let scopeDescriptor: AtomCore.ScopeDescriptor;
declare let selection: AtomCore.Selection;
declare let selections: AtomCore.Selection[];
declare let styleManager: AtomCore.StyleManager;
declare let subscription: EventKit.Disposable;
declare let subscriptions: EventKit.CompositeDisposable;
declare let tooltips: AtomCore.Structures.Tooltip[];
declare let workspaceCenter: AtomCore.WorkspaceCenter;
declare let buffer: Atom.TextBuffer;
declare const color: Atom.Color;
declare let cursor: Atom.Cursor;
declare let cursors: Atom.Cursor[];
declare let decoration: Atom.Decoration;
declare let decorations: Atom.Decoration[];
declare let decorationLayerProps: Atom.DecorationLayerOptions;
declare let dir: Atom.Directory;
declare let dirs: Atom.Directory[];
declare let displayMarker: Atom.DisplayMarker;
declare let displayMarkers: Atom.DisplayMarker[];
declare let displayMarkerLayer: Atom.DisplayMarkerLayer;
declare let dock: Atom.Dock;
declare let editor: Atom.TextEditor;
declare let editors: Atom.TextEditor[];
declare let emitter: Atom.Emitter;
declare let file: Atom.File;
declare let grammar: Atom.Grammar;
declare let grammars: Atom.Grammar[];
declare let gutter: Atom.Gutter;
declare let gutters: Atom.Gutter[];
declare let historyPaths: Atom.ProjectHistory[];
declare let layerDecoration: Atom.LayerDecoration;
declare let marker: Atom.Marker;
declare let markers: Atom.Marker[];
declare let markerLayer: Atom.MarkerLayer;
declare let notification: Atom.Notification;
declare let notifications: Atom.Notification[];
declare let pack: Atom.Package;
declare let packs: Atom.Package[];
declare let pane: Atom.Pane;
declare let panes: Atom.Pane[];
declare let paneContainer: Atom.Dock|Atom.WorkspaceCenter;
declare let panel: Atom.Panel;
declare let panels: Atom.Panel[];
declare let pos: Atom.Point;
declare let posArr: Atom.Point[];
declare let project: Atom.Project;
declare let range: Atom.Range;
declare let ranges: Atom.Range[];
declare let registry: Atom.GrammarRegistry;
declare let repository: Atom.GitRepository;
declare let repositories: Atom.GitRepository[];
declare let scopeDescriptor: Atom.ScopeDescriptor;
declare let selection: Atom.Selection;
declare let selections: Atom.Selection[];
declare let styleManager: Atom.StyleManager;
declare let subscription: Atom.Disposable;
declare let subscriptions: Atom.CompositeDisposable;
declare let tooltips: Atom.Tooltip[];
declare let workspaceCenter: Atom.WorkspaceCenter;
// AtomEnvironment ============================================================
function testAtomEnvironment() {
@@ -125,8 +125,8 @@ function testAtomEnvironment() {
});
subscription = atom.workspace.observeTextEditors((editor) => {
subscription = editor.onDidStopChanging((keyboardEvent) => {
for (const change of keyboardEvent.changes) {
subscription = editor.onDidStopChanging((event) => {
for (const change of event.changes) {
change.newExtent;
}
});
@@ -276,9 +276,6 @@ function testCommandRegistry() {
// CompositeDisposable ========================================================
function testCompositeDisposable() {
// Properties
bool = subscriptions.disposed;
// Construction and Lifecycle
subscriptions = new Atom.CompositeDisposable();
new Atom.CompositeDisposable(subscription);
@@ -482,7 +479,7 @@ function testCursor() {
// TestRunner =================================================================
function testTestRunner() {
const testRunner: AtomCore.TestRunner = (params) => {
const testRunner: Atom.TestRunner = (params) => {
const delegate = params.buildDefaultApplicationDelegate();
const environment = params.buildAtomEnvironment({
applicationDelegate: delegate,
@@ -803,7 +800,6 @@ function testDisplayMarkerLayer() {
// Disposable =================================================================
function testDisposable() {
bool = subscription.disposed;
if (subscription.disposalAction) subscription.disposalAction();
subscription.dispose();
}
@@ -847,8 +843,6 @@ function testDock() {
function testEmitter() {
emitter = new Atom.Emitter();
bool = emitter.disposed;
emitter.clear();
emitter.dispose();
@@ -1113,7 +1107,7 @@ function testKeymapManager() {
subscription = manager.add("a", {}, 0);
// Accessing Bindings
let bindings: AtomKeymap.KeyBinding[] = manager.getKeyBindings();
let bindings: Atom.KeyBinding[] = manager.getKeyBindings();
bindings = manager.findKeyBindings();
bindings = manager.findKeyBindings({ command: "a" });
bindings = manager.findKeyBindings({ keystrokes: "a" });
@@ -1127,8 +1121,8 @@ function testKeymapManager() {
manager.loadKeymap("Test.file", { watch: true, priority: 0});
// Managing Keyboard Events
manager.handleKeyboardEvent(keyboardEvent);
manager.keystrokeForKeyboardEvent(keyboardEvent);
manager.handleKeyboardEvent(event);
manager.keystrokeForKeyboardEvent(event);
subscription = manager.addKeystrokeResolver((event): string => {
event.layoutName;
@@ -1151,10 +1145,6 @@ function testLayerDecoration() {
function testMarker() {
// Properties
num = marker.id;
bool = marker.tailed;
bool = marker.reversed;
bool = marker.valid;
str = marker.invalidate;
// Lifecycle
marker = marker.copy({
@@ -1301,8 +1291,8 @@ function testNotification() {
});
// Event Subscription
subscription = notification.onDidDismiss(notification => notification.dismissed);
subscription = notification.onDidDisplay(notification => notification.timestamp);
subscription = notification.onDidDismiss(notification => notification.getType());
subscription = notification.onDidDisplay(notification => notification.getMessage());
// Methods
str = notification.getType();
@@ -1377,7 +1367,7 @@ function testPackageManager() {
subscription = atom.packages.onDidActivatePackage(pack => pack.name);
subscription = atom.packages.onDidDeactivatePackage(pack => pack.path);
subscription = atom.packages.onDidLoadPackage(pack => pack.isCompatible());
subscription = atom.packages.onDidUnloadPackage(pack => pack.bundledPackage);
subscription = atom.packages.onDidUnloadPackage(pack => pack.name);
// Package system data
str = atom.packages.getApmPath();
@@ -1618,7 +1608,7 @@ function testPoint() {
point.isGreaterThanOrEqual([0, 0]);
// Operations
const frozenPoint: Readonly<TextBuffer.Point> = point.freeze();
const frozenPoint: Readonly<Atom.Point> = point.freeze();
point = point.translate(point);
point.translate([0, 0]);
@@ -1644,7 +1634,7 @@ function testProject() {
});
subscription = project.onDidAddBuffer(buffer => buffer.id);
subscription = project.observeBuffers(buffer => buffer.file);
subscription = project.observeBuffers(buffer => buffer.getUri());
// Accessing the git repository
repositories = project.getRepositories();
@@ -1707,7 +1697,7 @@ function testRange() {
nums = range.getRows();
// Operations
const frozenRange: Readonly<TextBuffer.Range> = range.freeze();
const frozenRange: Readonly<Atom.Range> = range.freeze();
range = range.union(range);
range = range.translate(pos);
@@ -1923,7 +1913,7 @@ function testStyleManager() {
// Task =======================================================================
function testTask() {
let task: AtomCore.Task = Atom.Task.once("File.path", {}, () => {});
let task: Atom.Task = Atom.Task.once("File.path", {}, () => {});
task = new Atom.Task("File.path");
task.start({}, () => {});
@@ -2282,7 +2272,7 @@ function testTextEditor() {
subscription = editor.onDidChangeSoftWrapped(softWrapped => {});
subscription = editor.onDidChangeEncoding(encoding => {});
subscription = editor.observeGrammar(grammar => grammar.name);
subscription = editor.onDidChangeGrammar(grammar => grammar.scopeName);
subscription = editor.onDidChangeGrammar(grammar => grammar.name);
subscription = editor.onDidChangeModified(modified => {});
subscription = editor.onDidConflict(() => {});
subscription = editor.onWillInsertText(event => event.cancel && event.text);
@@ -3045,7 +3035,13 @@ function testWorkspace() {
if (result) obj = result;
}
atom.workspace.addOpener(() => element);
atom.workspace.addOpener((uri) => {
if (uri === "test://") {
return {
getTitle: () => "Test Title",
};
}
});
atom.workspace.buildTextEditor(obj);
+128
View File
@@ -0,0 +1,128 @@
import "../index";
declare module "atom" {
interface ConfigValues {
/**
* Suggestions will show as you type if this preference is enabled. If it is
* disabled, you can still see suggestions by using the keymapping for
* 'autocomplete-plus:activate' (shown below).
*/
"autocomplete-plus.enableAutoActivation": boolean;
/**
* If you are experiencing performance issues when typing, you should try
* increasing this value to a non-zero number (e.g. 100).
*/
"autocomplete-plus.autoActivationDelay": number;
/** The suggestion list will only show this many suggestions. */
"autocomplete-plus.maxVisibleSuggestions": number;
/**
* You should use the key(s) indicated here to confirm a suggestion from the
* suggestion list and have it inserted into the file.
*/
"autocomplete-plus.confirmCompletion":
| "tab"
| "enter"
| "tab and enter"
| "tab always, enter when suggestion explicitly selected";
/**
* Disable this if you want to bind your own keystrokes to move around the
* suggestion list. You will also need to add definitions to your keymap.
*/
"autocomplete-plus.useCoreMovementCommands": boolean;
/**
* Suggestions will not be provided for files matching this list, e.g. *.md
* for Markdown files. To blacklist more than one file extension, use comma
* as a separator, e.g. ["*.md", "*.txt"] (both Markdown and text files).
*/
"autocomplete-plus.fileBlacklist": string[];
/** Suggestions will not be provided for scopes matching this list. */
"autocomplete-plus.scopeBlacklist": string[];
/**
* For grammars with no registered provider(s), the default provider will
* include completions from all buffers, instead of just the buffer you are
* currently editing.
*/
"autocomplete-plus.includeCompletionsFromAllBuffers": boolean;
/**
* Fuzzy searching is performed if this is disabled; if it is enabled, suggestions
* must begin with the prefix from the current word.
*/
"autocomplete-plus.strictMatching": boolean;
/**
* Only autocomplete when you've typed at least this many characters.
* Note: May not affect external providers.
*/
"autocomplete-plus.minimumWordLength": number;
/**
* The package comes with a built-in provider that will provide suggestions
* using the words in your current buffer or all open buffers. You will get
* better suggestions by installing additional autocomplete+ providers.
* To stop using the built-in provider, disable this option.
*/
"autocomplete-plus.enableBuiltinProvider": boolean;
/** Don't use the built-in provider for these selector(s). */
"autocomplete-plus.builtinProviderBlacklist": string;
/**
* If enabled, typing `backspace` will show the suggestion list if suggestions
* are available. If disabled, suggestions will not be shown while backspacing.
*/
"autocomplete-plus.backspaceTriggersAutocomplete": boolean;
/**
* If enabled, automatically insert suggestion on manual activation with
* 'autocomplete-plus:activate' when there is only one match.
*/
"autocomplete-plus.enableAutoConfirmSingleSuggestion": boolean;
/**
* With 'Cursor' the suggestion list appears at the cursor's position.
* With 'Word' it appears at the beginning of the word that's being completed.
*/
"autocomplete-plus.suggestionListFollows": "Word"|"Cursor";
/**
* If you're having trouble with autocomplete, you may consider falling back
* to the Symbol provider and filing an issue.
*/
"autocomplete-plus.defaultProvider": "Subsequence"|"Symbol";
/** Don't auto-activate when any of these classes are present in the editor. */
"autocomplete-plus.suppressActivationForEditorClasses": string[];
/**
* Completing a suggestion consumes text following the cursor matching the
* suffix of the chosen suggestion.
*/
"autocomplete-plus.consumeSuffix": boolean;
/**
* -EXPERIMENTAL- Prefers runs of consecutive characters, acronyms and start
* of words.
*/
"autocomplete-plus.useAlternateScoring": boolean;
/** Gives words near the cursor position a higher score than those far away. */
"autocomplete-plus.useLocalityBonus": boolean;
/** Identifies non-latin alphabet characters as letters. */
"autocomplete-plus.enableExtendedUnicodeSupport": boolean;
/**
* Should similar suggestions be removed from the list? If so how to determine
* they are similar.
*/
"autocomplete-plus.similarSuggestionRemoval": "none"|"textOrSnippet";
}
}
@@ -1,16 +1,20 @@
// Autocomplete Plus 2.x
// https://atom.io/packages/autocomplete-plus
/// <reference path="./config.d.ts" />
import { Point, ScopeDescriptor, TextEditor } from "../index";
/** The parameters passed into getSuggestions by Autocomplete+. */
export interface SuggestionsRequestedEvent {
/** The current TextEditor. */
editor: AtomCore.TextEditor;
editor: TextEditor;
/** The position of the cursor. */
bufferPosition: TextBuffer.Point;
bufferPosition: Point;
/** The scope descriptor for the current cursor position. */
scopeDescriptor: AtomCore.ScopeDescriptor;
scopeDescriptor: ScopeDescriptor;
/** The prefix for the word immediately preceding the current cursor position. */
prefix: string;
@@ -21,26 +25,30 @@ export interface SuggestionsRequestedEvent {
/** The parameters passed into onDidInsertSuggestion by Autocomplete+. */
export interface SuggestionInsertedEvent {
editor: AtomCore.TextEditor;
triggerPosition: TextBuffer.Point;
editor: TextEditor;
triggerPosition: Point;
suggestion: TextSuggestion|SnippetSuggestion;
}
/** An autocompletion suggestion for the user.
/**
* An autocompletion suggestion for the user.
* Primary data type for the Atom Autocomplete+ service.
*/
export interface Suggestion<T extends { text: string }|{ snippet: string }> {
/** A string that will show in the UI for this suggestion.
/**
* A string that will show in the UI for this suggestion.
* When not set, snippet || text is displayed.
*/
displayText?: string;
/** The text immediately preceding the cursor, which will be replaced by the text.
/**
* The text immediately preceding the cursor, which will be replaced by the text.
* If not provided, the prefix passed into getSuggestions will be used.
*/
replacementPrefix?: string;
/** The suggestion type. It will be converted into an icon shown against the
/**
* The suggestion type. It will be converted into an icon shown against the
* suggestion.
*/
type?: string;
@@ -51,7 +59,8 @@ export interface Suggestion<T extends { text: string }|{ snippet: string }> {
/** Use this instead of leftLabel if you want to use html for the left label. */
leftLabelHTML?: string;
/** An indicator (e.g. function, variable) denoting the "kind" of suggestion this
/**
* An indicator (e.g. function, variable) denoting the "kind" of suggestion this
* represents.
*/
rightLabel?: string;
@@ -59,22 +68,26 @@ export interface Suggestion<T extends { text: string }|{ snippet: string }> {
/** Use this instead of rightLabel if you want to use html for the right label. */
rightLabelHTML?: string;
/** Class name for the suggestion in the suggestion list. Allows you to style your
/**
* Class name for the suggestion in the suggestion list. Allows you to style your
* suggestion via CSS, if desired.
*/
className?: string;
/** If you want complete control over the icon shown against the suggestion.
/**
* If you want complete control over the icon shown against the suggestion.
* e.g. iconHTML: <i class="icon-move-right"></i>
*/
iconHTML?: string;
/** A doc-string summary or short description of the suggestion. When specified, it
/**
* A doc-string summary or short description of the suggestion. When specified, it
* will be displayed at the bottom of the suggestions list.
*/
description?: string;
/** A url to the documentation or more information about this suggestion.
/**
* A url to the documentation or more information about this suggestion.
* When specified, a More.. link will be displayed in the description area.
*/
descriptionMoreURL?: string;
@@ -86,7 +99,8 @@ export interface TextSuggestion extends Suggestion<TextSuggestion> {
}
export interface SnippetSuggestion extends Suggestion<SnippetSuggestion> {
/** A snippet string. This will allow users to tab through function arguments
/**
* A snippet string. This will allow users to tab through function arguments
* or other options.
*/
snippet: string;
@@ -96,24 +110,28 @@ export type Suggestions = Array<TextSuggestion|SnippetSuggestion>;
/** The interface that all Autocomplete+ providers must implement. */
export interface AutocompleteProvider {
/** Defines the scope selector(s) (can be comma-separated) for which your provider
/**
* Defines the scope selector(s) (can be comma-separated) for which your provider
* should receive suggestion requests.
*/
selector: string;
/** Is called when a suggestion request has been dispatched by autocomplete+ to
/**
* Is called when a suggestion request has been dispatched by autocomplete+ to
* your provider. Return an array of suggestions (if any) in the order you would
* like them displayed to the user. Returning a Promise of an array of suggestions
* is also supported.
*/
getSuggestions(params: SuggestionsRequestedEvent): Suggestions|Promise<Suggestions>;
/** Defines the scope selector(s) (can be comma-separated) for which your provider
/**
* Defines the scope selector(s) (can be comma-separated) for which your provider
* should not be used.
*/
disableForSelector?: string;
/** A number to indicate its priority to be included in a suggestions request.
/**
* A number to indicate its priority to be included in a suggestions request.
* The default provider has an inclusion priority of 0. Higher priority providers
* can suppress lower priority providers with excludeLowerPriority.
*/
@@ -122,12 +140,14 @@ export interface AutocompleteProvider {
/** Will not use lower priority providers when this provider is used. */
excludeLowerPriority?: boolean;
/** A number to determine the sort order of suggestions. The default provider has
/**
* A number to determine the sort order of suggestions. The default provider has
* an suggestion priority of 1.
*/
suggestionPriority?: number;
/** Function that is called when a suggestion from your provider was inserted
/**
* Function that is called when a suggestion from your provider was inserted
* into the buffer.
*/
onDidInsertSuggestion?(params: SuggestionInsertedEvent): void;
+6467 -4084
View File
File diff suppressed because it is too large Load Diff
+26
View File
@@ -0,0 +1,26 @@
import "../index";
declare module "atom" {
interface ConfigValues {
/** Lint tabs while they are still in preview status. */
"linter.lintPreviewTabs": boolean;
/** Lint files automatically when they are opened. */
"linter.lintOnOpen": boolean;
/**
* Lint files while typing, without the need to save (only for supported
* providers).
*/
"linter.lintOnChange": boolean;
/** Interval at which linting is done as you type (in ms). */
"linter.lintOnChangeInterval": number;
/** Ignore files matching this Glob. */
"linter.ignoreGlob": string;
/** Disabled providers. */
"linter.disabledProviders": string[];
}
}
+13 -8
View File
@@ -1,9 +1,13 @@
// Linter 2.x
// https://atom.io/packages/linter
/// <reference path="./config.d.ts" />
import { Disposable, Point, Range, TextEditor } from "../index";
export interface ReplacementSolution {
title?: string;
position: TextBuffer.Range;
position: Range;
priority?: number;
currentText?: string;
replaceWith: string;
@@ -11,7 +15,7 @@ export interface ReplacementSolution {
export interface CallbackSolution {
title?: string;
position: TextBuffer.Range;
position: Range;
priority?: number;
// tslint:disable-next-line:no-any
apply(): any;
@@ -24,7 +28,7 @@ export interface Message {
file: string;
/** The range of the message in the editor. */
position: TextBuffer.Range;
position: Range;
};
/** A reference to a different location in the editor. */
@@ -33,7 +37,7 @@ export interface Message {
file: string;
/** The point being referenced in that file. */
position?: TextBuffer.Point;
position?: Point;
};
/** An HTTP link to a resource explaining the issue. Default is a google search. */
@@ -51,7 +55,8 @@ export interface Message {
/** Possible solutions (which the user can invoke at will). */
solutions?: Array<ReplacementSolution|CallbackSolution>;
/** Markdown long description of the error. Accepts a callback so that you can
/**
* Markdown long description of the error. Accepts a callback so that you can
* do things like HTTP requests.
*/
description?: string|(() => Promise<string>|string);
@@ -63,8 +68,8 @@ export interface IndieDelegate {
clearMessages(): void;
setMessages(filePath: string, messages: Message[]): void;
setAllMessages(messages: Message[]): void;
onDidUpdate(callback: () => void): EventKit.Disposable;
onDidDestroy(callback: () => void): EventKit.Disposable;
onDidUpdate(callback: () => void): Disposable;
onDidDestroy(callback: () => void): Disposable;
dispose(): void;
}
@@ -73,5 +78,5 @@ export interface LinterProvider {
scope: "file"|"project";
lintsOnChange: boolean;
grammarScopes: string[];
lint(textEditor: AtomCore.TextEditor): Message[]|void|Promise<Message[]|undefined>;
lint(textEditor: TextEditor): Message[]|void|Promise<Message[]|undefined>;
}
+23
View File
@@ -0,0 +1,23 @@
import "../index";
declare module "atom" {
interface ConfigValues {
/** Show status bar at the bottom of the workspace. */
"status-bar.isVisible": boolean;
/** Fit the status-bar to the window's full-width. */
"status-bar.fullWidth": boolean;
/**
* Format for the cursor position status bar element, where %L is the line
* number and %C is the column number.
*/
"status-bar.cursorPositionFormat": string;
/**
* Format for the selection count status bar element, where %L is the line
* count and %C is the character count.
*/
"status-bar.selectionCountFormat": string;
}
}
@@ -1,13 +1,17 @@
// Status Bar 1.x
// https://atom.io/packages/status-bar
/// <reference path="./config.d.ts" />
export interface AddTileOptions {
/** A DOM element, a jQuery object, or a model object for which a view provider
/**
* A DOM element, a jQuery object, or a model object for which a view provider
* has been registered in the the view registry.
*/
item: object;
/** Determines the placement of the tile within the status bar. Lower priority
/**
* Determines the placement of the tile within the status bar. Lower priority
* will result in closer placement to the anchor.
*/
priority: number;
@@ -25,12 +29,14 @@ export interface Tile {
}
export interface StatusBar {
/** Add a tile to the left side of the status bar. Lower priority tiles are placed
/**
* Add a tile to the left side of the status bar. Lower priority tiles are placed
* further to the left.
*/
addLeftTile(options: AddTileOptions): Tile;
/** Add a tile to the right side of the status bar. Lower priority tiles are placed
/**
* Add a tile to the right side of the status bar. Lower priority tiles are placed
* further to the right.
*/
addRightTile(options: AddTileOptions): Tile;
+4 -4
View File
@@ -8,7 +8,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
@@ -20,8 +20,8 @@
"files": [
"index.d.ts",
"atom-tests.ts",
"autocomplete-plus.d.ts",
"linter.d.ts",
"status-bar.d.ts"
"autocomplete-plus/index.d.ts",
"linter/index.d.ts",
"status-bar/index.d.ts"
]
}
+2 -30
View File
@@ -2,36 +2,8 @@
"extends": "dtslint/dt.json",
"rules": {
"await-promise": [true, "CancellablePromise"],
"class-name": true,
"indent": [true, "spaces", 4],
"jsdoc-format": true,
"max-line-length": [true, 110],
"quotemark": [true, "double", "avoid-escape"],
"trailing-comma": [true, {
"multiline": { "objects": "always", "arrays": "always", "functions": "never" },
"singleline": { "objects": "never", "arrays": "never", "functions": "never" }
}],
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-module",
"check-separator",
"check-type",
"check-typecast",
"check-rest-spread",
"check-preblock"
],
// Soon to be defaults.
"arrow-return-shorthand": [true, "multiline"],
"no-any": true,
"no-floating-promises": true,
"no-unbound-method": true,
"no-unsafe-any": true,
"number-literal-format": true,
"restrict-plus-operands": true,
"return-undefined": true,
"switch-final-break": true
"max-line-length": [true, 100],
"no-any": true
}
}
-38
View File
@@ -1,38 +0,0 @@
## Event Kit Type Definitions
TypeScript type definitions for [event-kit](https://github.com/atom/event-kit), which is published [under the same name](https://www.npmjs.com/package/event-kit) on NPM.
### Usage Notes
#### Exports
The three classes exported from this module are: [CompositeDisposable](https://github.com/atom/event-kit/blob/master/src/composite-disposable.coffee), [Disposable](https://github.com/atom/event-kit/blob/master/src/disposable.coffee), and [Emitter](https://github.com/atom/event-kit/blob/master/src/emitter.coffee).
```ts
import { CompositeDisposable, Disposable, Emitter } from "event-kit";
let subscriptions = new CompositeDisposable();
```
#### The EventKit Namespace
All types used by "event-kit" can be referenced from the EventKit namespace.
```ts
function example(disposable: EventKit.DisposableLike) {}
```
### Exposing Private Methods and Properties
[Declaration Merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) can be used to augment any of the types used within Event Kit. As an example, if we wanted to reveal the private ```getEventNames``` method within the Emitter class, then we would create a file with the following contents:
```ts
// <<filename>>.d.ts
declare namespace EventKit {
interface Emitter {
getEventNames(): string[];
}
}
```
Once this file is either referenced or included within your project, then this new member function would be freely usable on instances of the Emitter class without TypeScript reporting errors.
+9 -4
View File
@@ -1,13 +1,13 @@
import { Disposable, CompositeDisposable, Emitter } from "event-kit";
declare let bool: boolean;
declare let subscription: EventKit.Disposable;
declare let subscriptions: EventKit.CompositeDisposable;
declare let emitter: EventKit.Emitter;
declare let subscription: Disposable;
declare let subscriptions: CompositeDisposable;
declare let emitter: Emitter;
// NPM Usage Tests ============================================================
class User {
private readonly emitter: EventKit.Emitter;
private readonly emitter: Emitter;
name: string;
constructor() {
@@ -81,3 +81,8 @@ subscription = emitter.preempt("test-event", value => {});
// Event Emission
emitter.emit("test-event");
emitter.emit("test-event", 42);
async function testEmitAsync() {
await emitter.emitAsync("test-event");
await emitter.emitAsync("test-event", 42);
}
+107 -109
View File
@@ -4,121 +4,119 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
declare global {
namespace EventKit {
interface DisposableLike {
dispose(): void;
}
/** A handle to a resource that can be disposed. */
interface Disposable extends DisposableLike {
disposed: boolean;
/** A callback which will be called within dispose(). */
disposalAction?(): void;
/** Perform the disposal action, indicating that the resource associated
* with this disposable is no longer needed.
*/
dispose(): void;
}
interface DisposableStatic {
/** Ensure that Object correctly implements the Disposable contract. */
isDisposable(object: object): boolean;
/** Construct a Disposable. */
new (disposableAction?: () => void): Disposable;
}
/** An object that aggregates multiple Disposable instances together into a
* single disposable, so they can all be disposed as a group.
*/
interface CompositeDisposable extends DisposableLike {
disposed: boolean;
/** Dispose all disposables added to this composite disposable.
* If this object has already been disposed, this method has no effect.
*/
dispose(): void;
// Managing Disposables
/** Add disposables to be disposed when the composite is disposed.
* If this object has already been disposed, this method has no effect.
*/
add(...disposables: DisposableLike[]): void;
/** Remove a previously added disposable. */
remove(disposable: DisposableLike): void;
/** Alias to CompositeDisposable::remove. */
delete(disposable: DisposableLike): void;
/** Clear all disposables. They will not be disposed by the next call to
* dispose.
*/
clear(): void;
}
/** The static side to the CompositeDisposable class. */
interface CompositeDisposableStatic {
/** Construct an instance, optionally with one or more disposables. */
new (...disposables: DisposableLike[]): CompositeDisposable;
}
/** Utility class to be used when implementing event-based APIs that allows
* for handlers registered via ::on to be invoked with calls to ::emit.
*/
interface Emitter extends DisposableLike {
disposed: boolean;
/** Clear out any existing subscribers. */
clear(): void;
/** Unsubscribe all handlers. */
dispose(): boolean;
// Event Subscription
/** Registers a handler to be invoked whenever the given event is emitted. */
// tslint:disable-next-line:no-any
on(eventName: string, handler: (value: any) => void): Disposable;
/** Register the given handler function to be invoked the next time an event
* with the given name is emitted via ::emit.
*/
// tslint:disable-next-line:no-any
once(eventName: string, handler: (value: any) => void): Disposable;
/** Register the given handler function to be invoked before all other
* handlers existing at the time of subscription whenever events by the
* given name are emitted via ::emit.
*/
// tslint:disable-next-line:no-any
preempt(eventName: string, handler: (value: any) => void): Disposable;
// Event Emission
/** Invoke handlers registered via ::on for the given event name. */
// tslint:disable-next-line:no-any
emit(eventName: string, value?: any): void;
}
/** The static side to the Emitter class. */
interface EmitterStatic {
/** Construct an emitter. */
new (): Emitter;
}
}
export interface DisposableLike {
dispose(): void;
}
/** A handle to a resource that can be disposed. */
export const Disposable: EventKit.DisposableStatic;
export class Disposable implements DisposableLike {
disposed: boolean;
/** An object that aggregates multiple Disposable instances together into a
/** Ensure that Object correctly implements the Disposable contract. */
static isDisposable(object: object): boolean;
/** Construct a Disposable. */
constructor(disposableAction?: () => void);
/** A callback which will be called within dispose(). */
disposalAction?: () => void;
/**
* Perform the disposal action, indicating that the resource associated
* with this disposable is no longer needed.
*/
dispose(): void;
}
/**
* An object that aggregates multiple Disposable instances together into a
* single disposable, so they can all be disposed as a group.
*/
export const CompositeDisposable: EventKit.CompositeDisposableStatic;
export class CompositeDisposable implements DisposableLike {
disposed: boolean;
/** Utility class to be used when implementing event-based APIs that allows
/** Construct an instance, optionally with one or more disposables. */
constructor(...disposables: DisposableLike[]);
/**
* Dispose all disposables added to this composite disposable.
* If this object has already been disposed, this method has no effect.
*/
dispose(): void;
// Managing Disposables
/**
* Add disposables to be disposed when the composite is disposed.
* If this object has already been disposed, this method has no effect.
*/
add(...disposables: DisposableLike[]): void;
/** Remove a previously added disposable. */
remove(disposable: DisposableLike): void;
/** Alias to CompositeDisposable::remove. */
delete(disposable: DisposableLike): void;
/**
* Clear all disposables. They will not be disposed by the next call to
* dispose.
*/
clear(): void;
}
/**
* Allows you to strongly type event emissions across your codebase. Additional
* key:value pairings merged into this interface will result in emissions under
* the value of each key being templated by the type of the associated value.
*/
export interface Emissions {
// tslint:disable-next-line:no-any
[key: string]: any;
}
/**
* Utility class to be used when implementing event-based APIs that allows
* for handlers registered via ::on to be invoked with calls to ::emit.
*/
export const Emitter: EventKit.EmitterStatic;
export class Emitter implements DisposableLike {
disposed: boolean;
/** Construct an emitter. */
constructor();
/** Clear out any existing subscribers. */
clear(): void;
/** Unsubscribe all handlers. */
dispose(): boolean;
// Event Subscription
/** Registers a handler to be invoked whenever the given event is emitted. */
on<T extends keyof Emissions>(eventName: T, handler: (value?: Emissions[T]) => void):
Disposable;
/**
* Register the given handler function to be invoked the next time an event
* with the given name is emitted via ::emit.
*/
once<T extends keyof Emissions>(eventName: T, handler: (value?: Emissions[T]) => void):
Disposable;
/**
* Register the given handler function to be invoked before all other
* handlers existing at the time of subscription whenever events by the
* given name are emitted via ::emit.
*/
preempt<T extends keyof Emissions>(eventName: T, handler: (value?: Emissions[T]) => void):
Disposable;
// Event Emission
/** Invoke the handlers registered via ::on for the given event name. */
emit<T extends keyof Emissions>(eventName: T, value?: Emissions[T]): void;
/**
* Asynchronously invoke the handlers registered via ::on for the given event name.
* @return A promise that will be fulfilled once all handlers have been invoked.
*/
emitAsync<T extends keyof Emissions>(eventName: T, value?: Emissions[T]): Promise<void>;
}
+2 -2
View File
@@ -8,7 +8,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
@@ -21,4 +21,4 @@
"index.d.ts",
"event-kit-tests.ts"
]
}
}
+2 -30
View File
@@ -1,36 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
"class-name": true,
"indent": [true, "spaces", 4],
"jsdoc-format": true,
"max-line-length": [true, 110],
"quotemark": [true, "double", "avoid-escape"],
"trailing-comma": [true, {
"multiline": { "objects": "always", "arrays": "always", "functions": "never" },
"singleline": { "objects": "never", "arrays": "never", "functions": "never" }
}],
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-module",
"check-separator",
"check-type",
"check-typecast",
"check-rest-spread",
"check-preblock"
],
// Soon to be defaults.
"arrow-return-shorthand": [true, "multiline"],
"no-any": true,
"no-floating-promises": true,
"no-unbound-method": true,
"no-unsafe-any": true,
"number-literal-format": true,
"restrict-plus-operands": true,
"return-undefined": true,
"switch-final-break": true
"max-line-length": [true, 100],
"no-any": true
}
}
-38
View File
@@ -1,38 +0,0 @@
## First Mate Type Definitions
TypeScript type definitions for [First Mate](https://github.com/atom/first-mate), which is published as "[first-mate](https://www.npmjs.com/package/first-mate)" on NPM.
### Usage Notes
#### Exports
The three classes exported from this module are: [Grammar](https://github.com/atom/first-mate/blob/master/src/grammar.coffee), [GrammarRegistry](https://github.com/atom/first-mate/blob/master/src/grammar-registry.coffee), and [ScopeSelector](https://github.com/atom/first-mate/blob/master/src/scope-selector.coffee).
```ts
import { Grammar, GrammarRegistry, ScopeSelector } from "first-mate";
let selector = new ScopeSelector("a | b");
```
#### The FirstMate Namespace
Many of the types used by First Mate can be referenced from the FirstMate namespace.
```ts
function example(grammar: FirstMate.Grammar) {}
```
### Exposing Private Methods and Properties
[Declaration Merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) can be used to augment any of the types used within First Mate. As an example, if we wanted to reveal the private ```getMaxTokensPerLine``` method within the Grammar class, then we would create a file with the following contents:
```ts
// <<filename>>.d.ts
declare namespace FirstMate {
interface Grammar {
getMaxTokensPerLine(): number;
}
}
```
Once this file is either referenced or included within your project, then this new member function would be freely usable on instances of the Grammar class without TypeScript reporting errors.
+4 -3
View File
@@ -1,8 +1,9 @@
import { Disposable } from "event-kit";
import { GrammarRegistry, Grammar, ScopeSelector } from "first-mate";
declare let subscription: EventKit.Disposable;
declare let grammar: FirstMate.Grammar;
declare let grammars: FirstMate.Grammar[];
declare let subscription: Disposable;
declare let grammar: Grammar;
declare let grammars: Grammar[];
// NPM Examples ===============================================================
const selector = new ScopeSelector("a | b");
+244 -246
View File
@@ -4,251 +4,249 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="event-kit" />
declare global {
/** TextMate helpers. */
namespace FirstMate {
/** The option objects that the user is expected to fill out and provide to
* specific API calls.
*/
namespace Options {
interface Grammar {
name?: string;
fileTypes?: ReadonlyArray<string>;
scopeName?: string;
foldingStopMarker?: string;
maxTokensPerLine?: number;
maxLineLength?: number;
injections?: object;
injectionSelector?: ScopeSelector;
patterns?: ReadonlyArray<object>;
repository?: object;
firstLineMatch?: boolean;
}
}
/** The structures that are passed to the user by Atom following specific API calls. */
namespace Structures {
interface GrammarToken {
value: string;
scopes: string[];
}
/** Result returned by `Grammar.tokenizeLine`. */
interface TokenizeLineResult {
/** The string of text that was tokenized. */
line: string;
/** An array of integer scope ids and strings. Positive ids indicate the
* beginning of a scope, and negative tags indicate the end. To resolve ids
* to scope names, call GrammarRegistry::scopeForId with the absolute
* value of the id.
*/
tags: Array<number|string>;
/** This is a dynamic property. Invoking it will incur additional overhead,
* but will automatically translate the `tags` into token objects with `value`
* and `scopes` properties.
*/
tokens: GrammarToken[];
/** An array of rules representing the tokenized state at the end of the line.
* These should be passed back into this method when tokenizing the next line
* in the file.
*/
ruleStack: GrammarRule[];
}
interface GrammarRule {
// https://github.com/atom/first-mate/blob/v7.0.7/src/rule.coffee
// This is private. Don't go down the rabbit hole.
rule: object;
scopeName: string;
contentScopeName: string;
}
}
/** Grammar that tokenizes lines of text. */
interface Grammar {
name: string;
fileTypes: string[];
scopeName: string;
maxTokensPerLine: number;
maxLineLength: number;
// Event Subscription
onDidUpdate(callback: () => void): EventKit.Disposable;
// Tokenizing
/** Tokenize all lines in the given text.
* @param text A string containing one or more lines.
* @return An array of token arrays for each line tokenized.
*/
tokenizeLines(text: string): Structures.GrammarToken[][];
/** Tokenizes the line of text.
* @param line A string of text to tokenize.
* @param ruleStack An optional array of rules previously returned from this
* method. This should be null when tokenizing the first line in the file.
* @param firstLine A optional boolean denoting whether this is the first line
* in the file which defaults to `false`.
* @return An object representing the result of the tokenize.
*/
tokenizeLine(line: string, ruleStack?: null, firstLine?: boolean):
Structures.TokenizeLineResult;
/** Tokenizes the line of text.
* @param line A string of text to tokenize.
* @param ruleStack An optional array of rules previously returned from this
* method. This should be null when tokenizing the first line in the file.
* @param firstLine A optional boolean denoting whether this is the first line
* in the file which defaults to `false`.
* @return An object representing the result of the tokenize.
*/
tokenizeLine(line: string, ruleStack: Structures.GrammarRule[], firstLine?: false):
Structures.TokenizeLineResult;
}
/** The static side to the Grammar class. */
interface GrammarStatic {
new (registry: GrammarRegistry, options?: Options.Grammar): Grammar;
}
/** Instance side of GrammarRegistry class. */
interface GrammarRegistry {
maxTokensPerLine: number;
maxLineLength: number;
// Event Subscription
/** Invoke the given callback when a grammar is added to the registry.
* @param callback The callback to be invoked whenever a grammar is added.
* @return A Disposable on which `.dispose()` can be called to unsubscribe.
*/
onDidAddGrammar(callback: (grammar: Grammar) => void): EventKit.Disposable;
/** Invoke the given callback when a grammar is updated due to a grammar it
* depends on being added or removed from the registry.
* @param callback The callback to be invoked whenever a grammar is updated.
* @return A Disposable on which `.dispose()` can be called to unsubscribe.
*/
onDidUpdateGrammar(callback: (grammar: Grammar) => void): EventKit.Disposable;
// Managing Grammars
/** Get all the grammars in this registry.
* @return A non-empty array of Grammar instances.
*/
getGrammars(): Grammar[];
/** Get a grammar with the given scope name.
* @param scopeName A string such as `source.js`.
* @return A Grammar or undefined.
*/
grammarForScopeName(scopeName: string): Grammar|undefined;
/** Add a grammar to this registry.
* A 'grammar-added' event is emitted after the grammar is added.
* @param grammar The Grammar to add. This should be a value previously returned
* from ::readGrammar or ::readGrammarSync.
* @return Returns a Disposable on which `.dispose()` can be called to remove
* the grammar.
*/
addGrammar(grammar: Grammar): EventKit.Disposable;
/** Remove the given grammar from this registry.
* @param grammar The grammar to remove. This should be a grammar previously
* added to the registry from ::addGrammar.
*/
removeGrammar(grammar: Grammar): void;
/** Remove the grammar with the given scope name.
* @param scopeName A string such as `source.js`.
* @return Returns the removed Grammar or undefined.
*/
removeGrammarForScopeName(scopeName: string): Grammar|undefined;
/** Read a grammar synchronously but don't add it to the registry.
* @param grammarPath The absolute file path to a grammar.
* @return The newly loaded Grammar.
*/
readGrammarSync(grammarPath: string): Grammar;
/** Read a grammar asynchronously but don't add it to the registry.
* @param grammarPath The absolute file path to the grammar.
* @param callback The function to be invoked once the Grammar has been read in.
*/
readGrammar(grammarPath: string, callback: (error: Error|null, grammar?: Grammar) =>
void): void;
/** Read a grammar synchronously and add it to this registry.
* @param grammarPath The absolute file path to the grammar.
* @return The newly loaded Grammar.
*/
loadGrammarSync(grammarPath: string): Grammar;
/** Read a grammar asynchronously and add it to the registry.
* @param grammarPath The absolute file path to the grammar.
* @param callback The function to be invoked once the Grammar has been read in
* and added to the registry.
*/
loadGrammar(grammarPath: string, callback: (error: Error|null, grammar?: Grammar) =>
void): void;
/** Convert compact tags representation into convenient, space-inefficient tokens.
* @param lineText The text of the tokenized line.
* @param tags The tags returned from a call to Grammar::tokenizeLine().
* @return An array of Token instances decoded from the given tags.
*/
decodeTokens(lineText: string, tags: Array<number|string>): Structures.GrammarToken[];
}
/** The static side to the GrammarRegistry class. */
interface GrammarRegistryStatic {
new (options?: { maxTokensPerLine?: number, maxLineLength?: number }):
GrammarRegistry;
}
interface ScopeSelector {
/** Check if this scope selector matches the scopes.
* @param scopes A single scope or an array of them to be compared against.
* @return A boolean indicating whether or not this ScopeSelector matched.
*/
matches(scopes: string|ReadonlyArray<string>): boolean;
/** Gets the prefix of this scope selector.
* @param scopes The scopes to match a prefix against.
* @return The matching prefix, if there is one.
*/
getPrefix(scopes: string|ReadonlyArray<string>): string|undefined;
/** Convert this TextMate scope selector to a CSS selector.
* @return A string with the CSSSelector representation of this ScopeSelector.
*/
toCssSelector(): string;
/** Convert this TextMate scope selector to a CSS selector, prefixing scopes
* with `syntax--`.
* @return A string with the syntax-specific CSSSelector representation of this
* ScopeSelector.
*/
toCssSyntaxSelector(): string;
}
/** The static side to the ScopeSelector class. */
interface ScopeSelectorStatic {
/** Create a new scope selector.
* @param source The string to parse as a scope selector.
* @return A newly constructed ScopeSelector.
*/
new (source: string): ScopeSelector;
}
}
}
/** Registry containing one or more grammars. */
export const GrammarRegistry: FirstMate.GrammarRegistryStatic;
export const ScopeSelector: FirstMate.ScopeSelectorStatic;
import { Disposable } from "event-kit";
/** Grammar that tokenizes lines of text. */
export const Grammar: FirstMate.GrammarStatic;
export class Grammar {
name: string;
fileTypes: string[];
scopeName: string;
maxTokensPerLine: number;
maxLineLength: number;
constructor(registry: GrammarRegistry, options?: GrammarOptions);
// Event Subscription
onDidUpdate(callback: () => void): Disposable;
// Tokenizing
/**
* Tokenize all lines in the given text.
* @param text A string containing one or more lines.
* @return An array of token arrays for each line tokenized.
*/
tokenizeLines(text: string): GrammarToken[][];
/**
* Tokenizes the line of text.
* @param line A string of text to tokenize.
* @param ruleStack An optional array of rules previously returned from this
* method. This should be null when tokenizing the first line in the file.
* @param firstLine A optional boolean denoting whether this is the first line
* in the file which defaults to `false`.
* @return An object representing the result of the tokenize.
*/
tokenizeLine(line: string, ruleStack?: null, firstLine?: boolean): TokenizeLineResult;
/**
* Tokenizes the line of text.
* @param line A string of text to tokenize.
* @param ruleStack An optional array of rules previously returned from this
* method. This should be null when tokenizing the first line in the file.
* @param firstLine A optional boolean denoting whether this is the first line
* in the file which defaults to `false`.
* @return An object representing the result of the tokenize.
*/
tokenizeLine(line: string, ruleStack: GrammarRule[], firstLine?: false):
TokenizeLineResult;
}
/** Instance side of GrammarRegistry class. */
export class GrammarRegistry {
maxTokensPerLine: number;
maxLineLength: number;
constructor(options?: { maxTokensPerLine?: number, maxLineLength?: number });
// Event Subscription
/**
* Invoke the given callback when a grammar is added to the registry.
* @param callback The callback to be invoked whenever a grammar is added.
* @return A Disposable on which `.dispose()` can be called to unsubscribe.
*/
onDidAddGrammar(callback: (grammar: Grammar) => void): Disposable;
/**
* Invoke the given callback when a grammar is updated due to a grammar it
* depends on being added or removed from the registry.
* @param callback The callback to be invoked whenever a grammar is updated.
* @return A Disposable on which `.dispose()` can be called to unsubscribe.
*/
onDidUpdateGrammar(callback: (grammar: Grammar) => void): Disposable;
// Managing Grammars
/**
* Get all the grammars in this registry.
* @return A non-empty array of Grammar instances.
*/
getGrammars(): Grammar[];
/**
* Get a grammar with the given scope name.
* @param scopeName A string such as `source.js`.
* @return A Grammar or undefined.
*/
grammarForScopeName(scopeName: string): Grammar|undefined;
/**
* Add a grammar to this registry.
* A 'grammar-added' event is emitted after the grammar is added.
* @param grammar The Grammar to add. This should be a value previously returned
* from ::readGrammar or ::readGrammarSync.
* @return Returns a Disposable on which `.dispose()` can be called to remove
* the grammar.
*/
addGrammar(grammar: Grammar): Disposable;
/**
* Remove the given grammar from this registry.
* @param grammar The grammar to remove. This should be a grammar previously
* added to the registry from ::addGrammar.
*/
removeGrammar(grammar: Grammar): void;
/**
* Remove the grammar with the given scope name.
* @param scopeName A string such as `source.js`.
* @return Returns the removed Grammar or undefined.
*/
removeGrammarForScopeName(scopeName: string): Grammar|undefined;
/**
* Read a grammar synchronously but don't add it to the registry.
* @param grammarPath The absolute file path to a grammar.
* @return The newly loaded Grammar.
*/
readGrammarSync(grammarPath: string): Grammar;
/**
* Read a grammar asynchronously but don't add it to the registry.
* @param grammarPath The absolute file path to the grammar.
* @param callback The function to be invoked once the Grammar has been read in.
*/
readGrammar(grammarPath: string, callback: (error: Error|null, grammar?: Grammar) =>
void): void;
/**
* Read a grammar synchronously and add it to this registry.
* @param grammarPath The absolute file path to the grammar.
* @return The newly loaded Grammar.
*/
loadGrammarSync(grammarPath: string): Grammar;
/**
* Read a grammar asynchronously and add it to the registry.
* @param grammarPath The absolute file path to the grammar.
* @param callback The function to be invoked once the Grammar has been read in
* and added to the registry.
*/
loadGrammar(grammarPath: string, callback: (error: Error|null, grammar?: Grammar) =>
void): void;
/**
* Convert compact tags representation into convenient, space-inefficient tokens.
* @param lineText The text of the tokenized line.
* @param tags The tags returned from a call to Grammar::tokenizeLine().
* @return An array of Token instances decoded from the given tags.
*/
decodeTokens(lineText: string, tags: Array<number|string>): GrammarToken[];
}
export class ScopeSelector {
/**
* Create a new scope selector.
* @param source The string to parse as a scope selector.
* @return A newly constructed ScopeSelector.
*/
constructor(source: string);
/**
* Check if this scope selector matches the scopes.
* @param scopes A single scope or an array of them to be compared against.
* @return A boolean indicating whether or not this ScopeSelector matched.
*/
matches(scopes: string|ReadonlyArray<string>): boolean;
/**
* Gets the prefix of this scope selector.
* @param scopes The scopes to match a prefix against.
* @return The matching prefix, if there is one.
*/
getPrefix(scopes: string|ReadonlyArray<string>): string|undefined;
/**
* Convert this TextMate scope selector to a CSS selector.
* @return A string with the CSSSelector representation of this ScopeSelector.
*/
toCssSelector(): string;
/**
* Convert this TextMate scope selector to a CSS selector, prefixing scopes
* with `syntax--`.
* @return A string with the syntax-specific CSSSelector representation of this
* ScopeSelector.
*/
toCssSyntaxSelector(): string;
}
// Options ====================================================================
// The option objects that the user is expected to fill out and provide to
// specific API calls.
export interface GrammarOptions {
name?: string;
fileTypes?: ReadonlyArray<string>;
scopeName?: string;
foldingStopMarker?: string;
maxTokensPerLine?: number;
maxLineLength?: number;
injections?: object;
injectionSelector?: ScopeSelector;
patterns?: ReadonlyArray<object>;
repository?: object;
firstLineMatch?: boolean;
}
// Structures =================================================================
// The structures that are passed to the user by Atom following specific API calls.
export interface GrammarToken {
value: string;
scopes: string[];
}
/** Result returned by `Grammar.tokenizeLine`. */
export interface TokenizeLineResult {
/** The string of text that was tokenized. */
line: string;
/**
* An array of integer scope ids and strings. Positive ids indicate the
* beginning of a scope, and negative tags indicate the end. To resolve ids
* to scope names, call GrammarRegistry::scopeForId with the absolute
* value of the id.
*/
tags: Array<number|string>;
/**
* This is a dynamic property. Invoking it will incur additional overhead,
* but will automatically translate the `tags` into token objects with `value`
* and `scopes` properties.
*/
tokens: GrammarToken[];
/**
* An array of rules representing the tokenized state at the end of the line.
* These should be passed back into this method when tokenizing the next line
* in the file.
*/
ruleStack: GrammarRule[];
}
export interface GrammarRule {
// https://github.com/atom/first-mate/blob/v7.0.7/src/rule.coffee
// This is private. Don't go down the rabbit hole.
rule: object;
scopeName: string;
contentScopeName: string;
}
+2 -2
View File
@@ -8,7 +8,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
@@ -21,4 +21,4 @@
"index.d.ts",
"first-mate-tests.ts"
]
}
}
+2 -30
View File
@@ -1,36 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
"class-name": true,
"indent": [true, "spaces", 4],
"jsdoc-format": true,
"max-line-length": [true, 110],
"quotemark": [true, "double", "avoid-escape"],
"trailing-comma": [true, {
"multiline": { "objects": "always", "arrays": "always", "functions": "never" },
"singleline": { "objects": "never", "arrays": "never", "functions": "never" }
}],
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-module",
"check-separator",
"check-type",
"check-typecast",
"check-rest-spread",
"check-preblock"
],
// Soon to be defaults.
"arrow-return-shorthand": [true, "multiline"],
"no-any": true,
"no-floating-promises": true,
"no-unbound-method": true,
"no-unsafe-any": true,
"number-literal-format": true,
"restrict-plus-operands": true,
"return-undefined": true,
"switch-final-break": true
"max-line-length": [true, 100],
"no-any": true
}
}
-44
View File
@@ -1,44 +0,0 @@
## Path Watcher Node Type Definitions
TypeScript type definitions for [Path Watcher Node], which is published as "[pathwatcher](https://www.npmjs.com/package/pathwatcher)" on NPM.
### Usage Notes
#### Exports
The two classes exported from this module are: [File](https://github.com/atom/node-pathwatcher/blob/master/src/file.coffee) and [Directory](https://github.com/atom/node-pathwatcher/blob/master/src/directory.coffee).
```ts
import { File, Directory } from "text-buffer";
```
Additionally, the following functions are exported as well:
```ts
watch(): PathWatcher.PathWatcher;
closeAllWatchers(): void;
getWatchedPaths(): string[];
```
#### The PathWatcher Namespace
All types used by Path Watcher can be referenced from the PathWatcher namespace.
```ts
function example(file: PathWatcher.File) {}
```
### Exposing Private Methods and Properties
[Declaration Merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) can be used to augment any of the types used within Path Watcher. As an example, if we wanted to reveal the private ```setPath``` method within the File class, then we would create a file with the following contents:
```ts
// <<filename>>.d.ts
declare namespace PathWatcher {
interface File {
setPath(path: string): void;
}
}
```
Once this file is either referenced or included within your project, then this new member function would be freely usable on instances of the File class without TypeScript reporting errors.
+229 -228
View File
@@ -5,236 +5,237 @@
// TypeScript Version: 2.2
/// <reference types="node" />
/// <reference types="event-kit" />
import { Disposable } from "event-kit";
import { ReadStream, WriteStream } from "fs";
declare global {
namespace PathWatcher {
/** The event objects that are passed into the callbacks which the user provides to
* specific API calls.
*/
namespace Events {
interface PathWatchErrorThrown {
/** The error object. */
error: Error;
/** Call this function to indicate you have handled the error.
* The error will not be thrown if this function is called.
*/
handle(): void;
}
interface WatchedFilePathChangedEvent {
event: string;
newFilePath: string;
}
}
/** Represents an individual file that can be watched, read from, and written to. */
interface File {
// Properties
realPath: string|null;
path: string;
symlink: boolean;
// Construction
/** Creates the file on disk that corresponds to ::getPath() if no such file
* already exists.
*/
create(): Promise<boolean>;
// Event Subscription
/** Invoke the given callback when the file's contents change. */
onDidChange(callback: () => void): EventKit.Disposable;
/** Invoke the given callback when the file's path changes. */
onDidRename(callback: () => void): EventKit.Disposable;
/** Invoke the given callback when the file is deleted. */
onDidDelete(callback: () => void): EventKit.Disposable;
/** Invoke the given callback when there is an error with the watch. When
* your callback has been invoked, the file will have unsubscribed from the
* file watches.
*/
onWillThrowWatchError(callback: (errorObject: Events.PathWatchErrorThrown) =>
void): EventKit.Disposable;
// File Metadata
/** Returns a boolean, always true. */
isFile(): boolean;
/** Returns a boolean, always false. */
isDirectory(): boolean;
/** Returns a boolean indicating whether or not this is a symbolic link. */
isSymbolicLink(): boolean;
/** Returns a promise that resolves to a boolean, true if the file exists,
* false otherwise.
*/
exists(): Promise<boolean>;
/** Returns a boolean, true if the file exists, false otherwise. */
existsSync(): boolean;
/** Get the SHA-1 digest of this file. */
getDigest(): Promise<string>;
/** Get the SHA-1 digest of this file. */
getDigestSync(): string;
/** Sets the file's character set encoding name. */
setEncoding(encoding: string): void;
/** Returns the string encoding name for this file (default: "utf8"). */
getEncoding(): string;
// Managing Paths
/** Returns the string path for the file. */
getPath(): string;
/** Returns this file's completely resolved string path. */
getRealPathSync(): string;
/** Returns a promise that resolves to the file's completely resolved
* string path.
*/
getRealPath(): Promise<string>;
/** Return the string filename without any directory information. */
getBaseName(): string;
// Traversing
/** Return the Directory that contains this file. */
getParent(): Directory;
// Reading and Writing
/** Reads the contents of the file. */
read(flushCache?: boolean): Promise<string>;
/** Returns a stream to read the content of the file. */
createReadStream(): ReadStream;
/** Overwrites the file with the given text. */
write(text: string): Promise<undefined>;
/** Returns a stream to write content to the file. */
createWriteStream(): WriteStream;
/** Overwrites the file with the given text. */
writeSync(text: string): undefined;
}
/** The static side to the File class. */
interface FileStatic {
/** Configures a new File instance, no files are accessed. */
new (filePath: string, symlink?: boolean): File;
}
/** Represents a directory on disk that can be watched for changes. */
interface Directory {
// Properties
realPath: string|null;
path: string;
symlink: boolean;
// Construction
/** Creates the directory on disk that corresponds to ::getPath() if no such
* directory already exists.
*/
create(mode?: number): Promise<boolean>;
// Event Subscription
/** Invoke the given callback when the directory's contents change. */
onDidChange(callback: () => void): EventKit.Disposable;
// Directory Metadata
/** Returns a boolean, always false. */
isFile(): boolean;
/** Returns a roolean, always true. */
isDirectory(): boolean;
/** Returns a boolean indicating whether or not this is a symbolic link. */
isSymbolicLink(): boolean;
/** Returns a promise that resolves to a boolean, true if the directory\
* exists, false otherwise.
*/
exists(): Promise<boolean>;
/** Returns a boolean, true if the directory exists, false otherwise. */
existsSync(): boolean;
/** Return a boolean, true if this Directory is the root directory of the
* filesystem, or false if it isn't.
*/
isRoot(): boolean;
// Managing Paths
/** This may include unfollowed symlinks or relative directory entries.
* Or it may be fully resolved, it depends on what you give it.
*/
getPath(): string;
/** All relative directory entries are removed and symlinks are resolved to
* their final destination.
*/
getRealPathSync(): string;
/** Returns the string basename of the directory. */
getBaseName(): string;
/** Returns the relative string path to the given path from this directory. */
relativize(fullPath: string): string;
// Traversing
/** Traverse to the parent directory. */
getParent(): Directory;
/** Traverse within this Directory to a child File. This method doesn't actually
* check to see if the File exists, it just creates the File object.
*/
getFile(filename: string): File;
/** Traverse within this a Directory to a child Directory. This method doesn't actually
* check to see if the Directory exists, it just creates the Directory object.
*/
getSubdirectory(dirname: string): Directory;
/** Reads file entries in this directory from disk synchronously. */
getEntriesSync(): Array<File|Directory>;
/** Reads file entries in this directory from disk asynchronously. */
getEntries(callback: (error: Error, entries: Array<File|Directory>) => void): void;
/** Determines if the given path (real or symbolic) is inside this directory. This
* method does not actually check if the path exists, it just checks if the path
* is under this directory.
*/
contains(pathToCheck: string): boolean;
}
/** The static side to the Directory class. */
interface DirectoryStatic {
/** Configures a new Directory instance, no files are accessed. */
new (directoryPath: string, symlink?: boolean): Directory;
}
interface PathWatcher {
onDidChange(callback: (change: Events.WatchedFilePathChangedEvent) => void):
EventKit.Disposable;
close(): void;
}
}
}
export let File: PathWatcher.FileStatic;
export let Directory: PathWatcher.DirectoryStatic;
export function watch(): PathWatcher.PathWatcher;
export function watch(): PathWatcher;
export function closeAllWatchers(): void;
export function getWatchedPaths(): string[];
/** Represents an individual file that can be watched, read from, and written to. */
export class File {
// Properties
realPath: string|null;
path: string;
symlink: boolean;
// Construction
/** Configures a new File instance, no files are accessed. */
constructor(filePath: string, symlink?: boolean);
/**
* Creates the file on disk that corresponds to ::getPath() if no such file
* already exists.
*/
create(): Promise<boolean>;
// Event Subscription
/** Invoke the given callback when the file's contents change. */
onDidChange(callback: () => void): Disposable;
/** Invoke the given callback when the file's path changes. */
onDidRename(callback: () => void): Disposable;
/** Invoke the given callback when the file is deleted. */
onDidDelete(callback: () => void): Disposable;
/**
* Invoke the given callback when there is an error with the watch. When
* your callback has been invoked, the file will have unsubscribed from the
* file watches.
*/
onWillThrowWatchError(callback: (errorObject: PathWatchErrorThrownEvent) =>
void): Disposable;
// File Metadata
/** Returns a boolean, always true. */
isFile(): boolean;
/** Returns a boolean, always false. */
isDirectory(): boolean;
/** Returns a boolean indicating whether or not this is a symbolic link. */
isSymbolicLink(): boolean;
/**
* Returns a promise that resolves to a boolean, true if the file exists,
* false otherwise.
*/
exists(): Promise<boolean>;
/** Returns a boolean, true if the file exists, false otherwise. */
existsSync(): boolean;
/** Get the SHA-1 digest of this file. */
getDigest(): Promise<string>;
/** Get the SHA-1 digest of this file. */
getDigestSync(): string;
/** Sets the file's character set encoding name. */
setEncoding(encoding: string): void;
/** Returns the string encoding name for this file (default: "utf8"). */
getEncoding(): string;
// Managing Paths
/** Returns the string path for the file. */
getPath(): string;
/** Returns this file's completely resolved string path. */
getRealPathSync(): string;
/**
* Returns a promise that resolves to the file's completely resolved
* string path.
*/
getRealPath(): Promise<string>;
/** Return the string filename without any directory information. */
getBaseName(): string;
// Traversing
/** Return the Directory that contains this file. */
getParent(): Directory;
// Reading and Writing
/** Reads the contents of the file. */
read(flushCache?: boolean): Promise<string>;
/** Returns a stream to read the content of the file. */
createReadStream(): ReadStream;
/** Overwrites the file with the given text. */
write(text: string): Promise<undefined>;
/** Returns a stream to write content to the file. */
createWriteStream(): WriteStream;
/** Overwrites the file with the given text. */
writeSync(text: string): undefined;
}
/** Represents a directory on disk that can be watched for changes. */
export class Directory {
// Properties
realPath: string|null;
path: string;
symlink: boolean;
// Construction
/** Configures a new Directory instance, no files are accessed. */
constructor(directoryPath: string, symlink?: boolean);
/**
* Creates the directory on disk that corresponds to ::getPath() if no such
* directory already exists.
*/
create(mode?: number): Promise<boolean>;
// Event Subscription
/** Invoke the given callback when the directory's contents change. */
onDidChange(callback: () => void): Disposable;
// Directory Metadata
/** Returns a boolean, always false. */
isFile(): boolean;
/** Returns a roolean, always true. */
isDirectory(): boolean;
/** Returns a boolean indicating whether or not this is a symbolic link. */
isSymbolicLink(): boolean;
/**
* Returns a promise that resolves to a boolean, true if the directory
* exists, false otherwise.
*/
exists(): Promise<boolean>;
/** Returns a boolean, true if the directory exists, false otherwise. */
existsSync(): boolean;
/**
* Return a boolean, true if this Directory is the root directory of the
* filesystem, or false if it isn't.
*/
isRoot(): boolean;
// Managing Paths
/**
* This may include unfollowed symlinks or relative directory entries.
* Or it may be fully resolved, it depends on what you give it.
*/
getPath(): string;
/**
* All relative directory entries are removed and symlinks are resolved to
* their final destination.
*/
getRealPathSync(): string;
/** Returns the string basename of the directory. */
getBaseName(): string;
/** Returns the relative string path to the given path from this directory. */
relativize(fullPath: string): string;
// Traversing
/** Traverse to the parent directory. */
getParent(): Directory;
/**
* Traverse within this Directory to a child File. This method doesn't actually
* check to see if the File exists, it just creates the File object.
*/
getFile(filename: string): File;
/**
* Traverse within this a Directory to a child Directory. This method doesn't actually
* check to see if the Directory exists, it just creates the Directory object.
*/
getSubdirectory(dirname: string): Directory;
/** Reads file entries in this directory from disk synchronously. */
getEntriesSync(): Array<File|Directory>;
/** Reads file entries in this directory from disk asynchronously. */
getEntries(callback: (error: Error, entries: Array<File|Directory>) => void): void;
/**
* Determines if the given path (real or symbolic) is inside this directory. This
* method does not actually check if the path exists, it just checks if the path
* is under this directory.
*/
contains(pathToCheck: string): boolean;
}
// Events =====================================================================
// The event objects that are passed into the callbacks which the user provides
// to specific API calls.
export interface PathWatchErrorThrownEvent {
/** The error object. */
error: Error;
/**
* Call this function to indicate you have handled the error.
* The error will not be thrown if this function is called.
*/
handle(): void;
}
export interface WatchedFilePathChangedEvent {
event: string;
newFilePath: string;
}
// Structures =================================================================
// The structures that are passed to the user by Atom following specific API calls.
export interface PathWatcher {
onDidChange(callback: (change: WatchedFilePathChangedEvent) => void): Disposable;
close(): void;
}
+4 -3
View File
@@ -1,11 +1,12 @@
import { Disposable } from "event-kit";
import { File, Directory } from "pathwatcher";
let bool: boolean;
let str: string;
let sub: EventKit.Disposable;
let sub: Disposable;
let file: PathWatcher.File;
let dir: PathWatcher.Directory;
let file: File;
let dir: Directory;
// File =======================================================================
// Construction
+2 -2
View File
@@ -7,7 +7,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
@@ -20,4 +20,4 @@
"index.d.ts",
"pathwatcher-tests.ts"
]
}
}
+1 -29
View File
@@ -1,36 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
"class-name": true,
"indent": [true, "spaces", 4],
"jsdoc-format": true,
"max-line-length": [true, 100],
"quotemark": [true, "double", "avoid-escape"],
"trailing-comma": [true, {
"multiline": { "objects": "always", "arrays": "always", "functions": "never" },
"singleline": { "objects": "never", "arrays": "never", "functions": "never" }
}],
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-module",
"check-separator",
"check-type",
"check-typecast",
"check-rest-spread",
"check-preblock"
],
// Soon to be defaults.
"arrow-return-shorthand": [true, "multiline"],
"no-any": true,
"no-floating-promises": true,
"no-unbound-method": true,
"no-unsafe-any": true,
"number-literal-format": true,
"restrict-plus-operands": true,
"return-undefined": true,
"switch-final-break": true
"no-any": true
}
}
+265 -155
View File
@@ -4,12 +4,13 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="event-kit" />
/// <reference types="pathwatcher" />
import { Disposable } from "event-kit";
import { File } from "pathwatcher";
declare global {
namespace TextBuffer {
/** The event objects that are passed into the callbacks which the user provides to
/**
* The event objects that are passed into the callbacks which the user provides to
* specific API calls.
*/
namespace Events {
@@ -17,7 +18,8 @@ declare global {
/** The error object. */
error: Error;
/** Call this function to indicate you have handled the error.
/**
* Call this function to indicate you have handled the error.
* The error will not be thrown if this function is called.
*/
handle(): void;
@@ -53,17 +55,20 @@ declare global {
/** Boolean indicating whether the marker now has a tail. */
hasTail: boolean;
/** -DEPRECATED- Object containing the marker's custom properties before the change.
/**
* Object containing the marker's custom properties before the change.
* @deprecated
*/
oldProperties: object;
/** -DEPRECATED- Object containing the marker's custom properties after the change.
/**
* Object containing the marker's custom properties after the change.
* @deprecated
*/
newProperties: object;
/** Boolean indicating whether this change was caused by a textual
/**
* 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.
*/
@@ -107,17 +112,20 @@ declare global {
/** Boolean indicating whether the marker now has a tail */
hasTail: boolean;
/** -DEPRECATED- Object containing the marker's custom properties before the change.
/**
* Object containing the marker's custom properties before the change.
* @deprecated
*/
oldProperties: object;
/** -DEPRECATED- Object containing the marker's custom properties after the change.
/**
* Object containing the marker's custom properties after the change.
* @deprecated
*/
newProperties: object;
/** Boolean indicating whether this change was caused by a textual change to the
/**
* 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.
*/
textChanged: boolean;
@@ -147,7 +155,8 @@ declare global {
}
}
/** The option objects that the user is expected to fill out and provide to
/**
* The option objects that the user is expected to fill out and provide to
* specific API calls.
*/
namespace Options {
@@ -155,7 +164,8 @@ declare global {
/** The file's encoding. */
encoding?: string;
/** A function that returns a boolean indicating whether the buffer should
/**
* A function that returns a boolean indicating whether the buffer should
* be destroyed if its file is deleted.
*/
shouldDestroyOnFileDelete?(): boolean;
@@ -227,12 +237,14 @@ declare global {
/** Only include markers ending at this row in screen coordinates. */
endScreenRow?: number;
/** Only include markers intersecting this Array of [startRow, endRow] in
/**
* Only include markers intersecting this Array of [startRow, endRow] in
* buffer coordinates.
*/
intersectsBufferRowRange?: [number, number];
/** Only include markers intersecting this Array of [startRow, endRow] in
/**
* Only include markers intersecting this Array of [startRow, endRow] in
* screen coordinates.
*/
intersectsScreenRowRange?: [number, number];
@@ -266,12 +278,16 @@ declare global {
/** Determines the rules by which changes to the buffer invalidate the marker. */
invalidate?: "never"|"surround"|"overlap"|"inside"|"touch";
/** Indicates whether insertions at the start or end of the marked range should
/**
* Indicates whether insertions at the start or end of the marked range should
* be interpreted as happening outside the marker.
*/
exclusive?: boolean;
/** -DEPRECATED- Custom properties to be associated with the marker. */
/**
* Custom properties to be associated with the marker.
* @deprecated
*/
properties?: object;
}
@@ -313,7 +329,8 @@ declare global {
}
}
/** Represents a buffer annotation that remains logically stationary even as
/**
* Represents a buffer annotation that remains logically stationary even as
* the buffer changes.
*/
interface Marker {
@@ -326,7 +343,8 @@ declare global {
properties: object;
// Lifecycle
/** Creates and returns a new Marker with the same properties as this
/**
* Creates and returns a new Marker with the same properties as this
* marker.
*/
copy(options?: Options.CopyMarker): Marker;
@@ -336,10 +354,10 @@ declare global {
// Event Subscription
/** Invoke the given callback when the marker is destroyed. */
onDidDestroy(callback: () => void): EventKit.Disposable;
onDidDestroy(callback: () => void): Disposable;
/** Invoke the given callback when the state of the marker changes. */
onDidChange(callback: (event: Events.MarkerChanged) => void): EventKit.Disposable;
onDidChange(callback: (event: Events.MarkerChanged) => void): Disposable;
// Marker Details
/** Returns the current range of the marker. The range is immutable. */
@@ -351,12 +369,14 @@ declare global {
/** Returns a point representing the marker's current tail position. */
getTailPosition(): Point;
/** Returns a point representing the start position of the marker, which
/**
* Returns a point representing the start position of the marker, which
* could be the head or tail position, depending on its orientation.
*/
getStartPosition(): Point;
/** Returns a point representing the end position of the marker, which
/**
* Returns a point representing the end position of the marker, which
* could be the head or tail position, depending on its orientation.
*/
getEndPosition(): Point;
@@ -373,7 +393,8 @@ declare global {
/** Is the marker destroyed? */
isDestroyed(): boolean;
/** Returns a boolean indicating whether changes that occur exactly at
/**
* Returns a boolean indicating whether changes that occur exactly at
* the marker's head or tail cause it to move.
*/
isExclusive(): boolean;
@@ -382,39 +403,46 @@ declare global {
getInvalidationStrategy(): string;
// Mutating Markers
/** Sets the range of the marker.
/**
* Sets the range of the marker.
* Returns a boolean indicating whether or not the marker was updated.
*/
setRange(range: RangeCompatible, params?: { reversed?: boolean, exclusive?:
boolean }): boolean;
/** Sets the head position of the marker.
/**
* Sets the head position of the marker.
* Returns a boolean indicating whether or not the marker was updated.
*/
setHeadPosition(position: PointCompatible): boolean;
/** Sets the tail position of the marker.
/**
* Sets the tail position of the marker.
* Returns a boolean indicating whether or not the marker was updated.
*/
setTailPosition(position: PointCompatible): boolean;
/** Removes the marker's tail.
/**
* Removes the marker's tail.
* Returns a boolean indicating whether or not the marker was updated.
*/
clearTail(): boolean;
/** Plants the marker's tail at the current head position.
/**
* Plants the marker's tail at the current head position.
* Returns a boolean indicating whether or not the marker was updated.
*/
plantTail(): boolean;
// Comparison
/** Returns a boolean indicating whether this marker is equivalent to
/**
* Returns a boolean indicating whether this marker is equivalent to
* another marker, meaning they have the same range and options.
*/
isEqual(other: Marker): boolean;
/** Compares this marker to another based on their ranges.
/**
* Compares this marker to another based on their ranges.
* Returns "-1" if this marker precedes the argument.
* Returns "0" if this marker is equivalent to the argument.
* Returns "1" if this marker follows the argument.
@@ -452,36 +480,45 @@ declare global {
// Marker Creation
/** Create a marker with the given range. */
markRange(range: RangeCompatible, options?: { reversed?: boolean, invalidate?:
"never"|"surround"|"overlap"|"inside"|"touch", exclusive?: boolean }): Marker;
markRange(range: RangeCompatible, options?: {
reversed?: boolean,
invalidate?: "never"|"surround"|"overlap"|"inside"|"touch",
exclusive?: boolean,
}): Marker;
/** Create a marker at with its head at the given position with no tail. */
markPosition(position: PointCompatible, options?: { invalidate?: "never"|"surround"
|"overlap"|"inside"|"touch", exclusive?: boolean }): Marker;
markPosition(position: PointCompatible, options?: {
invalidate?: "never"|"surround"|"overlap"|"inside"|"touch",
exclusive?: boolean,
}): Marker;
// Event Subscription
/** Subscribe to be notified asynchronously whenever markers are created,
/**
* Subscribe to be notified asynchronously whenever markers are created,
* updated, or destroyed on this layer.
*/
onDidUpdate(callback: () => void): EventKit.Disposable;
onDidUpdate(callback: () => void): Disposable;
/** Subscribe to be notified synchronously whenever markers are created on
/**
* Subscribe to be notified synchronously whenever markers are created on
* this layer.
*/
onDidCreateMarker(callback: (marker: Marker) => void): EventKit.Disposable;
onDidCreateMarker(callback: (marker: Marker) => void): Disposable;
/** Subscribe to be notified synchronously when this layer is destroyed. */
onDidDestroy(callback: () => void): EventKit.Disposable;
onDidDestroy(callback: () => void): Disposable;
}
/** Represents a buffer annotation that remains logically stationary even as the
/**
* 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.
*/
interface DisplayMarker {
// Construction and Destruction
/** Destroys the marker, causing it to emit the 'destroyed' event. Once destroyed,
/**
* Destroys the marker, causing it to emit the 'destroyed' event. Once destroyed,
* a marker cannot be restored by undo/redo operations.
*/
destroy(): void;
@@ -492,18 +529,20 @@ declare global {
// Event Subscription
/** Invoke the given callback when the state of the marker changes. */
onDidChange(callback: (event: Events.DisplayMarkerChanged) => void):
EventKit.Disposable;
Disposable;
/** Invoke the given callback when the marker is destroyed. */
onDidDestroy(callback: () => void): EventKit.Disposable;
onDidDestroy(callback: () => void): Disposable;
// TextEditorMarker Details
/** Returns a boolean indicating whether the marker is valid. Markers can be
/**
* Returns a boolean indicating whether the marker is valid. Markers can be
* invalidated when a region surrounding them in the buffer is changed.
*/
isValid(): boolean;
/** Returns a boolean indicating whether the marker has been destroyed. A marker
/**
* Returns a boolean indicating whether the marker has been destroyed. A marker
* can be invalid without being destroyed, in which case undoing the invalidating
* operation would restore the marker.
*/
@@ -512,12 +551,14 @@ declare global {
/** Returns a boolean indicating whether the head precedes the tail. */
isReversed(): boolean;
/** Returns a boolean indicating whether changes that occur exactly at the marker's
/**
* Returns a boolean indicating whether changes that occur exactly at the marker's
* head or tail cause it to move.
*/
isExclusive(): boolean;
/** Get the invalidation strategy for this marker.
/**
* Get the invalidation strategy for this marker.
* Valid values include: never, surround, overlap, inside, and touch.
*/
getInvalidationStrategy(): string;
@@ -535,7 +576,8 @@ declare global {
/** Compares this marker to another based on their ranges. */
compare(other: DisplayMarker): number;
/** Returns a boolean indicating whether this marker is equivalent to another
/**
* Returns a boolean indicating whether this marker is equivalent to another
* marker, meaning they have the same range and options.
*/
isEqual(other: DisplayMarker): boolean;
@@ -555,13 +597,15 @@ declare global {
setScreenRange(screenRange: RangeCompatible, options?: { reversed?: boolean,
clipDirection?: "backward"|"forward"|"closest" }): void;
/** Retrieves the screen position of the marker's start. This will always be
/**
* Retrieves the screen position of the marker's start. This will always be
* less than or equal to the result of DisplayMarker::getEndScreenPosition.
*/
getStartScreenPosition(options?: { clipDirection: "backward"|"forward"|"closest" }):
Point;
/** Retrieves the screen position of the marker's end. This will always be
/**
* Retrieves the screen position of the marker's end. This will always be
* greater than or equal to the result of DisplayMarker::getStartScreenPosition.
*/
getEndScreenPosition(options?: { clipDirection: "backward"|"forward"|"closest" }):
@@ -595,12 +639,14 @@ declare global {
setTailScreenPosition(screenPosition: PointCompatible,
options?: { clipDirection: "backward"|"forward"|"closest" }): void;
/** Retrieves the buffer position of the marker's start. This will always be less
/**
* Retrieves the buffer position of the marker's start. This will always be less
* than or equal to the result of DisplayMarker::getEndBufferPosition.
*/
getStartBufferPosition(): Point;
/** Retrieves the buffer position of the marker's end. This will always be greater
/**
* Retrieves the buffer position of the marker's end. This will always be greater
* than or equal to the result of DisplayMarker::getStartBufferPosition.
*/
getEndBufferPosition(): Point;
@@ -608,19 +654,22 @@ declare global {
/** Returns a boolean indicating whether the marker has a tail. */
hasTail(): boolean;
/** Plants the marker's tail at the current head position. After calling the
/**
* 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.
*/
plantTail(): void;
/** Removes the marker's tail. After calling the marker's head position will be
/**
* 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.
*/
clearTail(): void;
}
/** Experimental: A container for a related set of markers at the DisplayLayer level.
/**
* Experimental: 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.
@@ -638,45 +687,56 @@ declare global {
// Event Subscription
/** Subscribe to be notified synchronously when this layer is destroyed. */
onDidDestroy(callback: () => void): EventKit.Disposable;
onDidDestroy(callback: () => void): Disposable;
/** Subscribe to be notified asynchronously whenever markers are created, updated,
/**
* 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.
*/
onDidUpdate(callback: () => void): EventKit.Disposable;
onDidUpdate(callback: () => void): Disposable;
/** Subscribe to be notified synchronously whenever markers are created on this
/**
* 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.
*/
onDidCreateMarker(callback: (marker: DisplayMarker|Marker) => void):
EventKit.Disposable;
onDidCreateMarker(callback: (marker: DisplayMarker|Marker) => void): Disposable;
// Marker creation
/** Create a marker with the given screen range. */
markScreenRange(range: RangeCompatible, options?: { reversed?: boolean,
invalidate?: "never"|"surround"|"overlap"|"inside"|"touch", exclusive?:
boolean, clipDirection?: "backward"|"forward"|"closest" }): DisplayMarker;
markScreenRange(range: RangeCompatible, options?: {
reversed?: boolean,
invalidate?: "never"|"surround"|"overlap"|"inside"|"touch",
exclusive?: boolean,
clipDirection?: "backward"|"forward"|"closest"
}): DisplayMarker;
/** Create a marker on this layer with its head at the given screen position
/**
* Create a marker on this layer with its head at the given screen position
* and no tail.
*/
markScreenPosition(screenPosition: PointCompatible, options?: { invalidate?:
"never"|"surround"|"overlap"|"inside"|"touch", exclusive?: boolean,
clipDirection?: "backward"|"forward"|"closest" }): DisplayMarker;
markScreenPosition(screenPosition: PointCompatible, options?: {
invalidate?: "never"|"surround"|"overlap"|"inside"|"touch",
exclusive?: boolean,
clipDirection?: "backward"|"forward"|"closest"
}): DisplayMarker;
/** Create a marker with the given buffer range. */
markBufferRange(range: RangeCompatible, options?: {
reversed?: boolean, invalidate?: "never"|"surround"|"overlap"|"inside"|"touch",
exclusive?: boolean }): DisplayMarker;
reversed?: boolean,
invalidate?: "never"|"surround"|"overlap"|"inside"|"touch",
exclusive?: boolean
}): DisplayMarker;
/** Create a marker on this layer with its head at the given buffer position
/**
* Create a marker on this layer with its head at the given buffer position
* and no tail.
*/
markBufferPosition(bufferPosition: PointCompatible, options?: { invalidate?:
"never"|"surround"|"overlap"|"inside"|"touch", exclusive?: boolean }):
DisplayMarker;
markBufferPosition(bufferPosition: PointCompatible, options?: {
invalidate?: "never"|"surround"|"overlap"|"inside"|"touch",
exclusive?: boolean
}): DisplayMarker;
// Querying
/** Get an existing marker by its id. */
@@ -688,7 +748,8 @@ declare global {
/** Get the number of markers in the marker layer. */
getMarkerCount(): number;
/** Find markers in the layer conforming to the given parameters.
/**
* 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,
@@ -715,14 +776,16 @@ declare global {
negate(): Point;
// Comparison
/** Compare another Point to this Point instance.
/**
* Compare another Point to this Point instance.
* Returns -1 if this point precedes the argument.
* Returns 0 if this point is equivalent to the argument.
* Returns 1 if this point follows the argument.
*/
compare(other: PointCompatible): number;
/** Returns a boolean indicating whether this point has the same row and
/**
* Returns a boolean indicating whether this point has the same row and
* column as the given Point.
*/
isEqual(other: PointCompatible): boolean;
@@ -730,7 +793,8 @@ declare global {
/** Returns a Boolean indicating whether this point precedes the given Point. */
isLessThan(other: PointCompatible): boolean;
/** Returns a Boolean indicating whether this point precedes or is equal to
/**
* Returns a Boolean indicating whether this point precedes or is equal to
* the given Point.
*/
isLessThanOrEqual(other: PointCompatible): boolean;
@@ -738,7 +802,8 @@ declare global {
/** Returns a Boolean indicating whether this point follows the given Point. */
isGreaterThan(other: PointCompatible): boolean;
/** Returns a Boolean indicating whether this point follows or is equal to
/**
* Returns a Boolean indicating whether this point follows or is equal to
* the given Point.
*/
isGreaterThanOrEqual(other: PointCompatible): boolean;
@@ -747,12 +812,14 @@ declare global {
/** Makes this point immutable and returns itself. */
freeze(): Readonly<Point>;
/** Build and return a new point by adding the rows and columns of the
/**
* Build and return a new point by adding the rows and columns of the
* given point.
*/
translate(other: PointCompatible): Point;
/** Build and return a new Point by traversing the rows and columns
/**
* Build and return a new Point by traversing the rows and columns
* specified by the given point.
*/
traverse(other: PointCompatible): Point;
@@ -769,7 +836,8 @@ declare global {
/** The static side to the Point class. */
interface PointStatic {
/** Create a Point from an array containing two numbers representing the
/**
* Create a Point from an array containing two numbers representing the
* row and column.
*/
fromObject(object: [number, number]): Point;
@@ -820,7 +888,8 @@ declare global {
/** Is the start position of this range equal to the end position? */
isEmpty(): boolean;
/** Returns a boolean indicating whether this range starts and ends on the
/**
* Returns a boolean indicating whether this range starts and ends on the
* same row.
*/
isSingleLine(): boolean;
@@ -832,7 +901,8 @@ declare global {
getRows(): number[];
// Operations
/** Freezes the range and its start and end point so it becomes immutable
/**
* Freezes the range and its start and end point so it becomes immutable
* and returns itself.
*/
freeze(): Readonly<Range>;
@@ -841,31 +911,36 @@ declare global {
/** Returns a new range that contains this range and the given range. */
union(other: RangeLike): Range;
/** Build and return a new range by translating this range's start and end
/**
* Build and return a new range by translating this range's start and end
* points by the given delta(s).
*/
translate(startDelta: PointCompatible, endDelta?: PointCompatible): Range;
/** Build and return a new range by traversing this range's start and end
/**
* Build and return a new range by traversing this range's start and end
* points by the given delta.
*/
traverse(delta: PointCompatible): Range;
// Comparison
/** Compare two Ranges.
/**
* Compare two Ranges.
* Returns -1 if this range starts before the argument or contains it.
* Returns 0 if this range is equivalent to the argument.
* Returns 1 if this range starts after the argument or is contained by it.
*/
compare(otherRange: RangeCompatible): number;
/** Returns a Boolean indicating whether this range has the same start and
/**
* Returns a Boolean indicating whether this range has the same start and
* end points as the given Range.
*/
isEqual(otherRange: RangeCompatible): boolean;
// NOTE: this function doesn't actually take a range-compatible parameter.
/** Returns a Boolean indicating whether this range starts and ends on the
/**
* Returns a Boolean indicating whether this range starts and ends on the
* same row as the argument.
*/
coversSameRows(otherRange: RangeLike): boolean;
@@ -880,12 +955,14 @@ declare global {
/** Returns a boolean indicating whether this range contains the given point. */
containsPoint(point: PointCompatible, exclusive?: boolean): boolean;
/** Returns a boolean indicating whether this range intersects the given
/**
* Returns a boolean indicating whether this range intersects the given
* row number.
*/
intersectsRow(row: number): boolean;
/** Returns a boolean indicating whether this range intersects the row range
/**
* Returns a boolean indicating whether this range intersects the row range
* indicated by the given startRow and endRow numbers.
*/
intersectsRowRange(startRow: number, endRow: number): boolean;
@@ -924,12 +1001,13 @@ declare global {
end: PointLike;
}
/** A mutable text container with undo/redo support and the ability to
/**
* A mutable text container with undo/redo support and the ability to
* annotate logical regions in the text.
*/
interface TextBuffer {
// Properties
file: PathWatcher.File;
file: File;
lines: string[];
lineEndings: string[];
stoppedChangingDelay: number;
@@ -939,7 +1017,8 @@ declare global {
refcount: number;
id: string;
/** Schedules a 'did-stop-changing' emission. The event will be emitted between
/**
* Schedules a 'did-stop-changing' emission. The event will be emitted between
* now and TextBuffer::stoppedChangingDelay milliseconds in the future.
*/
debouncedEmitDidStopChangingEvent(): void;
@@ -964,85 +1043,89 @@ declare global {
release(): TextBuffer;
// Event Subscription
/** Invoke the given callback synchronously before the content of the buffer
/**
* Invoke the given callback synchronously before the content of the buffer
* changes.
*/
onWillChange(callback: (event: Events.BufferChanging) => void):
EventKit.Disposable;
onWillChange(callback: (event: Events.BufferChanging) => void): Disposable;
/** Invoke the given callback synchronously when the content of the buffer
/**
* Invoke the given callback synchronously when the content of the buffer
* changes. You should probably not be using this in packages.
*/
onDidChange(callback: (event: Events.BufferChanged) => void):
EventKit.Disposable;
onDidChange(callback: (event: Events.BufferChanged) => void): Disposable;
/** Invoke the given callback synchronously when a transaction finishes with
/**
* Invoke the given callback synchronously when a transaction finishes with
* a list of all the changes in the transaction.
*/
onDidChangeText(callback: (event: Events.BufferStoppedChanging) => void):
EventKit.Disposable;
Disposable;
/** Invoke the given callback asynchronously following one or more changes after
/**
* Invoke the given callback asynchronously following one or more changes after
* ::getStoppedChangingDelay milliseconds elapse without an additional change.
*/
onDidStopChanging(callback: (event: Events.BufferStoppedChanging) => void):
EventKit.Disposable;
Disposable;
/** Invoke the given callback when the in-memory contents of the buffer become
/**
* Invoke the given callback when the in-memory contents of the buffer become
* in conflict with the contents of the file on disk.
*/
onDidConflict(callback: () => void): EventKit.Disposable;
onDidConflict(callback: () => void): Disposable;
/** Invoke the given callback if the value of ::isModified changes. */
onDidChangeModified(callback: (modified: boolean) => void):
EventKit.Disposable;
onDidChangeModified(callback: (modified: boolean) => void): Disposable;
/** Invoke the given callback when all marker ::onDidChange observers have been
/**
* Invoke the given callback when all marker ::onDidChange observers have been
* notified following a change to the buffer.
*/
onDidUpdateMarkers(callback: () => void): EventKit.Disposable;
onDidUpdateMarkers(callback: () => void): Disposable;
onDidCreateMarker(callback: (marker: Marker) => void):
EventKit.Disposable;
onDidCreateMarker(callback: (marker: Marker) => void): Disposable;
/** Invoke the given callback when the value of ::getPath changes. */
onDidChangePath(callback: (path: string) => void): EventKit.Disposable;
onDidChangePath(callback: (path: string) => void): Disposable;
/** Invoke the given callback when the value of ::getEncoding changes. */
onDidChangeEncoding(callback: (encoding: string) => void):
EventKit.Disposable;
onDidChangeEncoding(callback: (encoding: string) => void): Disposable;
/** Invoke the given callback before the buffer is saved to disk. If the
/**
* Invoke the given callback before the buffer is saved to disk. If the
* given callback returns a promise, then the buffer will not be saved until
* the promise resolves.
*/
onWillSave(callback: () => Promise<void>|void): EventKit.Disposable;
onWillSave(callback: () => Promise<void>|void): Disposable;
/** Invoke the given callback after the buffer is saved to disk. */
onDidSave(callback: (event: Events.FileSaved) => void):
EventKit.Disposable;
onDidSave(callback: (event: Events.FileSaved) => void): Disposable;
/** Invoke the given callback after the file backing the buffer is deleted. */
onDidDelete(callback: () => void): EventKit.Disposable;
onDidDelete(callback: () => void): Disposable;
/** Invoke the given callback before the buffer is reloaded from the contents
/**
* Invoke the given callback before the buffer is reloaded from the contents
* of its file on disk.
*/
onWillReload(callback: () => void): EventKit.Disposable;
onWillReload(callback: () => void): Disposable;
/** Invoke the given callback after the buffer is reloaded from the contents
/**
* Invoke the given callback after the buffer is reloaded from the contents
* of its file on disk.
*/
onDidReload(callback: () => void): EventKit.Disposable;
onDidReload(callback: () => void): Disposable;
/** Invoke the given callback when the buffer is destroyed. */
onDidDestroy(callback: () => void): EventKit.Disposable;
onDidDestroy(callback: () => void): Disposable;
/** Invoke the given callback when there is an error in watching the file. */
onWillThrowWatchError(callback: (errorObject: Events.BufferWatchError) =>
void): EventKit.Disposable;
void): Disposable;
/** Get the number of milliseconds that will elapse without a change before
/**
* Get the number of milliseconds that will elapse without a change before
* ::onDidStopChanging observers are invoked following a change.
*/
getStoppedChangingDelay(): number;
@@ -1051,13 +1134,15 @@ declare global {
emitDidStopChangingEvent(): void;
// File Details
/** Determine if the in-memory contents of the buffer differ from its contents
/**
* 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.
*/
isModified(): boolean;
/** Determine if the in-memory contents of the buffer conflict with the on-disk
/**
* Determine if the in-memory contents of the buffer conflict with the on-disk
* contents of its associated file.
*/
isInConflict(): boolean;
@@ -1102,7 +1187,8 @@ declare global {
/** Get the line ending for the given 0-indexed row. */
lineEndingForRow(row: number): string|undefined;
/** Get the length of the line for the given 0-indexed row, without its line
/**
* Get the length of the line for the given 0-indexed row, without its line
* ending.
*/
lineLengthForRow(row: number): number;
@@ -1110,12 +1196,14 @@ declare global {
/** Determine if the given row contains only whitespace. */
isRowBlank(row: number): boolean;
/** Given a row, find the first preceding row that's not blank.
/**
* Given a row, find the first preceding row that's not blank.
* Returns a number or null if there's no preceding non-blank row.
*/
previousNonBlankRow(startRow: number): number|null;
/** Given a row, find the next row that's not blank.
/**
* Given a row, find the next row that's not blank.
* Returns a number or null if there's no next non-blank row.
*/
nextNonBlankRow(startRow: number): number|null;
@@ -1124,7 +1212,8 @@ declare global {
/** Replace the entire contents of the buffer with the given text. */
setText(text: string): Range;
/** Replace the current buffer contents by applying a diff based on the
/**
* Replace the current buffer contents by applying a diff based on the
* given text.
*/
setTextViaDiff(text: string): void;
@@ -1155,7 +1244,8 @@ declare global {
addMarkerLayer(options?: { maintainHistory?: boolean, persistent?: boolean }):
MarkerLayer;
/** Get a MarkerLayer by id.
/**
* Get a MarkerLayer by id.
* Returns a MarkerLayer or `` if no layer exists with the given id.
*/
getMarkerLayer(id: string): MarkerLayer|undefined;
@@ -1195,34 +1285,40 @@ declare global {
transact<T>(groupingInterval: number, fn: () => T): T;
transact<T>(fn: () => T): T;
/** Call within a transaction to terminate the function's execution and
/**
* Call within a transaction to terminate the function's execution and
* revert any changes performed up to the abortion.
*/
abortTransaction(): void;
/** Clear the undo stack. When calling this method within a transaction,
/**
* Clear the undo stack. When calling this method within a transaction,
* the ::onDidChangeText event will not be triggered because the information
* describing the changes is lost.
*/
clearUndoStack(): void;
/** Create a pointer to the current state of the buffer for use with
/**
* Create a pointer to the current state of the buffer for use with
* ::revertToCheckpoint and ::groupChangesSinceCheckpoint.
*/
createCheckpoint(): number;
/** Revert the buffer to the state it was in when the given checkpoint was created.
/**
* Revert the buffer to the state it was in when the given checkpoint was created.
* Returns a boolean indicating whether the operation succeeded.
*/
revertToCheckpoint(checkpoint: number): boolean;
/** Group all changes since the given checkpoint into a single transaction for
/**
* Group all changes since the given checkpoint into a single transaction for
* purposes of undo/redo.
* Returns a boolean indicating whether the operation succeeded.
*/
groupChangesSinceCheckpoint(checkpoint: number): boolean;
/** Returns a list of changes since the given checkpoint.
/**
* Returns a list of changes since the given checkpoint.
* If the given checkpoint is no longer present in the undo history, this method
* will return an empty Array.
*/
@@ -1241,48 +1337,57 @@ declare global {
}>;
// Search and Replace
/** Scan regular expression matches in the entire buffer, calling the given
/**
* Scan regular expression matches in the entire buffer, calling the given
* iterator function on each match.
*/
scan(regex: RegExp, iterator: (params: Structures.BufferScanResult) => void): void;
/** Scan regular expression matches in the entire buffer, calling the given
/**
* Scan regular expression matches in the entire buffer, calling the given
* iterator function on each match.
*/
scan(regex: RegExp, options: Options.ScanContext, iterator: (params:
Structures.ContextualBufferScanResult) => void): void;
/** Scan regular expression matches in the entire buffer in reverse order,
/**
* Scan regular expression matches in the entire buffer in reverse order,
* calling the given iterator function on each match.
*/
backwardsScan(regex: RegExp, iterator: (params: Structures.BufferScanResult) => void):
void;
/** Scan regular expression matches in the entire buffer in reverse order,
/**
* Scan regular expression matches in the entire buffer in reverse order,
* calling the given iterator function on each match.
*/
backwardsScan(regex: RegExp, options: Options.ScanContext, iterator: (params:
Structures.ContextualBufferScanResult) => void): void;
/** Scan regular expression matches in a given range , calling the given
/**
* Scan regular expression matches in a given range , calling the given
* iterator function on each match.
*/
scanInRange(regex: RegExp, range: RangeCompatible, iterator:
(params: Structures.BufferScanResult) => void): void;
/** Scan regular expression matches in a given range , calling the given
/**
* Scan regular expression matches in a given range , calling the given
* iterator function on each match.
*/
scanInRange(regex: RegExp, range: RangeCompatible, options: Options.ScanContext,
iterator: (params: Structures.ContextualBufferScanResult) => void): void;
/** Scan regular expression matches in a given range in reverse order,
/**
* Scan regular expression matches in a given range in reverse order,
* calling the given iterator function on each match.
*/
backwardsScanInRange(regex: RegExp, range: RangeCompatible, iterator:
(params: Structures.BufferScanResult) => void): void;
/** Scan regular expression matches in a given range in reverse order,
/**
* Scan regular expression matches in a given range in reverse order,
* calling the given iterator function on each match.
*/
backwardsScanInRange(regex: RegExp, range: RangeCompatible, options: Options.ScanContext,
iterator: (params: Structures.ContextualBufferScanResult) => void): void;
backwardsScanInRange(regex: RegExp, range: RangeCompatible, options:
Options.ScanContext, iterator:
(params: Structures.ContextualBufferScanResult) => void): void;
/** Replace all regular expression matches in the entire buffer. */
replace(regex: RegExp, replacementText: string): number;
@@ -1309,12 +1414,14 @@ declare global {
/** Get the range for the given row. */
rangeForRow(row: number, includeNewline: boolean): Range;
/** Convert a position in the buffer in row/column coordinates to an absolute
/**
* Convert a position in the buffer in row/column coordinates to an absolute
* character offset, inclusive of line ending characters.
*/
characterIndexForPosition(position: Point|[number, number]): number;
/** Convert an absolute character offset, inclusive of newlines, to a position
/**
* Convert an absolute character offset, inclusive of newlines, to a position
* in the buffer in row/column coordinates.
*/
positionForCharacterIndex(offset: number): Point;
@@ -1344,12 +1451,14 @@ declare global {
/** Create a new buffer backed by the given file path. */
load(source: string, params?: Options.BufferLoad): Promise<TextBuffer>;
/** Create a new buffer backed by the given file path. For better performance,
/**
* Create a new buffer backed by the given file path. For better performance,
* use TextBuffer.load instead.
*/
loadSync(filePath: string, params?: Options.BufferLoad): TextBuffer;
/** Restore a TextBuffer based on an earlier state created using the
/**
* Restore a TextBuffer based on an earlier state created using the
* TextBuffer::serialize method.
*/
deserialize(params: object): Promise<TextBuffer>;
@@ -1360,7 +1469,8 @@ declare global {
new (params?: {
/** The initial string text of the buffer. */
text?: string
/** A function that returns a Boolean indicating whether the buffer should
/**
* A function that returns a Boolean indicating whether the buffer should
* be destroyed if its file is deleted.
*/
shouldDestroyOnFileDelete?(): boolean
+2 -1
View File
@@ -1,3 +1,4 @@
import { Disposable } from "event-kit";
import TextBuffer = require("text-buffer");
declare let obj: object;
@@ -14,7 +15,7 @@ declare let displayMarkerLayer: TextBuffer.DisplayMarkerLayer;
declare let marker: TextBuffer.Marker;
declare let markers: TextBuffer.Marker[];
declare let markerLayer: TextBuffer.MarkerLayer;
declare let sub: EventKit.Disposable;
declare let sub: Disposable;
// Point ======================================================================
let point = new TextBuffer.Point(42, 42);
+2 -2
View File
@@ -8,7 +8,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
@@ -21,4 +21,4 @@
"index.d.ts",
"text-buffer-tests.ts"
]
}
}
+2 -30
View File
@@ -1,36 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
"class-name": true,
"indent": [true, "spaces", 4],
"jsdoc-format": true,
"max-line-length": [true, 110],
"quotemark": [true, "double", "avoid-escape"],
"trailing-comma": [true, {
"multiline": { "objects": "always", "arrays": "always", "functions": "never" },
"singleline": { "objects": "never", "arrays": "never", "functions": "never" }
}],
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-module",
"check-separator",
"check-type",
"check-typecast",
"check-rest-spread",
"check-preblock"
],
// Soon to be defaults.
"arrow-return-shorthand": [true, "multiline"],
"no-any": true,
"no-floating-promises": true,
"no-unbound-method": true,
"no-unsafe-any": true,
"number-literal-format": true,
"restrict-plus-operands": true,
"return-undefined": true,
"switch-final-break": true
"max-line-length": [true, 100],
"no-any": true
}
}