Merge branch 'master' into ben/sqlite

This commit is contained in:
Benjamin Pasero
2018-10-12 09:16:30 +02:00
400 changed files with 2648 additions and 2092 deletions
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"module": "amd",
"moduleResolution": "node",
"noImplicitAny": false,
"target": "es5",
"experimentalDecorators": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noImplicitThis": true,
"alwaysStrict": true,
"baseUrl": ".",
"paths": {
"vs/*": [
"./vs/*"
]
},
"types": [
"keytar",
"minimist",
"mocha",
"semver",
"sinon",
"winreg"
]
}
}
+2 -24
View File
@@ -1,33 +1,11 @@
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"module": "amd",
"moduleResolution": "node",
"noImplicitAny": false,
"removeComments": false,
"preserveConstEnums": true,
"target": "es5",
"sourceMap": false,
"experimentalDecorators": true,
"declaration": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noImplicitThis": true,
"alwaysStrict": true,
"baseUrl": ".",
"outDir": "../out",
"paths": {
"vs/*": [
"./vs/*"
]
},
"types": [
"keytar",
"minimist",
"mocha",
"semver",
"sinon",
"winreg"
]
"outDir": "../out"
},
"include": [
"./typings",
+273
View File
@@ -0,0 +1,273 @@
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"noEmit": true,
"strictNullChecks": true
},
"include": [
"./typings",
"./vs/base/browser/browser.ts",
"./vs/base/browser/dom.ts",
"./vs/base/browser/event.ts",
"./vs/base/browser/history.ts",
"./vs/base/browser/iframe.ts",
"./vs/base/browser/keyboardEvent.ts",
"./vs/base/browser/mouseEvent.ts",
"./vs/base/browser/ui/list/splice.ts",
"./vs/base/browser/ui/octiconLabel/octiconLabel.mock.ts",
"./vs/base/browser/ui/octiconLabel/octiconLabel.ts",
"./vs/base/browser/ui/scrollbar/scrollableElementOptions.ts",
"./vs/base/browser/ui/scrollbar/scrollbarState.ts",
"./vs/base/browser/ui/tree/tree.ts",
"./vs/base/common/actions.ts",
"./vs/base/common/amd.ts",
"./vs/base/common/arrays.ts",
"./vs/base/common/assert.ts",
"./vs/base/common/async.ts",
"./vs/base/common/cache.ts",
"./vs/base/common/cancellation.ts",
"./vs/base/common/charCode.ts",
"./vs/base/common/collections.ts",
"./vs/base/common/color.ts",
"./vs/base/common/comparers.ts",
"./vs/base/common/date.ts",
"./vs/base/common/decorators.ts",
"./vs/base/common/diff/diff.ts",
"./vs/base/common/diff/diffChange.ts",
"./vs/base/common/errorMessage.ts",
"./vs/base/common/errors.ts",
"./vs/base/common/errorsWithActions.ts",
"./vs/base/common/event.ts",
"./vs/base/common/filters.ts",
"./vs/base/common/functional.ts",
"./vs/base/common/glob.ts",
"./vs/base/common/hash.ts",
"./vs/base/common/history.ts",
"./vs/base/common/htmlContent.ts",
"./vs/base/common/idGenerator.ts",
"./vs/base/common/iterator.ts",
"./vs/base/common/jsonSchema.ts",
"./vs/base/common/keyCodes.ts",
"./vs/base/common/keybindingParser.ts",
"./vs/base/common/labels.ts",
"./vs/base/common/lifecycle.ts",
"./vs/base/common/linkedList.ts",
"./vs/base/common/map.ts",
"./vs/base/common/marshalling.ts",
"./vs/base/common/network.ts",
"./vs/base/common/normalization.ts",
"./vs/base/common/numbers.ts",
"./vs/base/common/objects.ts",
"./vs/base/common/parsers.ts",
"./vs/base/common/paths.ts",
"./vs/base/common/platform.ts",
"./vs/base/common/processes.ts",
"./vs/base/common/range.ts",
"./vs/base/common/resources.ts",
"./vs/base/common/scanCode.ts",
"./vs/base/common/scrollable.ts",
"./vs/base/common/sequence.ts",
"./vs/base/common/severity.ts",
"./vs/base/common/stopwatch.ts",
"./vs/base/common/strings.ts",
"./vs/base/common/types.ts",
"./vs/base/common/uri.ts",
"./vs/base/common/uriIpc.ts",
"./vs/base/common/uuid.ts",
"./vs/base/common/winjs.base.d.ts",
"./vs/base/common/winjs.polyfill.promise.ts",
"./vs/base/common/worker/simpleWorker.ts",
"./vs/base/node/decoder.ts",
"./vs/base/node/id.ts",
"./vs/base/node/paths.ts",
"./vs/base/node/ports.ts",
"./vs/base/parts/contextmenu/common/contextmenu.ts",
"./vs/base/parts/contextmenu/electron-main/contextmenu.ts",
"./vs/base/parts/quickopen/common/quickOpen.ts",
"./vs/base/test/common/utils.ts",
"./vs/base/test/node/uri.test.perf.ts",
"./vs/base/worker/defaultWorkerFactory.ts",
"./vs/base/worker/workerMain.ts",
"./vs/code/electron-browser/issue/issueReporterPage.ts",
"./vs/code/electron-browser/issue/issueReporterUtil.ts",
"./vs/code/electron-main/keyboard.ts",
"./vs/code/electron-main/theme.ts",
"./vs/code/node/shellEnv.ts",
"./vs/editor/browser/config/charWidthReader.ts",
"./vs/editor/browser/config/elementSizeObserver.ts",
"./vs/editor/browser/controller/textAreaState.ts",
"./vs/editor/common/commands/replaceCommand.ts",
"./vs/editor/common/commands/surroundSelectionCommand.ts",
"./vs/editor/common/commands/trimTrailingWhitespaceCommand.ts",
"./vs/editor/common/config/editorOptions.ts",
"./vs/editor/common/config/editorZoom.ts",
"./vs/editor/common/config/fontInfo.ts",
"./vs/editor/common/controller/cursorEvents.ts",
"./vs/editor/common/controller/wordCharacterClassifier.ts",
"./vs/editor/common/core/characterClassifier.ts",
"./vs/editor/common/core/editOperation.ts",
"./vs/editor/common/core/lineTokens.ts",
"./vs/editor/common/core/position.ts",
"./vs/editor/common/core/range.ts",
"./vs/editor/common/core/rgba.ts",
"./vs/editor/common/core/selection.ts",
"./vs/editor/common/core/stringBuilder.ts",
"./vs/editor/common/core/token.ts",
"./vs/editor/common/core/uint.ts",
"./vs/editor/common/diff/diffComputer.ts",
"./vs/editor/common/editorAction.ts",
"./vs/editor/common/editorCommon.ts",
"./vs/editor/common/editorContextKeys.ts",
"./vs/editor/common/model.ts",
"./vs/editor/common/model/editStack.ts",
"./vs/editor/common/model/indentationGuesser.ts",
"./vs/editor/common/model/intervalTree.ts",
"./vs/editor/common/model/mirrorTextModel.ts",
"./vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase.ts",
"./vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer.ts",
"./vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder.ts",
"./vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase.ts",
"./vs/editor/common/model/textModel.ts",
"./vs/editor/common/model/textModelEvents.ts",
"./vs/editor/common/model/textModelSearch.ts",
"./vs/editor/common/model/textModelTokens.ts",
"./vs/editor/common/model/wordHelper.ts",
"./vs/editor/common/modes.ts",
"./vs/editor/common/modes/abstractMode.ts",
"./vs/editor/common/modes/languageConfiguration.ts",
"./vs/editor/common/modes/languageConfigurationRegistry.ts",
"./vs/editor/common/modes/languageFeatureRegistry.ts",
"./vs/editor/common/modes/languageSelector.ts",
"./vs/editor/common/modes/linkComputer.ts",
"./vs/editor/common/modes/nullMode.ts",
"./vs/editor/common/modes/supports.ts",
"./vs/editor/common/modes/supports/characterPair.ts",
"./vs/editor/common/modes/supports/electricCharacter.ts",
"./vs/editor/common/modes/supports/indentRules.ts",
"./vs/editor/common/modes/supports/inplaceReplaceSupport.ts",
"./vs/editor/common/modes/supports/onEnter.ts",
"./vs/editor/common/modes/supports/richEditBrackets.ts",
"./vs/editor/common/modes/supports/tokenization.ts",
"./vs/editor/common/modes/textToHtmlTokenizer.ts",
"./vs/editor/common/modes/tokenizationRegistry.ts",
"./vs/editor/common/services/editorWorkerService.ts",
"./vs/editor/common/services/modelService.ts",
"./vs/editor/common/services/modeService.ts",
"./vs/editor/common/services/resolverService.ts",
"./vs/editor/common/standalone/standaloneBase.ts",
"./vs/editor/common/view/minimapCharRenderer.ts",
"./vs/editor/common/view/overviewZoneManager.ts",
"./vs/editor/common/view/runtimeMinimapCharRenderer.ts",
"./vs/editor/common/view/viewEvents.ts",
"./vs/editor/common/viewLayout/whitespaceComputer.ts",
"./vs/editor/common/viewModel/prefixSumComputer.ts",
"./vs/editor/contrib/codeAction/codeActionTrigger.ts",
"./vs/editor/contrib/colorPicker/colorPickerModel.ts",
"./vs/editor/contrib/find/findState.ts",
"./vs/editor/contrib/find/replaceAllCommand.ts",
"./vs/editor/contrib/find/replacePattern.ts",
"./vs/editor/contrib/indentation/indentUtils.ts",
"./vs/editor/contrib/inPlaceReplace/inPlaceReplaceCommand.ts",
"./vs/editor/contrib/linesOperations/copyLinesCommand.ts",
"./vs/editor/standalone/common/monarch/monarchCommon.ts",
"./vs/editor/standalone/common/monarch/monarchCompile.ts",
"./vs/editor/standalone/common/monarch/monarchTypes.ts",
"./vs/editor/test/common/commentMode.ts",
"./vs/editor/test/common/core/viewLineToken.ts",
"./vs/editor/test/common/editorTestUtils.ts",
"./vs/editor/test/common/mocks/mockMode.ts",
"./vs/editor/test/common/model/benchmark/benchmarkUtils.ts",
"./vs/editor/test/common/modes/supports/javascriptOnEnterRules.ts",
"./vs/editor/test/common/modesTestUtils.ts",
"./vs/monaco.d.ts",
"./vs/nls.mock.ts",
"./vs/platform/broadcast/electron-browser/broadcastService.ts",
"./vs/platform/clipboard/common/clipboardService.ts",
"./vs/platform/clipboard/electron-browser/clipboardService.ts",
"./vs/platform/contextkey/common/contextkey.ts",
"./vs/platform/download/common/download.ts",
"./vs/platform/editor/common/editor.ts",
"./vs/platform/environment/common/environment.ts",
"./vs/platform/extensions/common/extensionHost.ts",
"./vs/platform/extensions/common/extensions.ts",
"./vs/platform/files/common/files.ts",
"./vs/platform/files/node/files.ts",
"./vs/platform/instantiation/common/descriptors.ts",
"./vs/platform/instantiation/common/extensions.ts",
"./vs/platform/instantiation/common/graph.ts",
"./vs/platform/instantiation/common/instantiation.ts",
"./vs/platform/instantiation/common/serviceCollection.ts",
"./vs/platform/integrity/common/integrity.ts",
"./vs/platform/jsonschemas/common/jsonContributionRegistry.ts",
"./vs/platform/lifecycle/common/lifecycle.ts",
"./vs/platform/localizations/common/localizations.ts",
"./vs/platform/log/common/bufferLog.ts",
"./vs/platform/log/common/log.ts",
"./vs/platform/log/node/spdlogService.ts",
"./vs/platform/markers/common/markers.ts",
"./vs/platform/menubar/common/menubar.ts",
"./vs/platform/node/minimalTranslations.ts",
"./vs/platform/node/package.ts",
"./vs/platform/node/product.ts",
"./vs/platform/notification/common/notification.ts",
"./vs/platform/notification/test/common/testNotificationService.ts",
"./vs/platform/opener/common/opener.ts",
"./vs/platform/output/node/outputAppender.ts",
"./vs/platform/progress/common/progress.ts",
"./vs/platform/quickinput/common/quickInput.ts",
"./vs/platform/quickOpen/common/quickOpen.ts",
"./vs/platform/registry/common/platform.ts",
"./vs/platform/search/common/search.ts",
"./vs/platform/state/common/state.ts",
"./vs/platform/statusbar/common/statusbar.ts",
"./vs/platform/telemetry/common/telemetry.ts",
"./vs/platform/telemetry/node/telemetryNodeUtils.ts",
"./vs/platform/theme/common/colorRegistry.ts",
"./vs/platform/theme/common/themeService.ts",
"./vs/platform/update/common/update.ts",
"./vs/platform/url/common/url.ts",
"./vs/platform/url/common/urlService.ts",
"./vs/platform/workbench/common/contextkeys.ts",
"./vs/workbench/api/shared/tasks.ts",
"./vs/workbench/browser/parts/statusbar/statusbar.ts",
"./vs/workbench/common/activity.ts",
"./vs/workbench/common/composite.ts",
"./vs/workbench/common/contributions.ts",
"./vs/workbench/common/extensionHostProtocol.ts",
"./vs/workbench/common/panel.ts",
"./vs/workbench/common/viewlet.ts",
"./vs/workbench/parts/codeEditor/browser/simpleEditorOptions.ts",
"./vs/workbench/parts/execution/common/execution.ts",
"./vs/workbench/parts/extensions/common/extensionQuery.ts",
"./vs/workbench/parts/logs/common/logConstants.ts",
"./vs/workbench/parts/markers/electron-browser/constants.ts",
"./vs/workbench/parts/outline/electron-browser/outline.ts",
"./vs/workbench/parts/output/common/output.ts",
"./vs/workbench/parts/scm/electron-browser/scmUtil.ts",
"./vs/workbench/parts/search/common/constants.ts",
"./vs/workbench/parts/terminal/browser/terminalWidgetManager.ts",
"./vs/workbench/parts/terminal/common/terminal.ts",
"./vs/workbench/parts/welcome/page/electron-browser/vs_code_welcome_page.ts",
"./vs/workbench/services/activity/common/activity.ts",
"./vs/workbench/services/backup/common/backup.ts",
"./vs/workbench/services/configuration/common/jsonEditing.ts",
"./vs/workbench/services/decorations/browser/decorations.ts",
"./vs/workbench/services/extensions/node/lazyPromise.ts",
"./vs/workbench/services/extensions/node/proxyIdentifier.ts",
"./vs/workbench/services/files/node/watcher/common.ts",
"./vs/workbench/services/files/node/watcher/nsfw/watcher.ts",
"./vs/workbench/services/files/node/watcher/unix/watcher.ts",
"./vs/workbench/services/hash/common/hashService.ts",
"./vs/workbench/services/hash/node/hashService.ts",
"./vs/workbench/services/panel/common/panelService.ts",
"./vs/workbench/services/scm/common/scm.ts",
"./vs/workbench/services/scm/common/scmService.ts",
"./vs/workbench/services/search/node/search.ts",
"./vs/workbench/services/textMate/electron-browser/textMateService.ts",
"./vs/workbench/services/title/common/titleService.ts",
"./vs/workbench/test/electron-browser/api/mock.ts"
],
"exclude": [
"./typings/require-monaco.d.ts"
]
}
+4 -2
View File
@@ -4,7 +4,9 @@
*--------------------------------------------------------------------------------------------*/
interface NodeRequire {
(moduleName: string): any;
}
toUrl(path: string): string;
(dependencies: string[], callback: (...args: any[]) => any, errorback?: (err: any) => void): any;
config(data: any): any;
}
declare var require: NodeRequire;
+26 -25
View File
@@ -20,7 +20,7 @@ export function clearNode(node: HTMLElement): void {
}
}
export function isInDOM(node: Node): boolean {
export function isInDOM(node: Node | null): boolean {
while (node) {
if (node === document.body) {
return true;
@@ -151,7 +151,7 @@ const _manualClassList = new class implements IDomClassList {
const _nativeClassList = new class implements IDomClassList {
hasClass(node: HTMLElement, className: string): boolean {
return className && node.classList && node.classList.contains(className);
return Boolean(className) && node.classList && node.classList.contains(className);
}
addClasses(node: HTMLElement, ...classNames: string[]): void {
@@ -198,7 +198,7 @@ class DomListener implements IDisposable {
private readonly _type: string;
private readonly _useCapture: boolean;
constructor(node: Element | Window | Document, type: string, handler: (e: any) => void, useCapture: boolean) {
constructor(node: Element | Window | Document, type: string, handler: (e: any) => void, useCapture?: boolean) {
this._node = node;
this._type = type;
this._handler = handler;
@@ -215,8 +215,8 @@ class DomListener implements IDisposable {
this._node.removeEventListener(this._type, this._handler, this._useCapture);
// Prevent leakers from holding on to the dom or handler func
this._node = null;
this._handler = null;
this._node = null!;
this._handler = null!;
}
}
@@ -257,7 +257,7 @@ export let addStandardDisposableListener: IAddStandardDisposableListenerSignatur
export function addDisposableNonBubblingMouseOutListener(node: Element, handler: (event: MouseEvent) => void): IDisposable {
return addDisposableListener(node, 'mouseout', (e: MouseEvent) => {
// Mouse out bubbles, so this is an attempt to ignore faux mouse outs coming from children elements
let toElement = <Node>(e.relatedTarget || e.toElement);
let toElement: Node | null = <Node>(e.relatedTarget || e.toElement);
while (toElement && toElement !== node) {
toElement = toElement.parentNode;
}
@@ -272,7 +272,7 @@ export function addDisposableNonBubblingMouseOutListener(node: Element, handler:
interface IRequestAnimationFrame {
(callback: (time: number) => void): number;
}
let _animationFrame: IRequestAnimationFrame = null;
let _animationFrame: IRequestAnimationFrame | null = null;
function doRequestAnimationFrame(callback: (time: number) => void): number {
if (!_animationFrame) {
const emulatedRequestAnimationFrame = (callback: (time: number) => void): any => {
@@ -311,7 +311,7 @@ class AnimationFrameQueueItem implements IDisposable {
public priority: number;
private _canceled: boolean;
constructor(runner: () => void, priority: number) {
constructor(runner: () => void, priority: number = 0) {
this._runner = runner;
this.priority = priority;
this._canceled = false;
@@ -347,7 +347,7 @@ class AnimationFrameQueueItem implements IDisposable {
/**
* The runners scheduled at the current animation frame
*/
let CURRENT_QUEUE: AnimationFrameQueueItem[] = null;
let CURRENT_QUEUE: AnimationFrameQueueItem[] | null = null;
/**
* A flag to keep track if the native requestAnimationFrame was already called
*/
@@ -366,7 +366,7 @@ class AnimationFrameQueueItem implements IDisposable {
inAnimationFrameRunner = true;
while (CURRENT_QUEUE.length > 0) {
CURRENT_QUEUE.sort(AnimationFrameQueueItem.sort);
let top = CURRENT_QUEUE.shift();
let top = CURRENT_QUEUE.shift()!;
top.execute();
}
inAnimationFrameRunner = false;
@@ -387,7 +387,7 @@ class AnimationFrameQueueItem implements IDisposable {
runAtThisOrScheduleAtNextAnimationFrame = (runner: () => void, priority?: number) => {
if (inAnimationFrameRunner) {
let item = new AnimationFrameQueueItem(runner, priority);
CURRENT_QUEUE.push(item);
CURRENT_QUEUE!.push(item);
return item;
} else {
return scheduleAtNextAnimationFrame(runner, priority);
@@ -407,7 +407,7 @@ export function modify(callback: () => void): IDisposable {
* Add a throttled listener. `handler` is fired at most every 16ms or with the next animation frame (if browser supports it).
*/
export interface IEventMerger<R, E> {
(lastEvent: R, currentEvent: E): R;
(lastEvent: R | null, currentEvent: E): R;
}
export interface DOMEvent {
@@ -425,13 +425,13 @@ class TimeoutThrottledDomListener<R, E extends DOMEvent> extends Disposable {
constructor(node: any, type: string, handler: (event: R) => void, eventMerger: IEventMerger<R, E> = <any>DEFAULT_EVENT_MERGER, minimumTimeMs: number = MINIMUM_TIME_MS) {
super();
let lastEvent: R = null;
let lastEvent: R | null = null;
let lastHandlerTime = 0;
let timeout = this._register(new TimeoutTimer());
let invokeHandler = () => {
lastHandlerTime = (new Date()).getTime();
handler(lastEvent);
handler(<R>lastEvent);
lastEvent = null;
};
@@ -455,7 +455,7 @@ export function addDisposableThrottledListener<R, E extends DOMEvent = DOMEvent>
}
export function getComputedStyle(el: HTMLElement): CSSStyleDeclaration {
return document.defaultView.getComputedStyle(el, null);
return document.defaultView!.getComputedStyle(el, null);
}
// Adapted from WinJS
@@ -660,7 +660,7 @@ export const StandardWindow: IStandardWindow = new class implements IStandardWin
// modern browsers
return window.scrollX;
} else {
return document.body.scrollLeft + document.documentElement.scrollLeft;
return document.body.scrollLeft + document.documentElement!.scrollLeft;
}
}
@@ -669,7 +669,7 @@ export const StandardWindow: IStandardWindow = new class implements IStandardWin
// modern browsers
return window.scrollY;
} else {
return document.body.scrollTop + document.documentElement.scrollTop;
return document.body.scrollTop + document.documentElement!.scrollTop;
}
}
};
@@ -728,7 +728,7 @@ export function getLargestChildWidth(parent: HTMLElement, children: HTMLElement[
// ----------------------------------------------------------------------------------------
export function isAncestor(testChild: Node, testAncestor: Node): boolean {
export function isAncestor(testChild: Node | null, testAncestor: Node): boolean {
while (testChild) {
if (testChild === testAncestor) {
return true;
@@ -739,7 +739,7 @@ export function isAncestor(testChild: Node, testAncestor: Node): boolean {
return false;
}
export function findParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): HTMLElement {
export function findParentWithClass(node: HTMLElement, clazz: string, stopAtClazzOrNode?: string | HTMLElement): HTMLElement | null {
while (node) {
if (hasClass(node, clazz)) {
return node;
@@ -771,7 +771,7 @@ export function createStyleSheet(container: HTMLElement = document.getElementsBy
return style;
}
let _sharedStyleSheet: HTMLStyleElement = null;
let _sharedStyleSheet: HTMLStyleElement | null = null;
function getSharedStyleSheet(): HTMLStyleElement {
if (!_sharedStyleSheet) {
_sharedStyleSheet = createStyleSheet();
@@ -1002,17 +1002,18 @@ export function $<T extends HTMLElement>(description: string, attrs?: { [key: st
result.className = match[4].replace(/\./g, ' ').trim();
}
Object.keys(attrs || {}).forEach(name => {
attrs = attrs || {};
Object.keys(attrs).forEach(name => {
const value = attrs![name];
if (/^on\w+$/.test(name)) {
(<any>result)[name] = attrs[name];
(<any>result)[name] = value;
} else if (name === 'selected') {
const value = attrs[name];
if (value) {
result.setAttribute(name, 'true');
}
} else {
result.setAttribute(name, attrs[name]);
result.setAttribute(name, value);
}
});
@@ -1061,7 +1062,7 @@ export function hide(...elements: HTMLElement[]): void {
}
}
function findParentWithAttribute(node: Node, attribute: string): HTMLElement {
function findParentWithAttribute(node: Node | null, attribute: string): HTMLElement | null {
while (node) {
if (node instanceof HTMLElement && node.hasAttribute(attribute)) {
return node;
+6 -5
View File
@@ -14,13 +14,13 @@ export interface IWindowChainElement {
/**
* The iframe element inside the window.parent corresponding to window
*/
iframeElement: HTMLIFrameElement;
iframeElement: HTMLIFrameElement | null;
}
let hasDifferentOriginAncestorFlag: boolean = false;
let sameOriginWindowChainCache: IWindowChainElement[] = null;
let sameOriginWindowChainCache: IWindowChainElement[] | null = null;
function getParentWindowIfSameOrigin(w: Window): Window {
function getParentWindowIfSameOrigin(w: Window): Window | null {
if (!w.parent || w.parent === w) {
return null;
}
@@ -41,7 +41,7 @@ function getParentWindowIfSameOrigin(w: Window): Window {
return w.parent;
}
function findIframeElementInParentWindow(parentWindow: Window, childWindow: Window): HTMLIFrameElement {
function findIframeElementInParentWindow(parentWindow: Window, childWindow: Window): HTMLIFrameElement | null {
let parentWindowIframes = parentWindow.document.getElementsByTagName('iframe');
let iframe: HTMLIFrameElement;
for (let i = 0, len = parentWindowIframes.length; i < len; i++) {
@@ -63,7 +63,8 @@ export class IframeUtils {
public static getSameOriginWindowChain(): IWindowChainElement[] {
if (!sameOriginWindowChainCache) {
sameOriginWindowChainCache = [];
let w = window, parent: Window;
let w: Window | null = window;
let parent: Window | null;
do {
parent = getParentWindowIfSameOrigin(w);
if (parent) {
+2 -2
View File
@@ -66,8 +66,8 @@ export class StandardMouseEvent implements IMouseEvent {
this.posy = e.pageY;
} else {
// Probably hit by MSGestureEvent
this.posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
this.posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
this.posx = e.clientX + document.body.scrollLeft + document.documentElement!.scrollLeft;
this.posy = e.clientY + document.body.scrollTop + document.documentElement!.scrollTop;
}
// Find the position of the iframe this code is executing in relative to the iframe where the event was captured.
@@ -286,7 +286,7 @@ export class ActionItem extends BaseActionItem {
}
updateTooltip(): void {
let title: string = null;
let title: string | null = null;
if (this.getAction().tooltip) {
title = this.getAction().tooltip;
@@ -602,7 +602,7 @@ export class ActionBar extends Disposable implements IActionRunner {
e.stopPropagation();
}));
let item: IActionItem = null;
let item: IActionItem | null = null;
if (this.options.actionItemProvider) {
item = this.options.actionItemProvider(action);
+2 -2
View File
@@ -260,7 +260,7 @@ export class InputBox extends Widget {
return document.activeElement === this.input;
}
public select(range: IRange = null): void {
public select(range: IRange | null = null): void {
this.input.select();
if (range) {
@@ -339,7 +339,7 @@ export class InputBox extends Widget {
}
public validate(): boolean {
let errorMsg: IMessage = null;
let errorMsg: IMessage | null = null;
if (this.validation) {
errorMsg = this.validation(this.value);
+1 -1
View File
@@ -60,7 +60,7 @@ export function shift({ start, end }: IRange, much: number): IRange {
*/
export function consolidate(groups: IRangedGroup[]): IRangedGroup[] {
const result: IRangedGroup[] = [];
let previousGroup: IRangedGroup = null;
let previousGroup: IRangedGroup | null = null;
for (let group of groups) {
const start = group.range.start;
+1 -1
View File
@@ -347,7 +347,7 @@ class MenuActionItem extends BaseActionItem {
}
updateTooltip(): void {
let title: string = null;
let title: string | null = null;
if (this.getAction().tooltip) {
title = this.getAction().tooltip;
@@ -78,8 +78,16 @@
white-space: nowrap;
}
.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row > .option-text-description {
display: none;
/* Accepted CSS hiding technique for accessibility reader text */
/* https://webaim.org/techniques/css/invisiblecontent/ */
.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row > .visually-hidden {
position: absolute;
left: -10000px;
top: auto;
width: 1px;
height: 1px;
overflow: hidden;
}
.monaco-select-box-dropdown-container > .select-box-dropdown-container-width-control {
@@ -5,7 +5,6 @@
import 'vs/css!./selectBoxCustom';
import * as nls from 'vs/nls';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { Event, Emitter, chain } from 'vs/base/common/event';
import { KeyCode, KeyCodeUtils } from 'vs/base/common/keyCodes';
@@ -50,6 +49,7 @@ class SelectListRenderer implements IRenderer<ISelectOptionItem, ISelectListTemp
data.root = container;
data.optionText = dom.append(container, $('.option-text'));
data.optionDescriptionText = dom.append(container, $('.option-text-description'));
dom.addClass(data.optionDescriptionText, 'visually-hidden');
return data;
}
@@ -60,18 +60,14 @@ class SelectListRenderer implements IRenderer<ISelectOptionItem, ISelectListTemp
const optionDisabled = (<ISelectOptionItem>element).optionDisabled;
data.optionText.textContent = optionText;
data.root.setAttribute('aria-label', nls.localize('selectAriaOption', "{0}", optionText) + ',.');
if (typeof element.optionDescriptionText === 'string') {
const optionDescriptionId = (optionText.replace(/ /g, '_').toLowerCase() + '_description_' + data.root.id);
data.root.setAttribute('aria-describedby', optionDescriptionId);
data.optionText.setAttribute('aria-describedby', optionDescriptionId);
data.optionDescriptionText.id = optionDescriptionId;
data.optionDescriptionText.setAttribute('aria-label', element.optionDescriptionText);
data.optionDescriptionText.innerText = element.optionDescriptionText;
}
// Workaround for list labels
data.root.setAttribute('aria-selected', 'true');
// pseudo-select disabled option
if (optionDisabled) {
dom.addClass((<HTMLElement>data.root), 'option-disabled');
+13 -5
View File
@@ -46,7 +46,6 @@ export abstract class Panel implements IView {
protected _expanded: boolean;
protected disposables: IDisposable[] = [];
private expandedSize: number | undefined = undefined;
private _headerVisible = true;
private _minimumBodySize: number;
private _maximumBodySize: number;
@@ -55,6 +54,9 @@ export abstract class Panel implements IView {
private header: HTMLElement;
private cachedExpandedSize: number | undefined = undefined;
private cachedBodySize: number | undefined = undefined;
private _onDidChange = new Emitter<number | undefined>();
readonly onDidChange: Event<number | undefined> = this._onDidChange.event;
@@ -129,7 +131,7 @@ export abstract class Panel implements IView {
this._expanded = !!expanded;
this.updateHeader();
this._onDidChange.fire(expanded ? this.expandedSize : undefined);
this._onDidChange.fire(expanded ? this.cachedExpandedSize : undefined);
}
get headerVisible(): boolean {
@@ -190,8 +192,14 @@ export abstract class Panel implements IView {
const headerSize = this.headerVisible ? Panel.HEADER_SIZE : 0;
if (this.isExpanded()) {
this.layoutBody(size - headerSize);
this.expandedSize = size;
const bodySize = size - headerSize;
if (bodySize !== this.cachedBodySize) {
this.layoutBody(bodySize);
this.cachedBodySize = bodySize;
}
this.cachedExpandedSize = size;
}
}
@@ -326,7 +334,7 @@ class PanelDraggable extends Disposable {
}
private render(): void {
let backgroundColor: string = null;
let backgroundColor: string | null = null;
if (this.dragOverCounter > 0) {
backgroundColor = (this.panel.dropBackground || PanelDraggable.DefaultDragOverBackgroundColor).toString();
+2 -2
View File
@@ -60,7 +60,7 @@ export class Action implements IAction {
protected _enabled: boolean;
protected _checked: boolean;
protected _radio: boolean;
protected _actionCallback: (event?: any) => Thenable<any>;
protected _actionCallback?: (event?: any) => Thenable<any>;
constructor(id: string, label: string = '', cssClass: string = '', enabled: boolean = true, actionCallback?: (event?: any) => Thenable<any>) {
this._id = id;
@@ -165,7 +165,7 @@ export class Action implements IAction {
}
run(event?: any, _data?: ITelemetryData): Thenable<any> {
if (this._actionCallback !== void 0) {
if (this._actionCallback) {
return this._actionCallback(event);
}
+18 -11
View File
@@ -138,7 +138,7 @@ function _sort<T>(a: T[], compare: Compare<T>, lo: number, hi: number, aux: T[])
export function groupBy<T>(data: T[], compare: (a: T, b: T) => number): T[][] {
const result: T[][] = [];
let currentGroup: T[];
let currentGroup: T[] | undefined = undefined;
for (const element of mergeSort(data.slice(0), compare)) {
if (!currentGroup || compare(currentGroup[0], element) !== 0) {
currentGroup = [element];
@@ -388,7 +388,9 @@ export function firstIndex<T>(array: T[] | ReadonlyArray<T>, fn: (item: T) => bo
return -1;
}
export function first<T>(array: T[] | ReadonlyArray<T>, fn: (item: T) => boolean, notFoundValue: T = null): T {
export function first<T>(array: T[] | ReadonlyArray<T>, fn: (item: T) => boolean, notFoundValue: T): T;
export function first<T>(array: T[] | ReadonlyArray<T>, fn: (item: T) => boolean): T | null;
export function first<T>(array: T[] | ReadonlyArray<T>, fn: (item: T) => boolean, notFoundValue: T | null = null): T | null {
const index = firstIndex(array, fn);
return index < 0 ? notFoundValue : array[index];
}
@@ -404,7 +406,7 @@ export function commonPrefixLength<T>(one: T[], other: T[], equals: (a: T, b: T)
}
export function flatten<T>(arr: T[][]): T[] {
return [].concat(...arr);
return (<T[]>[]).concat(...arr);
}
export function range(to: number): number[];
@@ -481,15 +483,20 @@ export function arrayInsert<T>(target: T[], insertIndex: number, insertArr: T[])
* Uses Fisher-Yates shuffle to shuffle the given array
* @param array
*/
export function shuffle<T>(array: T[], seed?: number): void {
// Seeded random number generator in JS. Modified from:
// https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript
const random = () => {
var x = Math.sin(seed++) * 179426549; // throw away most significant digits and reduce any potential bias
return x - Math.floor(x);
};
export function shuffle<T>(array: T[], _seed?: number): void {
let rand: () => number;
const rand = typeof seed === 'number' ? random : Math.random;
if (typeof _seed === 'number') {
let seed = _seed;
// Seeded random number generator in JS. Modified from:
// https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript
rand = () => {
var x = Math.sin(seed++) * 179426549; // throw away most significant digits and reduce any potential bias
return x - Math.floor(x);
};
} else {
rand = Math.random;
}
for (let i = array.length - 1; i > 0; i -= 1) {
let j = Math.floor(rand() * (i + 1));
+43 -21
View File
@@ -91,9 +91,9 @@ export interface ITask<T> {
*/
export class Throttler {
private activePromise: TPromise;
private queuedPromise: TPromise;
private queuedPromiseFactory: ITask<TPromise>;
private activePromise: TPromise | null;
private queuedPromise: TPromise | null;
private queuedPromiseFactory: ITask<TPromise> | null;
constructor() {
this.activePromise = null;
@@ -109,26 +109,26 @@ export class Throttler {
const onComplete = () => {
this.queuedPromise = null;
const result = this.queue(this.queuedPromiseFactory);
const result = this.queue(this.queuedPromiseFactory!);
this.queuedPromiseFactory = null;
return result;
};
this.queuedPromise = new TPromise(c => {
this.activePromise.then(onComplete, onComplete).then(c);
this.activePromise!.then(onComplete, onComplete).then(c);
});
}
return new TPromise((c, e) => {
this.queuedPromise.then(c, e);
this.queuedPromise!.then(c, e);
});
}
this.activePromise = promiseFactory();
return new TPromise((c, e) => {
this.activePromise.then((result: any) => {
this.activePromise!.then((result: any) => {
this.activePromise = null;
c(result);
}, (err: any) => {
@@ -175,10 +175,10 @@ export class SimpleThrottler {
export class Delayer<T> {
private timeout: any;
private completionPromise: TPromise;
private doResolve: ValueCallback;
private completionPromise: TPromise | null;
private doResolve: ValueCallback | null;
private doReject: (err: any) => void;
private task: ITask<T | TPromise<T>>;
private task: ITask<T | TPromise<T>> | null;
constructor(public defaultDelay: number) {
this.timeout = null;
@@ -198,7 +198,7 @@ export class Delayer<T> {
}).then(() => {
this.completionPromise = null;
this.doResolve = null;
const task = this.task;
const task = this.task!;
this.task = null;
return task();
@@ -207,7 +207,7 @@ export class Delayer<T> {
this.timeout = setTimeout(() => {
this.timeout = null;
this.doResolve(null);
this.doResolve!(null);
}, delay);
return this.completionPromise;
@@ -363,11 +363,11 @@ export function sequence<T>(promiseFactories: ITask<Thenable<T>>[]): Promise<T[]
return Promise.resolve(null).then(thenHandler);
}
export function first<T>(promiseFactories: ITask<Thenable<T>>[], shouldStop: (t: T) => boolean = t => !!t, defaultValue: T = null): Promise<T> {
export function first<T>(promiseFactories: ITask<Thenable<T>>[], shouldStop: (t: T) => boolean = t => !!t, defaultValue: T | null = null): Promise<T | null> {
let index = 0;
const len = promiseFactories.length;
const loop: () => Promise<T> = () => {
const loop: () => Promise<T | null> = () => {
if (index >= len) {
return Promise.resolve(defaultValue);
}
@@ -429,7 +429,7 @@ export class Limiter<T> {
private consume(): void {
while (this.outstandingPromises.length && this.runningPromises < this.maxDegreeOfParalellism) {
const iLimitedTask = this.outstandingPromises.shift();
const iLimitedTask = this.outstandingPromises.shift()!;
this.runningPromises++;
const promise = iLimitedTask.factory();
@@ -567,7 +567,7 @@ export class IntervalTimer extends Disposable {
export class RunOnceScheduler {
protected runner: (...args: any[]) => void;
protected runner: ((...args: any[]) => void) | null;
private timeoutToken: any;
private timeout: number;
@@ -621,7 +621,9 @@ export class RunOnceScheduler {
}
protected doRun(): void {
this.runner();
if (this.runner) {
this.runner();
}
}
}
@@ -644,7 +646,9 @@ export class RunOnceWorker<T> extends RunOnceScheduler {
const units = this.units;
this.units = [];
this.runner(units);
if (this.runner) {
this.runner(units);
}
}
dispose(): void {
@@ -689,12 +693,30 @@ declare function cancelIdleCallback(handle: number): void;
});
runWhenIdle = (runner, timeout = 0) => {
let handle = setTimeout(() => runner(dummyIdle), timeout);
return { dispose() { clearTimeout(handle); handle = undefined; } };
let disposed = false;
return {
dispose() {
if (disposed) {
return;
}
disposed = true;
clearTimeout(handle);
}
};
};
} else {
runWhenIdle = (runner, timeout?) => {
let handle = requestIdleCallback(runner, typeof timeout === 'number' ? { timeout } : undefined);
return { dispose() { cancelIdleCallback(handle); handle = undefined; } };
let handle: number = requestIdleCallback(runner, typeof timeout === 'number' ? { timeout } : undefined);
let disposed = false;
return {
dispose() {
if (disposed) {
return;
}
disposed = true;
cancelIdleCallback(handle);
}
};
};
}
})();
+1 -1
View File
@@ -13,7 +13,7 @@ export interface CacheResult<T> {
export class Cache<T> {
private result: CacheResult<T> = null;
private result: CacheResult<T> | null = null;
constructor(private task: (ct: CancellationToken) => Promise<T>) { }
get(): CacheResult<T> {
+2 -2
View File
@@ -51,7 +51,7 @@ export namespace CancellationToken {
class MutableToken implements CancellationToken {
private _isCancelled: boolean = false;
private _emitter: Emitter<any>;
private _emitter: Emitter<any> | null = null;
public cancel() {
if (!this._isCancelled) {
@@ -80,7 +80,7 @@ class MutableToken implements CancellationToken {
public dispose(): void {
if (this._emitter) {
this._emitter.dispose();
this._emitter = undefined;
this._emitter = null;
}
}
}
+1 -1
View File
@@ -45,7 +45,7 @@ export function size<T>(from: IStringDictionary<T> | INumberDictionary<T>): numb
return count;
}
export function first<T>(from: IStringDictionary<T> | INumberDictionary<T>): T {
export function first<T>(from: IStringDictionary<T> | INumberDictionary<T>): T | undefined {
for (let key in from) {
if (hasOwnProperty.call(from, key)) {
return from[key];
+1 -1
View File
@@ -416,7 +416,7 @@ export class Color {
}
toString(): string {
return Color.Format.CSS.format(this);
return '' + Color.Format.CSS.format(this);
}
static getLighterColor(of: Color, relative: Color, factor?: number): Color {
+1 -1
View File
@@ -98,7 +98,7 @@ function noIntlCompareFileExtensions(one: string, other: string): number {
}
function extractNameAndExtension(str?: string): [string, string] {
const match = str ? FileNameMatch.exec(str) : [] as RegExpExecArray;
const match = str ? FileNameMatch.exec(str) as Array<string> : ([] as Array<string>);
return [(match && match[1]) || '', (match && match[3]) || ''];
}
+8 -8
View File
@@ -5,8 +5,8 @@
export function createDecorator(mapFn: (fn: Function, key: string) => Function): Function {
return (target: any, key: string, descriptor: any) => {
let fnKey: string = null;
let fn: Function = null;
let fnKey: string | null = null;
let fn: Function | null = null;
if (typeof descriptor.value === 'function') {
fnKey = 'value';
@@ -20,19 +20,19 @@ export function createDecorator(mapFn: (fn: Function, key: string) => Function):
throw new Error('not supported');
}
descriptor[fnKey] = mapFn(fn, key);
descriptor[fnKey!] = mapFn(fn, key);
};
}
export function memoize(target: any, key: string, descriptor: any) {
let fnKey: string = null;
let fn: Function = null;
let fnKey: string | null = null;
let fn: Function | null = null;
if (typeof descriptor.value === 'function') {
fnKey = 'value';
fn = descriptor.value;
if (fn.length !== 0) {
if (fn!.length !== 0) {
console.warn('Memoize should only be used in functions with zero parameters');
}
} else if (typeof descriptor.get === 'function') {
@@ -46,13 +46,13 @@ export function memoize(target: any, key: string, descriptor: any) {
const memoizeKey = `$memoize$${key}`;
descriptor[fnKey] = function (...args: any[]) {
descriptor[fnKey!] = function (...args: any[]) {
if (!this.hasOwnProperty(memoizeKey)) {
Object.defineProperty(this, memoizeKey, {
configurable: false,
enumerable: false,
writable: false,
value: fn.apply(this, args)
value: fn!.apply(this, args)
});
}
+9 -10
View File
@@ -216,7 +216,7 @@ export class LcsDiff {
private OriginalSequence: ISequence;
private ModifiedSequence: ISequence;
private ContinueProcessingPredicate: IContinueProcessingPredicate;
private ContinueProcessingPredicate: IContinueProcessingPredicate | null;
private m_forwardHistory: number[][];
private m_reverseHistory: number[][];
@@ -224,7 +224,7 @@ export class LcsDiff {
/**
* Constructs the DiffFinder
*/
constructor(originalSequence: ISequence, newSequence: ISequence, continueProcessingPredicate: IContinueProcessingPredicate = null) {
constructor(originalSequence: ISequence, newSequence: ISequence, continueProcessingPredicate: IContinueProcessingPredicate | null = null) {
this.OriginalSequence = originalSequence;
this.ModifiedSequence = newSequence;
this.ContinueProcessingPredicate = continueProcessingPredicate;
@@ -362,7 +362,7 @@ export class LcsDiff {
originalIndex: number, originalEnd: number, midOriginalArr: number[],
modifiedIndex: number, modifiedEnd: number, midModifiedArr: number[],
deltaIsEven: boolean, quitEarlyArr: boolean[]): DiffChange[] {
let forwardChanges: DiffChange[] = null, reverseChanges: DiffChange[] = null;
let forwardChanges: DiffChange[] | null = null, reverseChanges: DiffChange[] | null = null;
// First, walk backward through the forward diagonals history
let changeHelper = new DiffChangeHelper();
@@ -498,7 +498,7 @@ export class LcsDiff {
* @returns The diff changes, if available, otherwise null
*/
private ComputeRecursionPoint(originalStart: number, originalEnd: number, modifiedStart: number, modifiedEnd: number, midOriginalArr: number[], midModifiedArr: number[], quitEarlyArr: boolean[]) {
let originalIndex: number, modifiedIndex: number;
let originalIndex = 0, modifiedIndex = 0;
let diagonalForwardStart = 0, diagonalForwardEnd = 0;
let diagonalReverseStart = 0, diagonalReverseEnd = 0;
let numDifferences: number;
@@ -763,9 +763,9 @@ export class LcsDiff {
change.modifiedStart++;
}
let mergedChangeArr: DiffChange[] = [null];
let mergedChangeArr: (DiffChange | null)[] = [null];
if (i < changes.length - 1 && this.ChangesOverlap(changes[i], changes[i + 1], mergedChangeArr)) {
changes[i] = mergedChangeArr[0];
changes[i] = mergedChangeArr[0]!;
changes.splice(i + 1, 1);
i--;
continue;
@@ -882,7 +882,6 @@ export class LcsDiff {
*/
private ConcatenateChanges(left: DiffChange[], right: DiffChange[]): DiffChange[] {
let mergedChangeArr: DiffChange[] = [];
let result: DiffChange[] = null;
if (left.length === 0 || right.length === 0) {
return (right.length > 0) ? right : left;
@@ -891,14 +890,14 @@ export class LcsDiff {
// might recurse in the middle of a change thereby splitting it into
// two changes. Here in the combining stage, we detect and fuse those
// changes back together
result = new Array<DiffChange>(left.length + right.length - 1);
let result = new Array<DiffChange>(left.length + right.length - 1);
MyArray.Copy(left, 0, result, 0, left.length - 1);
result[left.length - 1] = mergedChangeArr[0];
MyArray.Copy(right, 1, result, left.length, right.length - 1);
return result;
} else {
result = new Array<DiffChange>(left.length + right.length);
let result = new Array<DiffChange>(left.length + right.length);
MyArray.Copy(left, 0, result, 0, left.length);
MyArray.Copy(right, 0, result, left.length, right.length);
@@ -914,7 +913,7 @@ export class LcsDiff {
* @param mergedChange The merged change if the two overlap, null otherwise
* @returns True if the two changes overlap
*/
private ChangesOverlap(left: DiffChange, right: DiffChange, mergedChangeArr: DiffChange[]): boolean {
private ChangesOverlap(left: DiffChange, right: DiffChange, mergedChangeArr: (DiffChange | null)[]): boolean {
Debug.Assert(left.originalStart <= right.originalStart, 'Left change is not less than or equal to right change');
Debug.Assert(left.modifiedStart <= right.modifiedStart, 'Left change is not less than or equal to right change');
-23
View File
@@ -3,7 +3,6 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IAction } from 'vs/base/common/actions';
import { TPromise, IPromiseError, IPromiseErrorDetail } from 'vs/base/common/winjs.base';
// ------ BEGIN Hook up error listeners to winjs promises
@@ -233,28 +232,6 @@ export function disposed(what: string): Error {
return result;
}
export interface IErrorOptions {
actions?: IAction[];
}
export interface IErrorWithActions {
actions?: IAction[];
}
export function isErrorWithActions(obj: any): obj is IErrorWithActions {
return obj instanceof Error && Array.isArray((obj as IErrorWithActions).actions);
}
export function create(message: string, options: IErrorOptions = Object.create(null)): Error & IErrorWithActions {
const result = new Error(message);
if (options.actions) {
(<IErrorWithActions>result).actions = options.actions;
}
return result;
}
export function getErrorMessage(err: any): string {
if (!err) {
return 'Error';
+28
View File
@@ -0,0 +1,28 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IAction } from 'vs/base/common/actions';
export interface IErrorOptions {
actions?: IAction[];
}
export interface IErrorWithActions {
actions?: IAction[];
}
export function isErrorWithActions(obj: any): obj is IErrorWithActions {
return obj instanceof Error && Array.isArray((obj as IErrorWithActions).actions);
}
export function createErrorWithActions(message: string, options: IErrorOptions = Object.create(null)): Error & IErrorWithActions {
const result = new Error(message);
if (options.actions) {
(<IErrorWithActions>result).actions = options.actions;
}
return result;
}
+35 -23
View File
@@ -56,13 +56,16 @@ export class Emitter<T> {
private static readonly _noop = function () { };
private _event: Event<T>;
private _event: Event<T> | null;
private _disposed: boolean;
private _deliveryQueue: [Listener, T][];
protected _listeners: LinkedList<Listener>;
constructor(private _options?: EmitterOptions) {
private _deliveryQueue: [Listener, (T | undefined)][] | null;
protected _listeners: LinkedList<Listener> | null;
constructor(private _options: EmitterOptions | null = null) {
this._event = null;
this._disposed = false;
this._deliveryQueue = null;
this._listeners = null;
}
/**
@@ -98,8 +101,11 @@ export class Emitter<T> {
result.dispose = Emitter._noop;
if (!this._disposed) {
remove();
if (this._options && this._options.onLastListenerRemove && this._listeners.isEmpty()) {
this._options.onLastListenerRemove(this);
if (this._options && this._options.onLastListenerRemove) {
const hasListeners = (this._listeners && !this._listeners.isEmpty());
if (!hasListeners) {
this._options.onLastListenerRemove(this);
}
}
}
}
@@ -133,7 +139,7 @@ export class Emitter<T> {
}
while (this._deliveryQueue.length > 0) {
const [listener, event] = this._deliveryQueue.shift();
const [listener, event] = this._deliveryQueue.shift()!;
try {
if (typeof listener === 'function') {
listener.call(undefined, event);
@@ -149,7 +155,7 @@ export class Emitter<T> {
dispose() {
if (this._listeners) {
this._listeners = undefined;
this._listeners = null;
}
if (this._deliveryQueue) {
this._deliveryQueue.length = 0;
@@ -184,7 +190,7 @@ export class AsyncEmitter<T extends IWaitUntil> extends Emitter<T> {
}
while (this._asyncDeliveryQueue.length > 0) {
const [listener, event, thenables] = this._asyncDeliveryQueue.shift();
const [listener, event, thenables] = this._asyncDeliveryQueue.shift()!;
try {
if (typeof listener === 'function') {
listener.call(undefined, event);
@@ -208,7 +214,7 @@ export class EventMultiplexer<T> implements IDisposable {
private readonly emitter: Emitter<T>;
private hasListeners = false;
private events: { event: Event<T>; listener: IDisposable; }[] = [];
private events: { event: Event<T>; listener: IDisposable | null; }[] = [];
constructor() {
this.emitter = new Emitter<T>({
@@ -251,12 +257,14 @@ export class EventMultiplexer<T> implements IDisposable {
this.events.forEach(e => this.unhook(e));
}
private hook(e: { event: Event<T>; listener: IDisposable; }): void {
private hook(e: { event: Event<T>; listener: IDisposable | null; }): void {
e.listener = e.event(r => this.emitter.fire(r));
}
private unhook(e: { event: Event<T>; listener: IDisposable; }): void {
e.listener.dispose();
private unhook(e: { event: Event<T>; listener: IDisposable | null; }): void {
if (e.listener) {
e.listener.dispose();
}
e.listener = null;
}
@@ -270,7 +278,7 @@ export function fromPromise<T =any>(promise: Thenable<T>): Event<T> {
let shouldEmit = false;
promise
.then(null, () => null)
.then(undefined, () => null)
.then(() => {
if (!shouldEmit) {
setTimeout(() => emitter.fire(), 0);
@@ -321,11 +329,11 @@ export function anyEvent<T>(...events: Event<T>[]): Event<T> {
}
export function debounceEvent<T>(event: Event<T>, merger: (last: T, event: T) => T, delay?: number, leading?: boolean): Event<T>;
export function debounceEvent<I, O>(event: Event<I>, merger: (last: O, event: I) => O, delay?: number, leading?: boolean): Event<O>;
export function debounceEvent<I, O>(event: Event<I>, merger: (last: O, event: I) => O, delay: number = 100, leading = false): Event<O> {
export function debounceEvent<I, O>(event: Event<I>, merger: (last: O | undefined, event: I) => O, delay?: number, leading?: boolean): Event<O>;
export function debounceEvent<I, O>(event: Event<I>, merger: (last: O | undefined, event: I) => O, delay: number = 100, leading = false): Event<O> {
let subscription: IDisposable;
let output: O = undefined;
let output: O | undefined = undefined;
let handle: any = undefined;
let numDebouncedCalls = 0;
@@ -497,10 +505,10 @@ export function stopwatch<T>(event: Event<T>): Event<number> {
* // 4
* ```
*/
export function buffer<T>(event: Event<T>, nextTick = false, buffer: T[] = []): Event<T> {
buffer = buffer.slice();
export function buffer<T>(event: Event<T>, nextTick = false, _buffer: T[] = []): Event<T> {
let buffer: T[] | null = _buffer.slice();
let listener = event(e => {
let listener: IDisposable | null = event(e => {
if (buffer) {
buffer.push(e);
} else {
@@ -509,7 +517,9 @@ export function buffer<T>(event: Event<T>, nextTick = false, buffer: T[] = []):
});
const flush = () => {
buffer.forEach(e => emitter.fire(e));
if (buffer) {
buffer.forEach(e => emitter.fire(e));
}
buffer = null;
};
@@ -531,7 +541,9 @@ export function buffer<T>(event: Event<T>, nextTick = false, buffer: T[] = []):
},
onLastListenerRemove() {
listener.dispose();
if (listener) {
listener.dispose();
}
listener = null;
}
});
+24 -24
View File
@@ -9,7 +9,7 @@ import * as strings from 'vs/base/common/strings';
export interface IFilter {
// Returns null if word doesn't match.
(word: string, wordToMatchAgainst: string): IMatch[];
(word: string, wordToMatchAgainst: string): IMatch[] | null;
}
export interface IMatch {
@@ -26,7 +26,7 @@ export interface IMatch {
* filter.
*/
export function or(...filter: IFilter[]): IFilter {
return function (word: string, wordToMatchAgainst: string): IMatch[] {
return function (word: string, wordToMatchAgainst: string): IMatch[] | null {
for (let i = 0, len = filter.length; i < len; i++) {
let match = filter[i](word, wordToMatchAgainst);
if (match) {
@@ -42,7 +42,7 @@ export function or(...filter: IFilter[]): IFilter {
export const matchesStrictPrefix: IFilter = _matchesPrefix.bind(undefined, false);
export const matchesPrefix: IFilter = _matchesPrefix.bind(undefined, true);
function _matchesPrefix(ignoreCase: boolean, word: string, wordToMatchAgainst: string): IMatch[] {
function _matchesPrefix(ignoreCase: boolean, word: string, wordToMatchAgainst: string): IMatch[] | null {
if (!wordToMatchAgainst || wordToMatchAgainst.length < word.length) {
return null;
}
@@ -63,7 +63,7 @@ function _matchesPrefix(ignoreCase: boolean, word: string, wordToMatchAgainst: s
// Contiguous Substring
export function matchesContiguousSubString(word: string, wordToMatchAgainst: string): IMatch[] {
export function matchesContiguousSubString(word: string, wordToMatchAgainst: string): IMatch[] | null {
let index = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase());
if (index === -1) {
return null;
@@ -74,18 +74,18 @@ export function matchesContiguousSubString(word: string, wordToMatchAgainst: str
// Substring
export function matchesSubString(word: string, wordToMatchAgainst: string): IMatch[] {
export function matchesSubString(word: string, wordToMatchAgainst: string): IMatch[] | null {
return _matchesSubString(word.toLowerCase(), wordToMatchAgainst.toLowerCase(), 0, 0);
}
function _matchesSubString(word: string, wordToMatchAgainst: string, i: number, j: number): IMatch[] {
function _matchesSubString(word: string, wordToMatchAgainst: string, i: number, j: number): IMatch[] | null {
if (i === word.length) {
return [];
} else if (j === wordToMatchAgainst.length) {
return null;
} else {
if (word[i] === wordToMatchAgainst[j]) {
let result: IMatch[] = null;
let result: IMatch[] | null = null;
if (result = _matchesSubString(word, wordToMatchAgainst, i + 1, j + 1)) {
return join({ start: j, end: j + 1 }, result);
}
@@ -144,7 +144,7 @@ function nextAnchor(camelCaseWord: string, start: number): number {
return camelCaseWord.length;
}
function _matchesCamelCase(word: string, camelCaseWord: string, i: number, j: number): IMatch[] {
function _matchesCamelCase(word: string, camelCaseWord: string, i: number, j: number): IMatch[] | null {
if (i === word.length) {
return [];
} else if (j === camelCaseWord.length) {
@@ -152,7 +152,7 @@ function _matchesCamelCase(word: string, camelCaseWord: string, i: number, j: nu
} else if (word[i] !== camelCaseWord[j].toLowerCase()) {
return null;
} else {
let result: IMatch[] = null;
let result: IMatch[] | null = null;
let nextUpperIndex = j + 1;
result = _matchesCamelCase(word, camelCaseWord, i + 1, j + 1);
while (!result && (nextUpperIndex = nextAnchor(camelCaseWord, nextUpperIndex)) < camelCaseWord.length) {
@@ -222,7 +222,7 @@ function isCamelCasePattern(word: string): boolean {
}
}
export function matchesCamelCase(word: string, camelCaseWord: string): IMatch[] {
export function matchesCamelCase(word: string, camelCaseWord: string): IMatch[] | null {
if (!camelCaseWord) {
return null;
}
@@ -251,7 +251,7 @@ export function matchesCamelCase(word: string, camelCaseWord: string): IMatch[]
camelCaseWord = camelCaseWord.toLowerCase();
}
let result: IMatch[] = null;
let result: IMatch[] | null = null;
let i = 0;
word = word.toLowerCase();
@@ -267,12 +267,12 @@ export function matchesCamelCase(word: string, camelCaseWord: string): IMatch[]
// Otherwise also matches sub string of the word with beginnings of the words in the target. E.g. "gp" or "g p" will match "Git: Pull"
// Useful in cases where the target is words (e.g. command labels)
export function matchesWords(word: string, target: string, contiguous: boolean = false): IMatch[] {
export function matchesWords(word: string, target: string, contiguous: boolean = false): IMatch[] | null {
if (!target || target.length === 0) {
return null;
}
let result: IMatch[] = null;
let result: IMatch[] | null = null;
let i = 0;
word = word.toLowerCase();
@@ -284,7 +284,7 @@ export function matchesWords(word: string, target: string, contiguous: boolean =
return result;
}
function _matchesWords(word: string, target: string, i: number, j: number, contiguous: boolean): IMatch[] {
function _matchesWords(word: string, target: string, i: number, j: number, contiguous: boolean): IMatch[] | null {
if (i === word.length) {
return [];
} else if (j === target.length) {
@@ -292,7 +292,7 @@ function _matchesWords(word: string, target: string, i: number, j: number, conti
} else if (word[i] !== target[j]) {
return null;
} else {
let result: IMatch[] = null;
let result: IMatch[] | null = null;
let nextWordIndex = j + 1;
result = _matchesWords(word, target, i + 1, j + 1, contiguous);
if (!contiguous) {
@@ -321,7 +321,7 @@ export const fuzzyContiguousFilter = or(matchesPrefix, matchesCamelCase, matches
const fuzzySeparateFilter = or(matchesPrefix, matchesCamelCase, matchesSubString);
const fuzzyRegExpCache = new LRUCache<string, RegExp>(10000); // bounded to 10000 elements
export function matchesFuzzy(word: string, wordToMatchAgainst: string, enableSeparateSubstringMatching = false): IMatch[] {
export function matchesFuzzy(word: string, wordToMatchAgainst: string, enableSeparateSubstringMatching = false): IMatch[] | null {
if (typeof word !== 'string' || typeof wordToMatchAgainst !== 'string') {
return null; // return early for invalid input
}
@@ -334,7 +334,7 @@ export function matchesFuzzy(word: string, wordToMatchAgainst: string, enableSep
}
// RegExp Filter
let match: RegExpExecArray = regexp.exec(wordToMatchAgainst);
let match = regexp.exec(wordToMatchAgainst);
if (match) {
return [{ start: match.index, end: match.index + match[0].length }];
}
@@ -372,7 +372,7 @@ export function createMatches(offsetOrScore: number[] | FuzzyScore): IMatch[] {
} else {
offsets = offsetOrScore as number[];
}
let last: IMatch;
let last: IMatch | undefined;
for (const pos of offsets) {
if (last && last.end === pos) {
last.end += 1;
@@ -466,7 +466,7 @@ export interface FuzzyScorer {
(pattern: string, lowPattern: string, patternPos: number, word: string, lowWord: string, wordPos: number, firstMatchCanBeWeak: boolean): FuzzyScore;
}
export function fuzzyScore(pattern: string, lowPattern: string, patternPos: number, word: string, lowWord: string, wordPos: number, firstMatchCanBeWeak: boolean): FuzzyScore {
export function fuzzyScore(pattern: string, lowPattern: string, patternPos: number, word: string, lowWord: string, wordPos: number, firstMatchCanBeWeak: boolean): FuzzyScore | undefined {
const patternLen = pattern.length > 100 ? 100 : pattern.length;
const wordLen = word.length > 100 ? 100 : word.length;
@@ -711,16 +711,16 @@ class LazyArray {
//#region --- graceful ---
export function fuzzyScoreGracefulAggressive(pattern: string, lowPattern: string, patternPos: number, word: string, lowWord: string, wordPos: number, firstMatchCanBeWeak: boolean): FuzzyScore {
export function fuzzyScoreGracefulAggressive(pattern: string, lowPattern: string, patternPos: number, word: string, lowWord: string, wordPos: number, firstMatchCanBeWeak: boolean): FuzzyScore | undefined {
return fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word, lowWord, wordPos, true, firstMatchCanBeWeak);
}
export function fuzzyScoreGraceful(pattern: string, lowPattern: string, patternPos: number, word: string, lowWord: string, wordPos: number, firstMatchCanBeWeak: boolean): FuzzyScore {
export function fuzzyScoreGraceful(pattern: string, lowPattern: string, patternPos: number, word: string, lowWord: string, wordPos: number, firstMatchCanBeWeak: boolean): FuzzyScore | undefined {
return fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word, lowWord, wordPos, false, firstMatchCanBeWeak);
}
function fuzzyScoreWithPermutations(pattern: string, lowPattern: string, patternPos: number, word: string, lowWord: string, wordPos: number, aggressive: boolean, firstMatchCanBeWeak: boolean): FuzzyScore {
let top: [number, number[]] = fuzzyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos, firstMatchCanBeWeak);
function fuzzyScoreWithPermutations(pattern: string, lowPattern: string, patternPos: number, word: string, lowWord: string, wordPos: number, aggressive: boolean, firstMatchCanBeWeak: boolean): FuzzyScore | undefined {
let top = fuzzyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos, firstMatchCanBeWeak);
if (top && !aggressive) {
// when using the original pattern yield a result we`
@@ -752,7 +752,7 @@ function fuzzyScoreWithPermutations(pattern: string, lowPattern: string, pattern
return top;
}
function nextTypoPermutation(pattern: string, patternPos: number): string {
function nextTypoPermutation(pattern: string, patternPos: number): string | undefined {
if (patternPos + 1 >= pattern.length) {
return undefined;
+16 -10
View File
@@ -248,7 +248,7 @@ const T5 = /^([\w\.-]+(\/[\w\.-]+)*)\/?$/; // something/else
export type ParsedPattern = (path: string, basename?: string) => boolean;
// The ParsedExpression returns a Promise iff hasSibling returns a Promise.
export type ParsedExpression = (path: string, basename?: string, hasSibling?: (name: string) => boolean | TPromise<boolean>) => string | TPromise<string> /* the matching pattern */;
export type ParsedExpression = (path: string, basename?: string, hasSibling?: (name: string) => boolean | TPromise<boolean>) => string | null | TPromise<string | null> /* the matching pattern */;
export interface IGlobOptions {
/**
@@ -258,14 +258,14 @@ export interface IGlobOptions {
}
interface ParsedStringPattern {
(path: string, basename: string): string | TPromise<string> /* the matching pattern */;
(path: string, basename: string): string | null | TPromise<string | null> /* the matching pattern */;
basenames?: string[];
patterns?: string[];
allBasenames?: string[];
allPaths?: string[];
}
interface ParsedExpressionPattern {
(path: string, basename: string, name: string, hasSibling: (name: string) => boolean | TPromise<boolean>): string | TPromise<string> /* the matching pattern */;
(path: string, basename: string, name?: string, hasSibling?: (name: string) => boolean | TPromise<boolean>): string | null | TPromise<string | null> /* the matching pattern */;
requiresSiblings?: boolean;
allBasenames?: string[];
allPaths?: string[];
@@ -277,7 +277,7 @@ const FALSE = function () {
return false;
};
const NULL = function (): string {
const NULL = function (): string | null {
return null;
};
@@ -305,7 +305,7 @@ function parsePattern(arg1: string | IRelativePattern, options: IGlobOptions): P
}
// Check for Trivias
let match: RegExpExecArray;
let match: RegExpExecArray | null;
if (T1.test(pattern)) { // common pattern: **/*.txt just need endsWith check
const base = pattern.substr(4); // '**/*'.length === 4
parsedPattern = function (path, basename) {
@@ -530,7 +530,7 @@ export function isRelativePattern(obj: any): obj is IRelativePattern {
*/
export function parseToAsync(expression: IExpression, options?: IGlobOptions): ParsedExpression {
const parsedExpression = parse(expression, options);
return (path: string, basename?: string, hasSibling?: (name: string) => boolean | TPromise<boolean>): string | TPromise<string> => {
return (path: string, basename?: string, hasSibling?: (name: string) => boolean | TPromise<boolean>): string | null | TPromise<string | null> => {
const result = parsedExpression(path, basename, hasSibling);
return result instanceof TPromise ? result : TPromise.as(result);
};
@@ -554,7 +554,7 @@ function parsedExpression(expression: IExpression, options: IGlobOptions): Parse
return NULL;
}
if (!parsedPatterns.some(parsedPattern => (<ParsedExpressionPattern>parsedPattern).requiresSiblings)) {
if (!parsedPatterns.some(parsedPattern => !!(<ParsedExpressionPattern>parsedPattern).requiresSiblings)) {
if (n === 1) {
return <ParsedStringPattern>parsedPatterns[0];
}
@@ -585,7 +585,7 @@ function parsedExpression(expression: IExpression, options: IGlobOptions): Parse
}
const resultExpression: ParsedStringPattern = function (path: string, basename: string, hasSibling?: (name: string) => boolean | TPromise<boolean>) {
let name: string;
let name: string | undefined = undefined;
for (let i = 0, n = parsedPatterns.length; i < n; i++) {
// Pattern matches path
@@ -665,7 +665,10 @@ function aggregateBasenameMatches(parsedPatterns: (ParsedStringPattern | ParsedE
return parsedPatterns;
}
const basenames = basenamePatterns.reduce<string[]>((all, current) => all.concat((<ParsedStringPattern>current).basenames), []);
const basenames = basenamePatterns.reduce<string[]>((all, current) => {
const basenames = (<ParsedStringPattern>current).basenames;
return basenames ? all.concat(basenames) : all;
}, <string[]>[]);
let patterns: string[];
if (result) {
patterns = [];
@@ -673,7 +676,10 @@ function aggregateBasenameMatches(parsedPatterns: (ParsedStringPattern | ParsedE
patterns.push(result);
}
} else {
patterns = basenamePatterns.reduce((all, current) => all.concat((<ParsedStringPattern>current).patterns), []);
patterns = basenamePatterns.reduce((all, current) => {
const patterns = (<ParsedStringPattern>current).patterns;
return patterns ? all.concat(patterns) : all;
}, <string[]>[]);
}
const aggregate: ParsedStringPattern = function (path, basename) {
if (!path) {
+2 -2
View File
@@ -22,9 +22,9 @@ export function hash(obj: any, hashVal = 0): number {
case 'number':
return numberHash(obj, hashVal);
case 'undefined':
return numberHash(obj, 937);
return numberHash(0, 937);
default:
return numberHash(obj, 617);
return numberHash(0, 617);
}
}
+6 -6
View File
@@ -27,27 +27,27 @@ export class HistoryNavigator<T> implements INavigator<T> {
this._onChange();
}
public next(): T {
public next(): T | null {
return this._navigator.next();
}
public previous(): T {
public previous(): T | null {
return this._navigator.previous();
}
public current(): T {
public current(): T | null {
return this._navigator.current();
}
public parent(): T {
public parent(): null {
return null;
}
public first(): T {
public first(): T | null {
return this._navigator.first();
}
public last(): T {
public last(): T | null {
return this._navigator.last();
}
+38 -31
View File
@@ -3,10 +3,16 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export interface IteratorResult<T> {
readonly done: boolean;
readonly value: T | undefined;
export interface IteratorDefinedResult<T> {
readonly done: false;
readonly value: T;
}
export interface IteratorUndefinedResult {
readonly done: true;
readonly value: undefined;
}
export const FIN: IteratorUndefinedResult = { done: true, value: undefined };
export type IteratorResult<T> = IteratorDefinedResult<T> | IteratorUndefinedResult;
export interface Iterator<T> {
next(): IteratorResult<T>;
@@ -15,7 +21,7 @@ export interface Iterator<T> {
export module Iterator {
const _empty: Iterator<any> = {
next() {
return { done: true, value: undefined };
return FIN;
}
};
@@ -27,7 +33,7 @@ export module Iterator {
return {
next(): IteratorResult<T> {
if (index >= length) {
return { done: true, value: undefined };
return FIN;
}
return { done: false, value: array[index++] };
@@ -48,8 +54,12 @@ export module Iterator {
export function map<T, R>(iterator: Iterator<T>, fn: (t: T) => R): Iterator<R> {
return {
next() {
const { done, value } = iterator.next();
return { done, value: done ? undefined : fn(value) };
const element = iterator.next();
if (element.done) {
return FIN;
} else {
return { done: false, value: fn(element.value) };
}
}
};
}
@@ -58,14 +68,12 @@ export module Iterator {
return {
next() {
while (true) {
const { done, value } = iterator.next();
if (done) {
return { done, value: undefined };
const element = iterator.next();
if (element.done) {
return FIN;
}
if (fn(value)) {
return { done, value };
if (fn(element.value)) {
return { done: false, value: element.value };
}
}
}
@@ -96,7 +104,7 @@ export function getSequenceIterator<T>(arg: Iterator<T> | T[]): Iterator<T> {
}
export interface INextIterator<T> {
next(): T;
next(): T | null;
}
export class ArrayIterator<T> implements INextIterator<T> {
@@ -113,17 +121,17 @@ export class ArrayIterator<T> implements INextIterator<T> {
this.index = index;
}
public first(): T {
public first(): T | null {
this.index = this.start;
return this.current();
}
public next(): T {
public next(): T | null {
this.index = Math.min(this.index + 1, this.end);
return this.current();
}
protected current(): T {
protected current(): T | null {
if (this.index === this.start - 1 || this.index === this.end) {
return null;
}
@@ -138,34 +146,33 @@ export class ArrayNavigator<T> extends ArrayIterator<T> implements INavigator<T>
super(items, start, end, index);
}
public current(): T {
public current(): T | null {
return super.current();
}
public previous(): T {
public previous(): T | null {
this.index = Math.max(this.index - 1, this.start - 1);
return this.current();
}
public first(): T {
public first(): T | null {
this.index = this.start;
return this.current();
}
public last(): T {
public last(): T | null {
this.index = this.end - 1;
return this.current();
}
public parent(): T {
public parent(): T | null {
return null;
}
}
export class MappedIterator<T, R> implements INextIterator<R> {
constructor(protected iterator: INextIterator<T>, protected fn: (item: T) => R) {
constructor(protected iterator: INextIterator<T>, protected fn: (item: T | null) => R) {
// noop
}
@@ -173,12 +180,12 @@ export class MappedIterator<T, R> implements INextIterator<R> {
}
export interface INavigator<T> extends INextIterator<T> {
current(): T;
previous(): T;
parent(): T;
first(): T;
last(): T;
next(): T;
current(): T | null;
previous(): T | null;
parent(): T | null;
first(): T | null;
last(): T | null;
next(): T | null;
}
export class MappedNavigator<T, R> extends MappedIterator<T, R> implements INavigator<R> {
+1 -1
View File
@@ -636,7 +636,7 @@ export interface ParseOptions {
* Therefore always check the errors list to find out if the input was valid.
*/
export function parse(text: string, errors: ParseError[] = [], options?: ParseOptions): any {
let currentProperty: string = null;
let currentProperty: string | null = null;
let currentParent: any = [];
let previousParents: any[] = [];
+1 -1
View File
@@ -410,7 +410,7 @@ export function KeyChord(firstPart: number, secondPart: number): number {
return (firstPart | chordPart) >>> 0;
}
export function createKeybinding(keybinding: number, OS: OperatingSystem): Keybinding {
export function createKeybinding(keybinding: number, OS: OperatingSystem): Keybinding | null {
if (keybinding === 0) {
return null;
}
+4 -4
View File
@@ -80,13 +80,13 @@ export class KeybindingParser {
return [new SimpleKeybinding(mods.ctrl, mods.shift, mods.alt, mods.meta, keyCode), mods.remains];
}
public static parseKeybinding(input: string, OS: OperatingSystem): Keybinding {
public static parseKeybinding(input: string, OS: OperatingSystem): Keybinding | null {
if (!input) {
return null;
}
let [firstPart, remains] = this.parseSimpleKeybinding(input);
let chordPart: SimpleKeybinding = null;
let chordPart: SimpleKeybinding | null = null;
if (remains.length > 0) {
[chordPart] = this.parseSimpleKeybinding(remains);
}
@@ -109,13 +109,13 @@ export class KeybindingParser {
return [new SimpleKeybinding(mods.ctrl, mods.shift, mods.alt, mods.meta, keyCode), mods.remains];
}
static parseUserBinding(input: string): [SimpleKeybinding | ScanCodeBinding, SimpleKeybinding | ScanCodeBinding] {
static parseUserBinding(input: string): [SimpleKeybinding | ScanCodeBinding | null, SimpleKeybinding | ScanCodeBinding | null] {
if (!input) {
return [null, null];
}
let [firstPart, remains] = this.parseSimpleUserBinding(input);
let chordPart: SimpleKeybinding | ScanCodeBinding = null;
let chordPart: SimpleKeybinding | ScanCodeBinding | null = null;
if (remains.length > 0) {
[chordPart] = this.parseSimpleUserBinding(remains);
}
+22 -20
View File
@@ -24,9 +24,9 @@ export interface IUserHomeProvider {
/**
* @deprecated use LabelService instead
*/
export function getPathLabel(resource: URI | string, userHomeProvider: IUserHomeProvider, rootProvider?: IWorkspaceFolderProvider): string {
export function getPathLabel(resource: URI | string, userHomeProvider: IUserHomeProvider, rootProvider?: IWorkspaceFolderProvider): string | undefined {
if (!resource) {
return null;
return undefined;
}
if (typeof resource === 'string') {
@@ -34,23 +34,25 @@ export function getPathLabel(resource: URI | string, userHomeProvider: IUserHome
}
// return early if we can resolve a relative path label from the root
const baseResource = rootProvider ? rootProvider.getWorkspaceFolder(resource) : null;
if (baseResource) {
const hasMultipleRoots = rootProvider.getWorkspace().folders.length > 1;
if (rootProvider) {
const baseResource = rootProvider.getWorkspaceFolder(resource);
if (baseResource) {
const hasMultipleRoots = rootProvider.getWorkspace().folders.length > 1;
let pathLabel: string;
if (isEqual(baseResource.uri, resource, !isLinux)) {
pathLabel = ''; // no label if paths are identical
} else {
pathLabel = normalize(ltrim(resource.path.substr(baseResource.uri.path.length), sep), true);
let pathLabel: string;
if (isEqual(baseResource.uri, resource, !isLinux)) {
pathLabel = ''; // no label if paths are identical
} else {
pathLabel = normalize(ltrim(resource.path.substr(baseResource.uri.path.length), sep)!, true);
}
if (hasMultipleRoots) {
const rootName = (baseResource && baseResource.name) ? baseResource.name : pathsBasename(baseResource.uri.fsPath);
pathLabel = pathLabel ? (rootName + ' • ' + pathLabel) : rootName; // always show root basename if there are multiple
}
return pathLabel;
}
if (hasMultipleRoots) {
const rootName = (baseResource && baseResource.name) ? baseResource.name : pathsBasename(baseResource.uri.fsPath);
pathLabel = pathLabel ? (rootName + ' • ' + pathLabel) : rootName; // always show root basename if there are multiple
}
return pathLabel;
}
// return if the resource is neither file:// nor untitled:// and no baseResource was provided
@@ -72,9 +74,9 @@ export function getPathLabel(resource: URI | string, userHomeProvider: IUserHome
return res;
}
export function getBaseLabel(resource: URI | string): string {
export function getBaseLabel(resource: URI | string): string | undefined {
if (!resource) {
return null;
return undefined;
}
if (typeof resource === 'string') {
@@ -92,7 +94,7 @@ export function getBaseLabel(resource: URI | string): string {
}
function hasDriveLetter(path: string): boolean {
return isWindows && path && path[1] === ':';
return !!(isWindows && path && path[1] === ':');
}
export function normalizeDriveLetter(path: string): string {
+1 -1
View File
@@ -17,7 +17,7 @@ export function isDisposable<E extends object>(thing: E): thing is E & IDisposab
export function dispose<T extends IDisposable>(disposable: T): T;
export function dispose<T extends IDisposable>(...disposables: T[]): T[];
export function dispose<T extends IDisposable>(disposables: T[]): T[];
export function dispose<T extends IDisposable>(first: T | T[], ...rest: T[]): T | T[] {
export function dispose<T extends IDisposable>(first: T | T[], ...rest: T[]): T | T[] | undefined {
if (Array.isArray(first)) {
first.forEach(d => d && d.dispose());
return [];
+21 -21
View File
@@ -3,12 +3,12 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Iterator } from 'vs/base/common/iterator';
import { Iterator, IteratorResult, FIN } from 'vs/base/common/iterator';
class Node<E> {
element: E;
next: Node<E>;
prev: Node<E>;
next: Node<E> | undefined;
prev: Node<E> | undefined;
constructor(element: E) {
this.element = element;
@@ -17,8 +17,8 @@ class Node<E> {
export class LinkedList<E> {
private _first: Node<E>;
private _last: Node<E>;
private _first: Node<E> | undefined;
private _last: Node<E> | undefined;
isEmpty(): boolean {
return !this._first;
@@ -45,7 +45,7 @@ export class LinkedList<E> {
} else if (atTheEnd) {
// push
const oldLast = this._last;
const oldLast = this._last!;
this._last = newNode;
newNode.prev = oldLast;
oldLast.next = newNode;
@@ -59,9 +59,10 @@ export class LinkedList<E> {
}
return () => {
for (let candidate = this._first; candidate instanceof Node; candidate = candidate.next) {
let candidate: Node<E> | undefined = this._first;
while (candidate instanceof Node) {
if (candidate !== newNode) {
candidate = candidate.next;
continue;
}
if (candidate.prev && candidate.next) {
@@ -77,12 +78,12 @@ export class LinkedList<E> {
} else if (!candidate.next) {
// last
this._last = this._last.prev;
this._last = this._last!.prev!;
this._last.next = undefined;
} else if (!candidate.prev) {
// first
this._first = this._first.next;
this._first = this._first!.next!;
this._first.prev = undefined;
}
@@ -93,21 +94,20 @@ export class LinkedList<E> {
}
iterator(): Iterator<E> {
let element = {
done: undefined,
value: undefined,
};
let element: { done: false; value: E; };
let node = this._first;
return {
next(): { done: boolean; value: E } {
next(): IteratorResult<E> {
if (!node) {
element.done = true;
element.value = undefined;
} else {
element.done = false;
element.value = node.element;
node = node.next;
return FIN;
}
if (!element) {
element = { done: false, value: node.element };
} else {
element.value = node.element;
}
node = node.next;
return element;
}
};
+23 -22
View File
@@ -5,7 +5,7 @@
import { URI } from 'vs/base/common/uri';
import { CharCode } from 'vs/base/common/charCode';
import { Iterator } from './iterator';
import { Iterator, IteratorResult, FIN } from './iterator';
export function values<V = any>(set: Set<V>): V[];
export function values<K = any, V = any>(map: Map<K, V>): V[];
@@ -139,11 +139,11 @@ export class PathIterator implements IKeyIterator {
class TernarySearchTreeNode<E> {
segment: string;
value: E;
value: E | undefined;
key: string;
left: TernarySearchTreeNode<E>;
mid: TernarySearchTreeNode<E>;
right: TernarySearchTreeNode<E>;
left: TernarySearchTreeNode<E> | undefined;
mid: TernarySearchTreeNode<E> | undefined;
right: TernarySearchTreeNode<E> | undefined;
isEmpty(): boolean {
return !this.left && !this.mid && !this.right && !this.value;
@@ -161,7 +161,7 @@ export class TernarySearchTree<E> {
}
private _iter: IKeyIterator;
private _root: TernarySearchTreeNode<E>;
private _root: TernarySearchTreeNode<E> | undefined;
constructor(segments: IKeyIterator) {
this._iter = segments;
@@ -171,7 +171,7 @@ export class TernarySearchTree<E> {
this._root = undefined;
}
set(key: string, element: E): E {
set(key: string, element: E): E | undefined {
let iter = this._iter.reset(key);
let node: TernarySearchTreeNode<E>;
@@ -217,7 +217,7 @@ export class TernarySearchTree<E> {
return oldElement;
}
get(key: string): E {
get(key: string): E | undefined {
let iter = this._iter.reset(key);
let node = this._root;
while (node) {
@@ -267,7 +267,7 @@ export class TernarySearchTree<E> {
// clean up empty nodes
while (stack.length > 0 && node.isEmpty()) {
let [dir, parent] = stack.pop();
let [dir, parent] = stack.pop()!;
switch (dir) {
case 1: parent.left = undefined; break;
case 0: parent.mid = undefined; break;
@@ -280,10 +280,10 @@ export class TernarySearchTree<E> {
}
}
findSubstr(key: string): E {
findSubstr(key: string): E | undefined {
let iter = this._iter.reset(key);
let node = this._root;
let candidate: E;
let candidate: E | undefined = undefined;
while (node) {
let val = iter.cmp(node.segment);
if (val > 0) {
@@ -304,7 +304,7 @@ export class TernarySearchTree<E> {
return node && node.value || candidate;
}
findSuperstr(key: string): Iterator<E> {
findSuperstr(key: string): Iterator<E> | undefined {
let iter = this._iter.reset(key);
let node = this._root;
while (node) {
@@ -332,13 +332,10 @@ export class TernarySearchTree<E> {
}
private _nodeIterator(node: TernarySearchTreeNode<E>): Iterator<E> {
let res = {
done: false,
value: undefined
};
let res: { done: false; value: E; };
let idx: number;
let data: E[];
let next = () => {
let next = (): IteratorResult<E> => {
if (!data) {
// lazy till first invocation
data = [];
@@ -346,10 +343,12 @@ export class TernarySearchTree<E> {
this._forEach(node, value => data.push(value));
}
if (idx >= data.length) {
res.done = true;
res.value = undefined;
return FIN;
}
if (!res) {
res = { done: false, value: data[idx++] };
} else {
res.done = false;
res.value = data[idx++];
}
return res;
@@ -361,7 +360,7 @@ export class TernarySearchTree<E> {
this._forEach(this._root, callback);
}
private _forEach(node: TernarySearchTreeNode<E>, callback: (value: E, index: string) => any) {
private _forEach(node: TernarySearchTreeNode<E> | undefined, callback: (value: E, index: string) => any) {
if (node) {
// left
this._forEach(node.left, callback);
@@ -649,7 +648,9 @@ export class LinkedMap<K, V> {
}
this._head = current;
this._size = currentSize;
current.previous = void 0;
if (current) {
current.previous = void 0;
}
}
private addItemFirst(item: Item<K, V>): void {
+1 -1
View File
@@ -218,7 +218,7 @@ export function safeStringify(obj: any): string {
});
}
export function getOrDefault<T, R>(obj: T, fn: (obj: T) => R, defaultValue: R = null): R {
export function getOrDefault<T, R>(obj: T, fn: (obj: T) => R, defaultValue: R | null = null): R | null {
const result = fn(obj);
return typeof result === 'undefined' ? defaultValue : result;
}
+2 -2
View File
@@ -83,7 +83,7 @@ export function normalize(path: string, toOSPath?: boolean): string {
return '.';
}
const wantsBackslash = isWindows && toOSPath;
const wantsBackslash = !!(isWindows && toOSPath);
if (_isNormal(path, wantsBackslash)) {
return path;
}
@@ -398,5 +398,5 @@ export function isAbsolute_win32(path: string): boolean {
}
export function isAbsolute_posix(path: string): boolean {
return path && path.charCodeAt(0) === CharCode.Slash;
return !!(path && path.charCodeAt(0) === CharCode.Slash);
}
+5 -5
View File
@@ -8,9 +8,9 @@ let _isMacintosh = false;
let _isLinux = false;
let _isNative = false;
let _isWeb = false;
let _locale: string = undefined;
let _language: string = undefined;
let _translationsConfigFile: string = undefined;
let _locale: string | undefined = undefined;
let _language: string | undefined = undefined;
let _translationsConfigFile: string | undefined = undefined;
interface NLSConfig {
locale: string;
@@ -129,7 +129,7 @@ export const translationsConfigFile = _translationsConfigFile;
const _globals = (typeof self === 'object' ? self : typeof global === 'object' ? global : {} as any);
export const globals: any = _globals;
let _setImmediate: (callback: (...args: any[]) => void) => number = null;
let _setImmediate: ((callback: (...args: any[]) => void) => number) | null = null;
export function setImmediate(callback: (...args: any[]) => void): number {
if (_setImmediate === null) {
if (globals.setImmediate) {
@@ -140,7 +140,7 @@ export function setImmediate(callback: (...args: any[]) => void): number {
_setImmediate = globals.setTimeout.bind(globals);
}
}
return _setImmediate(callback);
return _setImmediate!(callback);
}
export const enum OperatingSystem {
+1 -1
View File
@@ -72,7 +72,7 @@ export function basename(resource: URI): string {
* @param resource The input URI.
* @returns The URI representing the directory of the input URI.
*/
export function dirname(resource: URI): URI {
export function dirname(resource: URI): URI | null {
let dirname = paths.dirname(resource.path, '/');
if (resource.authority && dirname.length && dirname.charCodeAt(0) !== CharCode.Slash) {
return null; // If a URI contains an authority component, then the path component must either be empty or begin with a CharCode.Slash ("/") character
+5 -2
View File
@@ -182,7 +182,7 @@ export class Scrollable extends Disposable {
private _smoothScrollDuration: number;
private readonly _scheduleAtNextAnimationFrame: (callback: () => void) => IDisposable;
private _state: ScrollState;
private _smoothScrolling: SmoothScrollingOperation;
private _smoothScrolling: SmoothScrollingOperation | null;
private _onScroll = this._register(new Emitter<ScrollEvent>());
public readonly onScroll: Event<ScrollEvent> = this._onScroll.event;
@@ -300,6 +300,9 @@ export class Scrollable extends Disposable {
}
private _performSmoothScrolling(): void {
if (!this._smoothScrolling) {
return;
}
const update = this._smoothScrolling.tick();
const newState = this._state.withScrollPosition(update);
@@ -372,7 +375,7 @@ export class SmoothScrollingOperation {
public to: ISmoothScrollPosition;
public readonly duration: number;
private readonly _startTime: number;
public animationFrameDisposable: IDisposable;
public animationFrameDisposable: IDisposable | null;
private scrollLeft: IAnimation;
private scrollTop: IAnimation;
+5 -5
View File
@@ -78,7 +78,7 @@ export function escapeRegExpCharacters(value: string): string {
* @param haystack string to trim
* @param needle the thing to trim (default is a blank)
*/
export function trim(haystack: string, needle: string = ' '): string {
export function trim(haystack: string, needle: string = ' '): string | undefined {
let trimmed = ltrim(haystack, needle);
return rtrim(trimmed, needle);
}
@@ -88,7 +88,7 @@ export function trim(haystack: string, needle: string = ' '): string {
* @param haystack string to trim
* @param needle the thing to trim
*/
export function ltrim(haystack?: string, needle?: string): string {
export function ltrim(haystack: string, needle: string): string {
if (!haystack || !needle) {
return haystack;
}
@@ -111,7 +111,7 @@ export function ltrim(haystack?: string, needle?: string): string {
* @param haystack string to trim
* @param needle the thing to trim
*/
export function rtrim(haystack?: string, needle?: string): string {
export function rtrim(haystack: string, needle: string): string {
if (!haystack || !needle) {
return haystack;
}
@@ -229,7 +229,7 @@ export function regExpLeadsToEndlessLoop(regexp: RegExp): boolean {
// We check against an empty string. If the regular expression doesn't advance
// (e.g. ends in an endless loop) it will match an empty string.
let match = regexp.exec('');
return (match && <any>regexp.lastIndex === 0);
return !!(match && <any>regexp.lastIndex === 0);
}
export function regExpContainsBackreference(regexpValue: string): boolean {
@@ -621,7 +621,7 @@ export function removeAnsiEscapeCodes(str: string): string {
export const UTF8_BOM_CHARACTER = String.fromCharCode(CharCode.UTF8_BOM);
export function startsWithUTF8BOM(str: string): boolean {
return (str && str.length > 0 && str.charCodeAt(0) === CharCode.UTF8_BOM);
return !!(str && str.length > 0 && str.charCodeAt(0) === CharCode.UTF8_BOM);
}
export function stripUTF8BOM(str: string): string {
+2 -2
View File
@@ -129,14 +129,14 @@ export function areFunctions(...objects: any[]): boolean {
export type TypeConstraint = string | Function;
export function validateConstraints(args: any[], constraints: TypeConstraint[]): void {
export function validateConstraints(args: any[], constraints: (TypeConstraint | undefined)[]): void {
const len = Math.min(args.length, constraints.length);
for (let i = 0; i < len; i++) {
validateConstraint(args[i], constraints[i]);
}
}
export function validateConstraint(arg: any, constraint: TypeConstraint): void {
export function validateConstraint(arg: any, constraint: TypeConstraint | undefined): void {
if (isString(constraint)) {
if (typeof arg !== constraint) {
+5 -5
View File
@@ -141,7 +141,7 @@ export class URI implements UriComponents {
/**
* @internal
*/
protected constructor(scheme: string, authority: string, path: string, query: string, fragment: string);
protected constructor(scheme: string, authority?: string, path?: string, query?: string, fragment?: string);
/**
* @internal
@@ -386,8 +386,8 @@ interface UriState extends UriComponents {
// tslint:disable-next-line:class-name
class _URI extends URI {
_formatted: string = null;
_fsPath: string = null;
_formatted: string | null = null;
_fsPath: string | null = null;
get fsPath(): string {
if (!this._fsPath) {
@@ -465,7 +465,7 @@ const encodeTable: { [ch: number]: string } = {
};
function encodeURIComponentFast(uriComponent: string, allowSlash: boolean, firstPos: number = 0): string {
let res: string = undefined;
let res: string | undefined = undefined;
let nativeEncodePos = -1;
for (let pos = firstPos; pos < uriComponent.length; pos++) {
@@ -526,7 +526,7 @@ function encodeURIComponentFast(uriComponent: string, allowSlash: boolean, first
}
function encodeURIComponentMinimal(path: string): string {
let res: string = undefined;
let res: string | undefined = undefined;
for (let pos = 0; pos < path.length; pos++) {
let code = path.charCodeAt(pos);
if (code === CharCode.Hash || code === CharCode.QuestionMark) {
+48 -55
View File
@@ -84,24 +84,18 @@ class SimpleWorkerProtocol {
public sendMessage(method: string, args: any[]): Promise<any> {
let req = String(++this._lastSentReq);
let reply: IMessageReply = {
resolve: null,
reject: null
};
let result = new Promise<any>((resolve, reject) => {
reply.resolve = resolve;
reply.reject = reject;
return new Promise<any>((resolve, reject) => {
this._pendingReplies[req] = {
resolve: resolve,
reject: reject
};
this._send({
vsWorker: this._workerId,
req: req,
method: method,
args: args
});
});
this._pendingReplies[req] = reply;
this._send({
vsWorker: this._workerId,
req: req,
method: method,
args: args
});
return result;
}
public handleMessage(serializedMessage: string): void {
@@ -110,6 +104,7 @@ class SimpleWorkerProtocol {
message = JSON.parse(serializedMessage);
} catch (e) {
// nothing
return;
}
if (!message || !message.vsWorker) {
return;
@@ -191,8 +186,7 @@ export class SimpleWorkerClient<T> extends Disposable {
constructor(workerFactory: IWorkerFactory, moduleId: string) {
super();
let lazyProxyResolve: (v: T) => void = null;
let lazyProxyReject: (err: any) => void = null;
let lazyProxyReject: ((err: any) => void) | null = null;
this._worker = this._register(workerFactory.create(
'vs/base/common/worker/simpleWorker',
@@ -202,7 +196,9 @@ export class SimpleWorkerClient<T> extends Disposable {
(err: any) => {
// in Firefox, web workers fail lazily :(
// we will reject the proxy
lazyProxyReject(err);
if (lazyProxyReject) {
lazyProxyReject(err);
}
}
));
@@ -227,26 +223,25 @@ export class SimpleWorkerClient<T> extends Disposable {
loaderConfiguration = (<any>self).requirejs.s.contexts._.config;
}
this._lazyProxy = new Promise<T>((resolve, reject) => {
lazyProxyResolve = resolve;
lazyProxyReject = reject;
});
// Send initialize message
this._onModuleLoaded = this._protocol.sendMessage(INITIALIZE, [
this._worker.getId(),
moduleId,
loaderConfiguration
]);
this._onModuleLoaded.then((availableMethods: string[]) => {
let proxy = <T>{};
for (let i = 0; i < availableMethods.length; i++) {
(proxy as any)[availableMethods[i]] = createProxyMethod(availableMethods[i], proxyMethodRequest);
}
lazyProxyResolve(proxy);
}, (e) => {
lazyProxyReject(e);
this._onError('Worker failed to load ' + moduleId, e);
this._lazyProxy = new Promise<T>((resolve, reject) => {
lazyProxyReject = reject;
this._onModuleLoaded.then((availableMethods: string[]) => {
let proxy = <T>{};
for (let i = 0; i < availableMethods.length; i++) {
(proxy as any)[availableMethods[i]] = createProxyMethod(availableMethods[i], proxyMethodRequest);
}
resolve(proxy);
}, (e) => {
reject(e);
this._onError('Worker failed to load ' + moduleId, e);
});
});
// Create proxy to loaded code
@@ -290,10 +285,10 @@ export interface IRequestHandler {
*/
export class SimpleWorkerServer {
private _requestHandler: IRequestHandler;
private _requestHandler: IRequestHandler | null;
private _protocol: SimpleWorkerProtocol;
constructor(postSerializedMessage: (msg: string) => void, requestHandler: IRequestHandler) {
constructor(postSerializedMessage: (msg: string) => void, requestHandler: IRequestHandler | null) {
this._requestHandler = requestHandler;
this._protocol = new SimpleWorkerProtocol({
sendMessage: (msg: string): void => {
@@ -353,29 +348,27 @@ export class SimpleWorkerServer {
(<any>self).require.config(loaderConfig);
}
let resolve: (value?: string[]) => void;
let reject: (error?: any) => void;
let r = new Promise<string[]>((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return new Promise<string[]>((resolve, reject) => {
// Use the global require to be sure to get the global config
(<any>self).require([moduleId], (...result: any[]) => {
let handlerModule = result[0];
this._requestHandler = handlerModule.create();
// Use the global require to be sure to get the global config
(<any>self).require([moduleId], (...result: any[]) => {
let handlerModule = result[0];
this._requestHandler = handlerModule.create();
let methods: string[] = [];
for (let prop in this._requestHandler) {
if (typeof this._requestHandler[prop] === 'function') {
methods.push(prop);
if (!this._requestHandler) {
reject(new Error(`No RequestHandler!`));
return;
}
}
resolve(methods);
}, reject);
let methods: string[] = [];
for (let prop in this._requestHandler) {
if (typeof this._requestHandler[prop] === 'function') {
methods.push(prop);
}
}
return r;
resolve(methods);
}, reject);
});
}
}
+2 -2
View File
@@ -16,7 +16,7 @@ import { CharCode } from 'vs/base/common/charCode';
*/
export class LineDecoder {
private stringDecoder: sd.NodeStringDecoder;
private remaining: string;
private remaining: string | null;
constructor(encoding: string = 'utf8') {
this.stringDecoder = new sd.StringDecoder(encoding);
@@ -56,7 +56,7 @@ export class LineDecoder {
return result;
}
public end(): string {
public end(): string | null {
return this.remaining;
}
}
+2 -2
View File
@@ -252,7 +252,7 @@ function rmRecursive(path: string, callback: (error: Error) => void): void {
} else if (children.length === 0) {
fs.rmdir(path, callback);
} else {
let firstError: Error = null;
let firstError: Error | null = null;
let childrenLeft = children.length;
children.forEach(child => {
rmRecursive(paths.join(path, child), (err: Error) => {
@@ -643,7 +643,7 @@ export function watch(path: string, onChange: (type: string, path?: string) => v
const watcher = fs.watch(path);
watcher.on('change', (type, raw) => {
let file: string = null;
let file: string | null = null;
if (raw) { // https://github.com/Microsoft/vscode/issues/38191
file = raw.toString();
if (platform.isMacintosh) {
+1 -1
View File
@@ -45,7 +45,7 @@ export const virtualMachineHint: { value(): number } = new class {
this._virtualMachineOUIs.set('00:16:3E', true);
this._virtualMachineOUIs.set('08:00:27', true);
}
return this._virtualMachineOUIs.findSubstr(mac);
return !!this._virtualMachineOUIs.findSubstr(mac);
}
value(): number {
+1 -1
View File
@@ -157,7 +157,7 @@ export function fileExists(path: string): Promise<boolean> {
/**
* Deletes a path from disk.
*/
let _tmpDir: string = null;
let _tmpDir: string | null = null;
function getTmpDir(): string {
if (!_tmpDir) {
_tmpDir = os.tmpdir();
@@ -328,7 +328,7 @@ class Renderer implements IRenderer<QuickOpenEntry> {
private actionProvider: IActionProvider;
private actionRunner: IActionRunner;
constructor(actionProvider: IActionProvider = new NoActionProvider(), actionRunner: IActionRunner = null) {
constructor(actionProvider: IActionProvider = new NoActionProvider(), actionRunner: IActionRunner | null = null) {
this.actionProvider = actionProvider;
this.actionRunner = actionRunner;
}
+2 -2
View File
@@ -179,7 +179,7 @@ export class Tree implements _.ITree {
return this.model.collapse(element, recursive);
}
public collapseAll(elements: any[] = null, recursive: boolean = false): WinJS.Promise {
public collapseAll(elements: any[] | null = null, recursive: boolean = false): WinJS.Promise {
return this.model.collapseAll(elements, recursive);
}
@@ -199,7 +199,7 @@ export class Tree implements _.ITree {
return this.model.getExpandedElements();
}
public reveal(element: any, relativeTop: number = null): WinJS.Promise {
public reveal(element: any, relativeTop: number | null = null): WinJS.Promise {
return this.model.reveal(element, relativeTop);
}
+7 -7
View File
@@ -346,7 +346,7 @@ export class Item {
this.expanded = value;
}
public reveal(relativeTop: number = null): void {
public reveal(relativeTop: number | null = null): void {
var eventData: IItemRevealEvent = { item: this, relativeTop: relativeTop };
this._onDidReveal.fire(eventData);
}
@@ -838,8 +838,8 @@ function getRange(one: Item, other: Item): Item[] {
var item = oneHierarchy[length - 1];
var nav = item.getNavigator();
var oneIndex: number = null;
var otherIndex: number = null;
var oneIndex: number | null = null;
var otherIndex: number | null = null;
var index = 0;
var result: Item[] = [];
@@ -1030,7 +1030,7 @@ export class TreeModel {
return item.collapse(recursive);
}
public collapseAll(elements: any[] = null, recursive: boolean = false): WinJS.Promise {
public collapseAll(elements: any[] | null = null, recursive: boolean = false): WinJS.Promise {
if (!elements) {
elements = [this.input];
recursive = true;
@@ -1078,7 +1078,7 @@ export class TreeModel {
return result;
}
public reveal(element: any, relativeTop: number = null): WinJS.Promise {
public reveal(element: any, relativeTop: number | null = null): WinJS.Promise {
return this.resolveUnknownParentChain(element).then((chain: any[]) => {
var result = WinJS.TPromise.as(null);
@@ -1221,8 +1221,8 @@ export class TreeModel {
public selectPrevious(count: number = 1, clearSelection: boolean = true, eventPayload?: any): void {
var selection = this.getSelection(),
item: Item = null,
previousItem: Item = null;
item: Item | null = null,
previousItem: Item | null = null;
if (selection.length === 0) {
let nav = this.getNavigator(this.input);
+1 -1
View File
@@ -1657,7 +1657,7 @@ export class TreeView extends HeightMap {
// DOM changes
private insertItemInDOM(item: ViewItem): void {
var elementAfter: HTMLElement = null;
var elementAfter: HTMLElement | null = null;
var itemAfter = <ViewItem>this.itemAfter(item);
if (itemAfter && itemAfter.element) {
@@ -28,7 +28,7 @@ export class HeightMap {
return !last ? 0 : last.top + last.height;
}
public onInsertItems(iterator: INextIterator<Item>, afterItemId: string = null): number {
public onInsertItems(iterator: INextIterator<Item>, afterItemId: string | null = null): number {
var item: Item;
var viewItem: IViewItem;
var i: number, j: number;
@@ -90,7 +90,7 @@ export class HeightMap {
public onRemoveItems(iterator: INextIterator<string>): void {
var itemId: string;
var viewItem: IViewItem;
var startIndex: number = null;
var startIndex: number | null = null;
var i: number;
var sizeDiff = 0;
@@ -140,7 +140,7 @@ export class HeightMap {
var item: Item;
var viewItem: IViewItem;
var newHeight: number;
var i: number, j: number = null;
var i: number, j: number | null = null;
var cummDiff = 0;
while (item = iterator.next()) {
+4 -2
View File
@@ -31,7 +31,7 @@ function getWorker(workerId: string, label: string): Worker {
class WebWorker implements IWorker {
private id: number;
private worker: Worker;
private worker: Worker | null;
constructor(moduleId: string, id: number, label: string, onMessageCallback: IWorkerCallback, onErrorCallback: (err: any) => void) {
this.id = id;
@@ -56,7 +56,9 @@ class WebWorker implements IWorker {
}
public dispose(): void {
this.worker.terminate();
if (this.worker) {
this.worker.terminate();
}
this.worker = null;
}
}
+1 -1
View File
@@ -27,7 +27,7 @@
self.onmessage = (e) => messageHandler.onmessage(e.data);
while (beforeReadyMessages.length > 0) {
self.onmessage(beforeReadyMessages.shift());
self.onmessage(beforeReadyMessages.shift()!);
}
}, 0);
});
@@ -99,7 +99,7 @@ function main(server: Server, initData: ISharedProcessInitData, configuration: I
telemetryLogService.info('The below are logs for every telemetry event sent from VS Code once the log level is set to trace.');
telemetryLogService.info('===========================================================');
let appInsightsAppender: ITelemetryAppender = NullAppender;
let appInsightsAppender: ITelemetryAppender | null = NullAppender;
if (product.aiConfig && product.aiConfig.asimovKey && isBuilt) {
appInsightsAppender = new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey, telemetryLogService);
disposables.push(appInsightsAppender); // Ensure the AI appender is disposed so that it flushes remaining data
+1 -1
View File
@@ -556,7 +556,7 @@ export class CodeApplication {
private afterWindowOpen(accessor: ServicesAccessor): void {
const windowsMainService = accessor.get(IWindowsMainService);
let windowsMutex: Mutex = null;
let windowsMutex: Mutex | null = null;
if (platform.isWindows) {
// Setup Windows mutex
+1 -1
View File
@@ -19,7 +19,7 @@ export function getBackgroundColor(stateService: IStateService): string {
return DEFAULT_BG_HC_BLACK;
}
let background = stateService.getItem<string>(THEME_BG_STORAGE_KEY, null);
let background = stateService.getItem<string | null>(THEME_BG_STORAGE_KEY, null);
if (!background) {
let baseTheme: string;
if (isWindows && systemPreferences.isInvertedColorScheme()) {
+22 -1
View File
@@ -57,6 +57,8 @@ export class CodeWindow implements ICodeWindow {
private static readonly MIN_WIDTH = 200;
private static readonly MIN_HEIGHT = 120;
private static readonly MAX_URL_LENGTH = 2 * 1024 * 1024; // https://cs.chromium.org/chromium/src/url/url_constants.cc?l=32
private hiddenTitleBarStyle: boolean;
private showTimeoutHandle: any;
private _id: number;
@@ -605,11 +607,30 @@ export class CodeWindow implements ICodeWindow {
const environment = parseArgs(process.argv);
const config = objects.assign(environment, windowConfiguration);
for (let key in config) {
if (config[key] === void 0 || config[key] === null || config[key] === '') {
if (config[key] === void 0 || config[key] === null || config[key] === '' || config[key] === false) {
delete config[key]; // only send over properties that have a true value
}
}
// In the unlikely event of the URL becoming larger than 2MB, remove parts of
// it that are not under our control. Mainly, the user environment can be very
// large depending on user configuration, so we can only remove it in that case.
let configUrl = this.doGetUrl(config);
if (configUrl.length > CodeWindow.MAX_URL_LENGTH) {
delete config.userEnv;
this.logService.warn('Application URL exceeds maximum of 2MB and was shortened.');
configUrl = this.doGetUrl(config);
if (configUrl.length > CodeWindow.MAX_URL_LENGTH) {
this.logService.error('Application URL exceeds maximum of 2MB and cannot be loaded.');
}
}
return configUrl;
}
private doGetUrl(config: object): string {
return `${require.toUrl('vs/code/electron-browser/workbench/workbench.html')}?config=${encodeURIComponent(JSON.stringify(config))}`;
}
+2 -2
View File
@@ -99,8 +99,8 @@ export function parseLineAndColumnAware(rawPath: string): IPathWithLineAndColumn
const segments = rawPath.split(':'); // C:\file.txt:<line>:<column>
let path: string;
let line: number = null;
let column: number = null;
let line: number | null = null;
let column: number | null = null;
segments.forEach(segment => {
const segmentAsNumber = Number(segment);
+2 -2
View File
@@ -21,7 +21,7 @@ function getUnixShellEnvironment(): Promise<typeof process.env> {
});
const command = `'${process.execPath}' -p '"${mark}" + JSON.stringify(process.env) + "${mark}"'`;
const child = cp.spawn(process.env.SHELL, ['-ilc', command], {
const child = cp.spawn(process.env.SHELL!, ['-ilc', command], {
detached: true,
stdio: ['ignore', 'pipe', process.stderr],
env
@@ -66,7 +66,7 @@ function getUnixShellEnvironment(): Promise<typeof process.env> {
});
// swallow errors
return promise.then(null, () => ({}));
return promise.then(undefined, () => ({}));
}
@@ -33,8 +33,8 @@ class DomCharWidthReader {
private readonly _bareFontInfo: BareFontInfo;
private readonly _requests: CharWidthRequest[];
private _container: HTMLElement;
private _testElements: HTMLSpanElement[];
private _container: HTMLElement | null;
private _testElements: HTMLSpanElement[] | null;
constructor(bareFontInfo: BareFontInfo, requests: CharWidthRequest[]) {
this._bareFontInfo = bareFontInfo;
@@ -49,13 +49,13 @@ class DomCharWidthReader {
this._createDomElements();
// Add the container to the DOM
document.body.appendChild(this._container);
document.body.appendChild(this._container!);
// Read character widths
this._readFromDomElements();
// Remove the container from the DOM
document.body.removeChild(this._container);
document.body.removeChild(this._container!);
this._container = null;
this._testElements = null;
@@ -107,11 +107,11 @@ class DomCharWidthReader {
parent = italicDomNode;
}
parent.appendChild(document.createElement('br'));
parent!.appendChild(document.createElement('br'));
let testElement = document.createElement('span');
DomCharWidthReader._render(testElement, request);
parent.appendChild(testElement);
parent!.appendChild(testElement);
testElements[i] = testElement;
}
@@ -141,7 +141,7 @@ class DomCharWidthReader {
private _readFromDomElements(): void {
for (let i = 0, len = this._requests.length; i < len; i++) {
const request = this._requests[i];
const testElement = this._testElements[i];
const testElement = this._testElements![i];
request.fulfill(testElement.offsetWidth / 256);
}
@@ -62,7 +62,7 @@ export function restoreFontInfo(nextStorage2Service: INextStorage2Service): void
if (typeof strStoredFontInfo !== 'string') {
return;
}
let storedFontInfo: ISerializedFontInfo[] = null;
let storedFontInfo: ISerializedFontInfo[] | null = null;
try {
storedFontInfo = JSON.parse(strStoredFontInfo);
} catch (err) {
@@ -321,7 +321,7 @@ export class Configuration extends CommonEditorConfiguration {
private readonly _elementSizeObserver: ElementSizeObserver;
constructor(options: IEditorOptions, referenceDomElement: HTMLElement = null) {
constructor(options: IEditorOptions, referenceDomElement: HTMLElement | null = null) {
super(options);
this._elementSizeObserver = this._register(new ElementSizeObserver(referenceDomElement, () => this._onReferenceDomElementSizeChanged()));
@@ -7,7 +7,7 @@ import * as nls from 'vs/nls';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { CursorState, ICursors, RevealTarget, IColumnSelectData, CursorContext, EditOperationType } from 'vs/editor/common/controller/cursorCommon';
import { CursorState, ICursors, RevealTarget, IColumnSelectData, CursorContext, EditOperationType, PartialCursorState } from 'vs/editor/common/controller/cursorCommon';
import { CursorChangeReason } from 'vs/editor/common/controller/cursorEvents';
import { CursorMoveCommands, CursorMove as CursorMove_ } from 'vs/editor/common/controller/cursorMoveCommands';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
@@ -703,14 +703,14 @@ export namespace CoreNavigationCommands {
public runCoreEditorCommand(cursors: ICursors, args: any): void {
const context = cursors.context;
let newState: CursorState;
let newState: PartialCursorState;
if (args.wholeLine) {
newState = CursorMoveCommands.line(context, cursors.getPrimaryCursor(), false, args.position, args.viewPosition);
} else {
newState = CursorMoveCommands.moveTo(context, cursors.getPrimaryCursor(), false, args.position, args.viewPosition);
}
const states = cursors.getAll();
const states: PartialCursorState[] = cursors.getAll();
// Check if we should remove a cursor (sort of like a toggle)
if (states.length > 1) {
@@ -766,8 +766,9 @@ export namespace CoreNavigationCommands {
const lastAddedCursorIndex = cursors.getLastAddedCursorIndex();
let newStates = cursors.getAll().slice(0);
newStates[lastAddedCursorIndex] = CursorMoveCommands.moveTo(context, newStates[lastAddedCursorIndex], true, args.position, args.viewPosition);
const states = cursors.getAll();
let newStates: PartialCursorState[] = states.slice(0);
newStates[lastAddedCursorIndex] = CursorMoveCommands.moveTo(context, states[lastAddedCursorIndex], true, args.position, args.viewPosition);
cursors.context.model.pushStackElement();
cursors.setStates(
@@ -846,8 +847,8 @@ export namespace CoreNavigationCommands {
cursors.reveal(true, RevealTarget.Primary, editorCommon.ScrollType.Smooth);
}
private _exec(context: CursorContext, cursors: CursorState[]): CursorState[] {
let result: CursorState[] = [];
private _exec(context: CursorContext, cursors: CursorState[]): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
const lineNumber = cursor.modelState.position.lineNumber;
@@ -925,8 +926,8 @@ export namespace CoreNavigationCommands {
cursors.reveal(true, RevealTarget.Primary, editorCommon.ScrollType.Smooth);
}
private _exec(context: CursorContext, cursors: CursorState[]): CursorState[] {
let result: CursorState[] = [];
private _exec(context: CursorContext, cursors: CursorState[]): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
const lineNumber = cursor.modelState.position.lineNumber;
@@ -1245,8 +1246,9 @@ export namespace CoreNavigationCommands {
const lastAddedCursorIndex = cursors.getLastAddedCursorIndex();
let newStates = cursors.getAll().slice(0);
let lastAddedState = newStates[lastAddedCursorIndex];
const states = cursors.getAll();
let newStates: PartialCursorState[] = states.slice(0);
let lastAddedState = states[lastAddedCursorIndex];
newStates[lastAddedCursorIndex] = CursorMoveCommands.word(context, lastAddedState, lastAddedState.modelState.hasSelection(), args.position);
context.model.pushStackElement();
@@ -1302,8 +1304,9 @@ export namespace CoreNavigationCommands {
public runCoreEditorCommand(cursors: ICursors, args: any): void {
const lastAddedCursorIndex = cursors.getLastAddedCursorIndex();
let newStates = cursors.getAll().slice(0);
newStates[lastAddedCursorIndex] = CursorMoveCommands.line(cursors.context, newStates[lastAddedCursorIndex], this._inSelectionMode, args.position, args.viewPosition);
const states = cursors.getAll();
let newStates: PartialCursorState[] = states.slice(0);
newStates[lastAddedCursorIndex] = CursorMoveCommands.line(cursors.context, states[lastAddedCursorIndex], this._inSelectionMode, args.position, args.viewPosition);
cursors.context.model.pushStackElement();
cursors.setStates(
@@ -97,7 +97,7 @@ export class MouseTarget implements IMouseTarget {
public readonly range: EditorRange;
public readonly detail: any;
constructor(element: Element, type: MouseTargetType, mouseColumn: number = 0, position: Position = null, range: EditorRange = null, detail: any = null) {
constructor(element: Element, type: MouseTargetType, mouseColumn: number = 0, position: Position | null = null, range: EditorRange | null = null, detail: any = null) {
this.element = element;
this.type = type;
this.mouseColumn = mouseColumn;
@@ -258,9 +258,9 @@ export class HitTestContext {
if (viewZoneWhitespace) {
let viewZoneMiddle = viewZoneWhitespace.verticalOffset + viewZoneWhitespace.height / 2,
lineCount = context.model.getLineCount(),
positionBefore: Position = null,
positionBefore: Position | null = null,
position: Position,
positionAfter: Position = null;
positionAfter: Position | null = null;
if (viewZoneWhitespace.afterLineNumber !== lineCount) {
// There are more lines after this view zone
@@ -406,7 +406,7 @@ class HitTestRequest extends BareHitTestRequest {
return `pos(${this.pos.x},${this.pos.y}), editorPos(${this.editorPos.x},${this.editorPos.y}), mouseVerticalOffset: ${this.mouseVerticalOffset}, mouseContentHorizontalOffset: ${this.mouseContentHorizontalOffset}\n\ttarget: ${this.target ? (<HTMLElement>this.target).outerHTML : null}`;
}
public fulfill(type: MouseTargetType, position: Position = null, range: EditorRange = null, detail: any = null): MouseTarget {
public fulfill(type: MouseTargetType, position: Position | null = null, range: EditorRange | null = null, detail: any = null): MouseTarget {
return new MouseTarget(this.target, type, this.mouseColumn, position, range, detail);
}
@@ -484,7 +484,7 @@ export class MouseTargetFactory {
return this._createMouseTarget(ctx, request.withTarget(hitTestResult.hitTarget), true);
}
let result: MouseTarget = null;
let result: MouseTarget | null = null;
result = result || MouseTargetFactory._hitTestContentWidget(ctx, request);
result = result || MouseTargetFactory._hitTestOverlayWidget(ctx, request);
@@ -895,8 +895,8 @@ export class MouseTargetFactory {
* Most probably IE
*/
private static _doHitTestWithMoveToPoint(ctx: HitTestContext, coords: ClientCoordinates): IHitTestResult {
let resultPosition: Position = null;
let resultHitTarget: Element = null;
let resultPosition: Position | null = null;
let resultHitTarget: Element | null = null;
let textRange: IETextRange = (<any>document.body).createTextRange();
try {
@@ -172,7 +172,7 @@ export class TextAreaHandler extends ViewPart {
const multicursorText = (Array.isArray(rawWhatToCopy) ? rawWhatToCopy : null);
const whatToCopy = (Array.isArray(rawWhatToCopy) ? rawWhatToCopy.join(newLineCharacter) : rawWhatToCopy);
let metadata: LocalClipboardMetadata = null;
let metadata: LocalClipboardMetadata | null = null;
if (isFromEmptySelection || multicursorText) {
// Only store the non-default metadata
@@ -250,7 +250,7 @@ export class TextAreaHandler extends ViewPart {
const metadata = LocalClipboardMetadataManager.INSTANCE.get(e.text);
let pasteOnNewLine = false;
let multicursorText: string[] = null;
let multicursorText: string[] | null = null;
if (metadata) {
pasteOnNewLine = (this._emptySelectionClipboard && metadata.isFromEmptySelection);
multicursorText = metadata.multicursorText;
@@ -442,7 +442,7 @@ export class TextAreaHandler extends ViewPart {
// --- end view API
private _primaryCursorVisibleRange: HorizontalRange = null;
private _primaryCursorVisibleRange: HorizontalRange | null = null;
public prepareRender(ctx: RenderingContext): void {
if (this._accessibilitySupport === platform.AccessibilitySupport.Enabled) {
@@ -479,7 +479,7 @@ export class TextAreaInput extends Disposable {
return;
}
let copyHTML: string = null;
let copyHTML: string | null = null;
if (browser.hasClipboardSupport() && (copyPlainText.length < 65536 || CopyOptions.forceCopyWithSyntaxHighlighting)) {
copyHTML = this._host.getHTMLToCopy();
}
@@ -35,10 +35,10 @@ export class TextAreaState {
public readonly value: string;
public readonly selectionStart: number;
public readonly selectionEnd: number;
public readonly selectionStartPosition: Position;
public readonly selectionEndPosition: Position;
public readonly selectionStartPosition: Position | null;
public readonly selectionEndPosition: Position | null;
constructor(value: string, selectionStart: number, selectionEnd: number, selectionStartPosition: Position, selectionEndPosition: Position) {
constructor(value: string, selectionStart: number, selectionEnd: number, selectionStartPosition: Position | null, selectionEndPosition: Position | null) {
this.value = value;
this.selectionStart = selectionStart;
this.selectionEnd = selectionEnd;
@@ -66,7 +66,7 @@ export class TextAreaState {
}
}
public deduceEditorPosition(offset: number): [Position, number, number] {
public deduceEditorPosition(offset: number): [Position | null, number, number] {
if (offset <= this.selectionStart) {
const str = this.value.substring(offset, this.selectionStart);
return this._finishDeduceEditorPosition(this.selectionStartPosition, str, -1);
@@ -83,7 +83,7 @@ export class TextAreaState {
return this._finishDeduceEditorPosition(this.selectionEndPosition, str2, -1);
}
private _finishDeduceEditorPosition(anchor: Position, deltaText: string, signum: number): [Position, number, number] {
private _finishDeduceEditorPosition(anchor: Position | null, deltaText: string, signum: number): [Position | null, number, number] {
let lineFeedCnt = 0;
let lastLineFeedIndex = -1;
while ((lastLineFeedIndex = deltaText.indexOf('\n', lastLineFeedIndex + 1)) !== -1) {
@@ -153,7 +153,7 @@ export class TextAreaState {
// the only hints we can use is that the selection is immediately after the inserted emoji
// and that none of the old text has been deleted
let potentialEmojiInput: string = null;
let potentialEmojiInput: string | null = null;
if (currentSelectionStart === currentValue.length) {
// emoji potentially inserted "somewhere" after the previous selection => it should appear at the end of `currentValue`
@@ -247,21 +247,22 @@ export class PagedScreenReaderStrategy {
let selectionEndPage = PagedScreenReaderStrategy._getPageOfLine(selection.endLineNumber);
let selectionEndPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionEndPage);
let pretextRange = selectionStartPageRange.intersectRanges(new Range(1, 1, selection.startLineNumber, selection.startColumn));
let pretextRange = selectionStartPageRange.intersectRanges(new Range(1, 1, selection.startLineNumber, selection.startColumn))!;
let pretext = model.getValueInRange(pretextRange, EndOfLinePreference.LF);
let lastLine = model.getLineCount();
let lastLineMaxColumn = model.getLineMaxColumn(lastLine);
let posttextRange = selectionEndPageRange.intersectRanges(new Range(selection.endLineNumber, selection.endColumn, lastLine, lastLineMaxColumn));
let posttextRange = selectionEndPageRange.intersectRanges(new Range(selection.endLineNumber, selection.endColumn, lastLine, lastLineMaxColumn))!;
let posttext = model.getValueInRange(posttextRange, EndOfLinePreference.LF);
let text: string = null;
let text: string;
if (selectionStartPage === selectionEndPage || selectionStartPage + 1 === selectionEndPage) {
// take full selection
text = model.getValueInRange(selection, EndOfLinePreference.LF);
} else {
let selectionRange1 = selectionStartPageRange.intersectRanges(selection);
let selectionRange2 = selectionEndPageRange.intersectRanges(selection);
let selectionRange1 = selectionStartPageRange.intersectRanges(selection)!;
let selectionRange2 = selectionEndPageRange.intersectRanges(selection)!;
text = (
model.getValueInRange(selectionRange1, EndOfLinePreference.LF)
+ String.fromCharCode(8230)
+1 -1
View File
@@ -74,7 +74,7 @@ export class EditorState {
export class StableEditorScrollState {
public static capture(editor: ICodeEditor): StableEditorScrollState {
let visiblePosition: Position = null;
let visiblePosition: Position | null = null;
let visiblePositionScrollDelta = 0;
if (editor.getScrollTop() !== 0) {
const visibleRanges = editor.getVisibleRanges();
@@ -9,7 +9,6 @@ import { IModelDecorationOptions, ITextModel } from 'vs/editor/common/model';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser';
import { IResourceInput } from 'vs/platform/editor/common/editor';
import { TPromise } from 'vs/base/common/winjs.base';
import { Disposable } from 'vs/base/common/lifecycle';
export abstract class AbstractCodeEditorService extends Disposable implements ICodeEditorService {
@@ -72,7 +71,7 @@ export abstract class AbstractCodeEditorService extends Disposable implements IC
}
getFocusedCodeEditor(): ICodeEditor {
let editorWithWidgetFocus: ICodeEditor = null;
let editorWithWidgetFocus: ICodeEditor | null = null;
let editors = this.listCodeEditors();
for (let i = 0; i < editors.length; i++) {
@@ -127,7 +126,7 @@ export abstract class AbstractCodeEditorService extends Disposable implements IC
}
abstract getActiveCodeEditor(): ICodeEditor;
abstract openCodeEditor(input: IResourceInput, source: ICodeEditor, sideBySide?: boolean): TPromise<ICodeEditor>;
abstract openCodeEditor(input: IResourceInput, source: ICodeEditor, sideBySide?: boolean): Thenable<ICodeEditor>;
}
export class ModelTransientSettingWatcher {
@@ -12,7 +12,6 @@ import { AbstractCodeEditorService } from 'vs/editor/browser/services/abstractCo
import { IDisposable, dispose as disposeAll } from 'vs/base/common/lifecycle';
import { IThemeService, ITheme, ThemeColor } from 'vs/platform/theme/common/themeService';
import { IResourceInput } from 'vs/platform/editor/common/editor';
import { TPromise } from 'vs/base/common/winjs.base';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
export abstract class CodeEditorServiceImpl extends AbstractCodeEditorService {
@@ -68,7 +67,7 @@ export abstract class CodeEditorServiceImpl extends AbstractCodeEditorService {
}
abstract getActiveCodeEditor(): ICodeEditor;
abstract openCodeEditor(input: IResourceInput, source: ICodeEditor, sideBySide?: boolean): TPromise<ICodeEditor>;
abstract openCodeEditor(input: IResourceInput, source: ICodeEditor, sideBySide?: boolean): Thenable<ICodeEditor>;
}
interface IModelDecorationOptionsProvider extends IDisposable {
@@ -22,7 +22,7 @@ export class OpenerService implements IOpenerService {
constructor(
@ICodeEditorService private readonly _editorService: ICodeEditorService,
@ICommandService private readonly _commandService: ICommandService,
@optional(ITelemetryService) private _telemetryService: ITelemetryService = NullTelemetryService
@optional(ITelemetryService) private _telemetryService: ITelemetryService | null = NullTelemetryService
) {
//
}
@@ -19,18 +19,18 @@ export interface EventCallback<T> {
export class ViewOutgoingEvents extends Disposable {
public onDidScroll: EventCallback<IScrollEvent> = null;
public onDidGainFocus: EventCallback<void> = null;
public onDidLoseFocus: EventCallback<void> = null;
public onKeyDown: EventCallback<IKeyboardEvent> = null;
public onKeyUp: EventCallback<IKeyboardEvent> = null;
public onContextMenu: EventCallback<IEditorMouseEvent> = null;
public onMouseMove: EventCallback<IEditorMouseEvent> = null;
public onMouseLeave: EventCallback<IEditorMouseEvent> = null;
public onMouseUp: EventCallback<IEditorMouseEvent> = null;
public onMouseDown: EventCallback<IEditorMouseEvent> = null;
public onMouseDrag: EventCallback<IEditorMouseEvent> = null;
public onMouseDrop: EventCallback<IEditorMouseEvent> = null;
public onDidScroll: EventCallback<IScrollEvent> | null = null;
public onDidGainFocus: EventCallback<void> | null = null;
public onDidLoseFocus: EventCallback<void> | null = null;
public onKeyDown: EventCallback<IKeyboardEvent> | null = null;
public onKeyUp: EventCallback<IKeyboardEvent> | null = null;
public onContextMenu: EventCallback<IEditorMouseEvent> | null = null;
public onMouseMove: EventCallback<IEditorMouseEvent> | null = null;
public onMouseLeave: EventCallback<IEditorMouseEvent> | null = null;
public onMouseUp: EventCallback<IEditorMouseEvent> | null = null;
public onMouseDown: EventCallback<IEditorMouseEvent> | null = null;
public onMouseDrag: EventCallback<IEditorMouseEvent> | null = null;
public onMouseDrop: EventCallback<IEditorMouseEvent> | null = null;
private _viewModel: IViewModel;
@@ -443,7 +443,7 @@ class Widget {
return null;
}
let placement: IBoxLayoutResult = null;
let placement: IBoxLayoutResult | null = null;
let fetchPlacement = (): void => {
if (placement) {
return;
@@ -149,9 +149,9 @@ export class DecorationsOverlay extends DynamicViewOverlay {
const lineHeight = String(this._lineHeight);
const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
let prevClassName: string = null;
let prevClassName: string | null = null;
let prevShowIfCollapsed: boolean = false;
let prevRange: Range = null;
let prevRange: Range | null = null;
for (let i = 0, lenI = decorations.length; i < lenI; i++) {
const d = decorations[i];
@@ -47,7 +47,7 @@ export abstract class DedupOverlay extends DynamicViewOverlay {
return (a.className < b.className ? -1 : 1);
});
let prevClassName: string = null;
let prevClassName: string | null = null;
let prevEndLineIndex = 0;
for (let i = 0, len = decorations.length; i < len; i++) {
let d = decorations[i];
@@ -225,7 +225,7 @@ export class ViewLine implements IVisibleLine {
sb.appendASCIIString('</div>');
let renderedViewLine: IRenderedViewLine = null;
let renderedViewLine: IRenderedViewLine | null = null;
if (canUseFastRenderedViewLine && lineData.isBasicASCII && options.useMonospaceOptimizations && output.containsForeignElements === ForeignElementType.None) {
if (lineData.content.length < 300 && renderLineInput.lineTokens.getCount() < 100) {
// Browser rounding errors have been observed in Chrome and IE, so using the fast
@@ -158,8 +158,8 @@ export class SelectionsOverlay extends DynamicViewOverlay {
private _enrichVisibleRangesWithStyle(viewport: Range, linesVisibleRanges: LineVisibleRangesWithStyle[], previousFrame: LineVisibleRangesWithStyle[]): void {
const epsilon = this._typicalHalfwidthCharacterWidth / 4;
let previousFrameTop: HorizontalRangeWithStyle = null;
let previousFrameBottom: HorizontalRangeWithStyle = null;
let previousFrameTop: HorizontalRangeWithStyle | null = null;
let previousFrameBottom: HorizontalRangeWithStyle | null = null;
if (previousFrame && previousFrame.length > 0 && linesVisibleRanges.length > 0) {
@@ -10,7 +10,6 @@ import * as dom from 'vs/base/browser/dom';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Event, Emitter } from 'vs/base/common/event';
import { Disposable, IDisposable, dispose } from 'vs/base/common/lifecycle';
import { TPromise } from 'vs/base/common/winjs.base';
import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
@@ -377,7 +376,7 @@ export class CodeEditorWidget extends Disposable implements editorBrowser.ICodeE
return this.model;
}
public setModel(model: ITextModel = null): void {
public setModel(model: ITextModel | null = null): void {
if (this.model === model) {
// Current model is the new model
return;
@@ -911,7 +910,7 @@ export class CodeEditorWidget extends Disposable implements editorBrowser.ICodeE
const action = this.getAction(handlerId);
if (action) {
TPromise.as(action.run()).then(null, onUnexpectedError);
Promise.resolve(action.run()).then(null, onUnexpectedError);
return;
}
@@ -931,7 +930,7 @@ export class CodeEditorWidget extends Disposable implements editorBrowser.ICodeE
if (command) {
payload = payload || {};
payload.source = source;
TPromise.as(command.runEditorCommand(null, this, payload)).then(null, onUnexpectedError);
Promise.resolve(command.runEditorCommand(null, this, payload)).then(null, onUnexpectedError);
return true;
}
@@ -1463,7 +1462,7 @@ export class CodeEditorWidget extends Disposable implements editorBrowser.ICodeE
}
private _detachModel(): ITextModel {
let removeDomNode: HTMLElement = null;
let removeDomNode: HTMLElement | null = null;
if (this._view) {
this._view.dispose();
@@ -847,8 +847,8 @@ export class DiffEditorWidget extends Disposable implements editorBrowser.IDiffE
this._beginUpdateDecorationsTimeout = window.setTimeout(() => this._beginUpdateDecorations(), DiffEditorWidget.UPDATE_DIFF_DECORATIONS_DELAY);
}
private _lastOriginalWarning: URI = null;
private _lastModifiedWarning: URI = null;
private _lastOriginalWarning: URI | null = null;
private _lastModifiedWarning: URI | null = null;
private static _equals(a: URI, b: URI): boolean {
if (!a && !b) {
@@ -1334,7 +1334,7 @@ abstract class ViewZonesComputer {
viewZoneLineNumber = originalEndEquivalentLineNumber;
}
let marginDomNode: HTMLDivElement = null;
let marginDomNode: HTMLDivElement | null = null;
if (lineChange && lineChange.modifiedStartLineNumber <= modifiedForeignVZ.current.afterLineNumber && modifiedForeignVZ.current.afterLineNumber <= lineChange.modifiedEndLineNumber) {
marginDomNode = this._createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion();
}
+16 -16
View File
@@ -834,7 +834,7 @@ export function cursorStyleToString(cursorStyle: TextEditorCursorStyle): string
}
}
function _cursorStyleFromString(cursorStyle: string, defaultValue: TextEditorCursorStyle): TextEditorCursorStyle {
function _cursorStyleFromString(cursorStyle: string | undefined, defaultValue: TextEditorCursorStyle): TextEditorCursorStyle {
if (typeof cursorStyle !== 'string') {
return defaultValue;
}
@@ -930,7 +930,7 @@ export interface InternalEditorViewOptions {
readonly rulers: number[];
readonly ariaLabel: string;
readonly renderLineNumbers: RenderLineNumbersType;
readonly renderCustomLineNumbers: (lineNumber: number) => string;
readonly renderCustomLineNumbers: ((lineNumber: number) => string) | null;
readonly selectOnLineNumbers: boolean;
readonly glyphMargin: boolean;
readonly revealHorizontalRightPadding: number;
@@ -1597,7 +1597,7 @@ function _boolean<T>(value: any, defaultValue: T): boolean | T {
return Boolean(value);
}
function _booleanMap(value: { [key: string]: boolean }, defaultValue: { [key: string]: boolean }): { [key: string]: boolean } {
function _booleanMap(value: { [key: string]: boolean } | undefined, defaultValue: { [key: string]: boolean }): { [key: string]: boolean } {
if (!value) {
return defaultValue;
}
@@ -1619,7 +1619,7 @@ function _string(value: any, defaultValue: string): string {
return value;
}
function _stringSet<T>(value: T, defaultValue: T, allowedValues: T[]): T {
function _stringSet<T>(value: T | undefined, defaultValue: T, allowedValues: T[]): T {
if (typeof value !== 'string') {
return defaultValue;
}
@@ -1652,7 +1652,7 @@ function _float(value: any, defaultValue: number): number {
return r;
}
function _wrappingIndentFromString(wrappingIndent: string, defaultValue: WrappingIndent): WrappingIndent {
function _wrappingIndentFromString(wrappingIndent: string | undefined, defaultValue: WrappingIndent): WrappingIndent {
if (typeof wrappingIndent !== 'string') {
return defaultValue;
}
@@ -1667,7 +1667,7 @@ function _wrappingIndentFromString(wrappingIndent: string, defaultValue: Wrappin
}
}
function _cursorBlinkingStyleFromString(cursorBlinkingStyle: string, defaultValue: TextEditorCursorBlinkingStyle): TextEditorCursorBlinkingStyle {
function _cursorBlinkingStyleFromString(cursorBlinkingStyle: string | undefined, defaultValue: TextEditorCursorBlinkingStyle): TextEditorCursorBlinkingStyle {
if (typeof cursorBlinkingStyle !== 'string') {
return defaultValue;
}
@@ -1687,7 +1687,7 @@ function _cursorBlinkingStyleFromString(cursorBlinkingStyle: string, defaultValu
return TextEditorCursorBlinkingStyle.Blink;
}
function _scrollbarVisibilityFromString(visibility: string, defaultValue: ScrollbarVisibility): ScrollbarVisibility {
function _scrollbarVisibilityFromString(visibility: string | undefined, defaultValue: ScrollbarVisibility): ScrollbarVisibility {
if (typeof visibility !== 'string') {
return defaultValue;
}
@@ -1726,7 +1726,7 @@ export class EditorOptionsValidator {
const viewInfo = this._sanitizeViewInfo(opts, defaults.viewInfo);
const contribInfo = this._sanitizeContribInfo(opts, defaults.contribInfo);
let configuredMulticursorModifier: 'altKey' | 'metaKey' | 'ctrlKey';
let configuredMulticursorModifier: 'altKey' | 'metaKey' | 'ctrlKey' | undefined = undefined;
if (typeof opts.multiCursorModifier === 'string') {
if (opts.multiCursorModifier === 'ctrlCmd') {
configuredMulticursorModifier = platform.isMacintosh ? 'metaKey' : 'ctrlKey';
@@ -1783,7 +1783,7 @@ export class EditorOptionsValidator {
};
}
private static _sanitizeScrollbarOpts(opts: IEditorScrollbarOptions, defaults: InternalEditorScrollbarOptions, mouseWheelScrollSensitivity: number): InternalEditorScrollbarOptions {
private static _sanitizeScrollbarOpts(opts: IEditorScrollbarOptions | undefined, defaults: InternalEditorScrollbarOptions, mouseWheelScrollSensitivity: number): InternalEditorScrollbarOptions {
if (typeof opts !== 'object') {
return defaults;
}
@@ -1810,7 +1810,7 @@ export class EditorOptionsValidator {
};
}
private static _sanitizeMinimapOpts(opts: IEditorMinimapOptions, defaults: InternalEditorMinimapOptions): InternalEditorMinimapOptions {
private static _sanitizeMinimapOpts(opts: IEditorMinimapOptions | undefined, defaults: InternalEditorMinimapOptions): InternalEditorMinimapOptions {
if (typeof opts !== 'object') {
return defaults;
}
@@ -1823,7 +1823,7 @@ export class EditorOptionsValidator {
};
}
private static _santizeFindOpts(opts: IEditorFindOptions, defaults: InternalEditorFindOptions): InternalEditorFindOptions {
private static _santizeFindOpts(opts: IEditorFindOptions | undefined, defaults: InternalEditorFindOptions): InternalEditorFindOptions {
if (typeof opts !== 'object') {
return defaults;
}
@@ -1835,7 +1835,7 @@ export class EditorOptionsValidator {
};
}
private static _sanitizeParameterHintOpts(opts: IEditorParameterHintOptions, defaults: InternalParameterHintOptions): InternalParameterHintOptions {
private static _sanitizeParameterHintOpts(opts: IEditorParameterHintOptions | undefined, defaults: InternalParameterHintOptions): InternalParameterHintOptions {
if (typeof opts !== 'object') {
return defaults;
}
@@ -1846,7 +1846,7 @@ export class EditorOptionsValidator {
};
}
private static _santizeHoverOpts(_opts: boolean | IEditorHoverOptions, defaults: InternalEditorHoverOptions): InternalEditorHoverOptions {
private static _santizeHoverOpts(_opts: boolean | IEditorHoverOptions | undefined, defaults: InternalEditorHoverOptions): InternalEditorHoverOptions {
let opts: IEditorHoverOptions;
if (typeof _opts === 'boolean') {
opts = {
@@ -1875,7 +1875,7 @@ export class EditorOptionsValidator {
};
}
private static _sanitizeTabCompletionOpts(opts: boolean | 'on' | 'off' | 'onlySnippets', defaults: 'on' | 'off' | 'onlySnippets'): 'on' | 'off' | 'onlySnippets' {
private static _sanitizeTabCompletionOpts(opts: boolean | 'on' | 'off' | 'onlySnippets' | undefined, defaults: 'on' | 'off' | 'onlySnippets'): 'on' | 'off' | 'onlySnippets' {
if (opts === false) {
return 'off';
} else if (opts === true) {
@@ -1896,7 +1896,7 @@ export class EditorOptionsValidator {
}
let renderLineNumbers: RenderLineNumbersType = defaults.renderLineNumbers;
let renderCustomLineNumbers: (lineNumber: number) => string = defaults.renderCustomLineNumbers;
let renderCustomLineNumbers: ((lineNumber: number) => string) | null = defaults.renderCustomLineNumbers;
if (typeof opts.lineNumbers !== 'undefined') {
let lineNumbers = opts.lineNumbers;
@@ -2198,7 +2198,7 @@ export class InternalEditorOptionsFactory {
pixelRatio: env.pixelRatio
});
let bareWrappingInfo: { isWordWrapMinified: boolean; isViewportWrapping: boolean; wrappingColumn: number; } = null;
let bareWrappingInfo: { isWordWrapMinified: boolean; isViewportWrapping: boolean; wrappingColumn: number; } | null = null;
{
const wordWrap = opts.wordWrap;
const wordWrapColumn = opts.wordWrapColumn;
+8 -2
View File
@@ -23,10 +23,13 @@ const MAXIMUM_LINE_HEIGHT = 150;
const MINIMUM_LETTER_SPACING = -5;
const MAXIMUM_LETTER_SPACING = 20;
function safeParseFloat(n: number | string, defaultValue: number): number {
function safeParseFloat(n: number | string | undefined, defaultValue: number): number {
if (typeof n === 'number') {
return n;
}
if (typeof n === 'undefined') {
return defaultValue;
}
let r = parseFloat(n);
if (isNaN(r)) {
return defaultValue;
@@ -34,10 +37,13 @@ function safeParseFloat(n: number | string, defaultValue: number): number {
return r;
}
function safeParseInt(n: number | string, defaultValue: number): number {
function safeParseInt(n: number | string | undefined, defaultValue: number): number {
if (typeof n === 'number') {
return Math.round(n);
}
if (typeof n === 'undefined') {
return defaultValue;
}
let r = parseInt(n);
if (isNaN(r)) {
return defaultValue;
+3 -3
View File
@@ -11,7 +11,7 @@ import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { Selection, SelectionDirection, ISelection } from 'vs/editor/common/core/selection';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { CursorColumns, CursorConfiguration, EditOperationResult, CursorContext, CursorState, RevealTarget, IColumnSelectData, ICursors, EditOperationType } from 'vs/editor/common/controller/cursorCommon';
import { CursorColumns, CursorConfiguration, EditOperationResult, CursorContext, CursorState, RevealTarget, IColumnSelectData, ICursors, EditOperationType, PartialCursorState } from 'vs/editor/common/controller/cursorCommon';
import { DeleteOperations } from 'vs/editor/common/controller/cursorDeleteOperations';
import { TypeOperations } from 'vs/editor/common/controller/cursorTypeOperations';
import { RawContentChangedType } from 'vs/editor/common/model/textModelEvents';
@@ -191,7 +191,7 @@ export class Cursor extends viewEvents.ViewEventEmitter implements ICursors {
return this._cursors.getAll();
}
public setStates(source: string, reason: CursorChangeReason, states: CursorState[]): void {
public setStates(source: string, reason: CursorChangeReason, states: PartialCursorState[]): void {
if (states.length > Cursor.MAX_CURSOR_COUNT) {
states = states.slice(0, Cursor.MAX_CURSOR_COUNT);
this._onDidReachMaxCursorCount.fire(void 0);
@@ -764,7 +764,7 @@ class CommandExecutor {
let operations: IIdentifiedSingleEditOperation[] = [];
let operationMinor = 0;
const addEditOperation = (selection: Range, text: string) => {
const addEditOperation = (selection: Range, text: string | null) => {
if (selection.isEmpty() && text === '') {
// This command wants to add a no-op => no thank you
return;
@@ -6,7 +6,7 @@
import { OneCursor } from 'vs/editor/common/controller/oneCursor';
import { Selection, ISelection } from 'vs/editor/common/core/selection';
import { Position } from 'vs/editor/common/core/position';
import { CursorState, CursorContext } from 'vs/editor/common/controller/cursorCommon';
import { CursorState, CursorContext, PartialCursorState } from 'vs/editor/common/controller/cursorCommon';
export class CursorCollection {
@@ -108,7 +108,7 @@ export class CursorCollection {
return this.primaryCursor.asCursorState();
}
public setStates(states: CursorState[]): void {
public setStates(states: PartialCursorState[]): void {
if (states === null) {
return;
}
@@ -119,7 +119,7 @@ export class CursorCollection {
/**
* Creates or disposes secondary cursors as necessary to match the number of `secondarySelections`.
*/
private _setSecondaryStates(secondaryStates: CursorState[]): void {
private _setSecondaryStates(secondaryStates: PartialCursorState[]): void {
const secondaryCursorsLength = this.secondaryCursors.length;
const secondaryStatesLength = secondaryStates.length;
+34 -12
View File
@@ -51,7 +51,7 @@ export interface ICursors {
getColumnSelectData(): IColumnSelectData;
setColumnSelectData(columnSelectData: IColumnSelectData): void;
setStates(source: string, reason: CursorChangeReason, states: CursorState[]): void;
setStates(source: string, reason: CursorChangeReason, states: PartialCursorState[]): void;
reveal(horizontal: boolean, target: RevealTarget, scrollType: ScrollType): void;
revealRange(revealHorizontal: boolean, viewRange: Range, verticalType: VerticalRevealType, scrollType: ScrollType): void;
@@ -93,7 +93,7 @@ export class CursorConfiguration {
public readonly shouldAutoCloseBefore: { quote: (ch: string) => boolean, bracket: (ch: string) => boolean };
private readonly _languageIdentifier: LanguageIdentifier;
private _electricChars: { [key: string]: boolean; };
private _electricChars: { [key: string]: boolean; } | null;
public static shouldRecreate(e: IConfigurationChangedEvent): boolean {
return (
@@ -179,7 +179,7 @@ export class CursorConfiguration {
return TextModel.normalizeIndentation(str, this.tabSize, this.insertSpaces);
}
private static _getElectricCharacters(languageIdentifier: LanguageIdentifier): string[] {
private static _getElectricCharacters(languageIdentifier: LanguageIdentifier): string[] | null {
try {
return LanguageConfigurationRegistry.getElectricCharacters(languageIdentifier.id);
} catch (e) {
@@ -188,7 +188,7 @@ export class CursorConfiguration {
}
}
private static _getAutoClosingPairs(languageIdentifier: LanguageIdentifier): IAutoClosingPair[] {
private static _getAutoClosingPairs(languageIdentifier: LanguageIdentifier): IAutoClosingPair[] | null {
try {
return LanguageConfigurationRegistry.getAutoClosingPairs(languageIdentifier.id);
} catch (e) {
@@ -220,7 +220,7 @@ export class CursorConfiguration {
}
}
private static _getSurroundingPairs(languageIdentifier: LanguageIdentifier): IAutoClosingPair[] {
private static _getSurroundingPairs(languageIdentifier: LanguageIdentifier): IAutoClosingPair[] | null {
try {
return LanguageConfigurationRegistry.getSurroundingPairs(languageIdentifier.id);
} catch (e) {
@@ -394,18 +394,40 @@ export class CursorContext {
}
}
export class PartialModelCursorState {
readonly modelState: SingleCursorState;
readonly viewState: null;
constructor(modelState: SingleCursorState) {
this.modelState = modelState;
this.viewState = null;
}
}
export class PartialViewCursorState {
readonly modelState: null;
readonly viewState: SingleCursorState;
constructor(viewState: SingleCursorState) {
this.modelState = null;
this.viewState = viewState;
}
}
export type PartialCursorState = CursorState | PartialModelCursorState | PartialViewCursorState;
export class CursorState {
_cursorStateBrand: void;
public static fromModelState(modelState: SingleCursorState): CursorState {
return new CursorState(modelState, null);
public static fromModelState(modelState: SingleCursorState): PartialModelCursorState {
return new PartialModelCursorState(modelState);
}
public static fromViewState(viewState: SingleCursorState): CursorState {
return new CursorState(null, viewState);
public static fromViewState(viewState: SingleCursorState): PartialViewCursorState {
return new PartialViewCursorState(viewState);
}
public static fromModelSelection(modelSelection: ISelection): CursorState {
public static fromModelSelection(modelSelection: ISelection): PartialModelCursorState {
const selectionStartLineNumber = modelSelection.selectionStartLineNumber;
const selectionStartColumn = modelSelection.selectionStartColumn;
const positionLineNumber = modelSelection.positionLineNumber;
@@ -417,8 +439,8 @@ export class CursorState {
return CursorState.fromModelState(modelState);
}
public static fromModelSelections(modelSelections: ISelection[]): CursorState[] {
let states: CursorState[] = [];
public static fromModelSelections(modelSelections: ISelection[]): PartialModelCursorState[] {
let states: PartialModelCursorState[] = [];
for (let i = 0, len = modelSelections.length; i < len; i++) {
states[i] = this.fromModelSelection(modelSelections[i]);
}
@@ -3,7 +3,7 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { SingleCursorState, ICursorSimpleModel, CursorState, CursorContext } from 'vs/editor/common/controller/cursorCommon';
import { SingleCursorState, ICursorSimpleModel, CursorState, CursorContext, PartialCursorState } from 'vs/editor/common/controller/cursorCommon';
import { Position, IPosition } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { MoveOperations } from 'vs/editor/common/controller/cursorMoveOperations';
@@ -13,8 +13,8 @@ import { ICommandHandlerDescription } from 'vs/platform/commands/common/commands
export class CursorMoveCommands {
public static addCursorDown(context: CursorContext, cursors: CursorState[], useLogicalLine: boolean): CursorState[] {
let result: CursorState[] = [], resultLen = 0;
public static addCursorDown(context: CursorContext, cursors: CursorState[], useLogicalLine: boolean): PartialCursorState[] {
let result: PartialCursorState[] = [], resultLen = 0;
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
result[resultLen++] = new CursorState(cursor.modelState, cursor.viewState);
@@ -27,8 +27,8 @@ export class CursorMoveCommands {
return result;
}
public static addCursorUp(context: CursorContext, cursors: CursorState[], useLogicalLine: boolean): CursorState[] {
let result: CursorState[] = [], resultLen = 0;
public static addCursorUp(context: CursorContext, cursors: CursorState[], useLogicalLine: boolean): PartialCursorState[] {
let result: PartialCursorState[] = [], resultLen = 0;
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
result[resultLen++] = new CursorState(cursor.modelState, cursor.viewState);
@@ -41,8 +41,8 @@ export class CursorMoveCommands {
return result;
}
public static moveToBeginningOfLine(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): CursorState[] {
let result: CursorState[] = [];
public static moveToBeginningOfLine(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
result[i] = this._moveToLineStart(context, cursor, inSelectionMode);
@@ -51,7 +51,7 @@ export class CursorMoveCommands {
return result;
}
private static _moveToLineStart(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): CursorState {
private static _moveToLineStart(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): PartialCursorState {
const currentViewStateColumn = cursor.viewState.position.column;
const currentModelStateColumn = cursor.modelState.position.column;
const isFirstLineOfWrappedLine = currentViewStateColumn === currentModelStateColumn;
@@ -67,20 +67,20 @@ export class CursorMoveCommands {
}
}
private static _moveToLineStartByView(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): CursorState {
private static _moveToLineStartByView(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): PartialCursorState {
return CursorState.fromViewState(
MoveOperations.moveToBeginningOfLine(context.config, context.viewModel, cursor.viewState, inSelectionMode)
);
}
private static _moveToLineStartByModel(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): CursorState {
private static _moveToLineStartByModel(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): PartialCursorState {
return CursorState.fromModelState(
MoveOperations.moveToBeginningOfLine(context.config, context.model, cursor.modelState, inSelectionMode)
);
}
public static moveToEndOfLine(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): CursorState[] {
let result: CursorState[] = [];
public static moveToEndOfLine(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
result[i] = this._moveToLineEnd(context, cursor, inSelectionMode);
@@ -89,7 +89,7 @@ export class CursorMoveCommands {
return result;
}
private static _moveToLineEnd(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): CursorState {
private static _moveToLineEnd(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): PartialCursorState {
const viewStatePosition = cursor.viewState.position;
const viewModelMaxColumn = context.viewModel.getLineMaxColumn(viewStatePosition.lineNumber);
const isEndOfViewLine = viewStatePosition.column === viewModelMaxColumn;
@@ -105,20 +105,20 @@ export class CursorMoveCommands {
}
}
private static _moveToLineEndByView(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): CursorState {
private static _moveToLineEndByView(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): PartialCursorState {
return CursorState.fromViewState(
MoveOperations.moveToEndOfLine(context.config, context.viewModel, cursor.viewState, inSelectionMode)
);
}
private static _moveToLineEndByModel(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): CursorState {
private static _moveToLineEndByModel(context: CursorContext, cursor: CursorState, inSelectionMode: boolean): PartialCursorState {
return CursorState.fromModelState(
MoveOperations.moveToEndOfLine(context.config, context.model, cursor.modelState, inSelectionMode)
);
}
public static expandLineSelection(context: CursorContext, cursors: CursorState[]): CursorState[] {
let result: CursorState[] = [];
public static expandLineSelection(context: CursorContext, cursors: CursorState[]): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
@@ -143,8 +143,8 @@ export class CursorMoveCommands {
return result;
}
public static moveToBeginningOfBuffer(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): CursorState[] {
let result: CursorState[] = [];
public static moveToBeginningOfBuffer(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
result[i] = CursorState.fromModelState(MoveOperations.moveToBeginningOfBuffer(context.config, context.model, cursor.modelState, inSelectionMode));
@@ -152,8 +152,8 @@ export class CursorMoveCommands {
return result;
}
public static moveToEndOfBuffer(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): CursorState[] {
let result: CursorState[] = [];
public static moveToEndOfBuffer(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
result[i] = CursorState.fromModelState(MoveOperations.moveToEndOfBuffer(context.config, context.model, cursor.modelState, inSelectionMode));
@@ -161,7 +161,7 @@ export class CursorMoveCommands {
return result;
}
public static selectAll(context: CursorContext, cursor: CursorState): CursorState {
public static selectAll(context: CursorContext, cursor: CursorState): PartialCursorState {
const lineCount = context.model.getLineCount();
const maxColumn = context.model.getLineMaxColumn(lineCount);
@@ -171,7 +171,7 @@ export class CursorMoveCommands {
));
}
public static line(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, _position: IPosition, _viewPosition: IPosition): CursorState {
public static line(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, _position: IPosition, _viewPosition: IPosition): PartialCursorState {
const position = context.model.validatePosition(_position);
const viewPosition = (
_viewPosition
@@ -230,12 +230,12 @@ export class CursorMoveCommands {
}
}
public static word(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, _position: IPosition): CursorState {
public static word(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, _position: IPosition): PartialCursorState {
const position = context.model.validatePosition(_position);
return CursorState.fromModelState(WordOperations.word(context.config, context.model, cursor.modelState, inSelectionMode, position));
}
public static cancelSelection(context: CursorContext, cursor: CursorState): CursorState {
public static cancelSelection(context: CursorContext, cursor: CursorState): PartialCursorState {
if (!cursor.modelState.hasSelection()) {
return new CursorState(cursor.modelState, cursor.viewState);
}
@@ -249,7 +249,7 @@ export class CursorMoveCommands {
));
}
public static moveTo(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, _position: IPosition, _viewPosition: IPosition): CursorState {
public static moveTo(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, _position: IPosition, _viewPosition: IPosition): PartialCursorState {
const position = context.model.validatePosition(_position);
const viewPosition = (
_viewPosition
@@ -259,7 +259,7 @@ export class CursorMoveCommands {
return CursorState.fromViewState(cursor.viewState.move(inSelectionMode, viewPosition.lineNumber, viewPosition.column, 0));
}
public static move(context: CursorContext, cursors: CursorState[], args: CursorMove.ParsedArguments): CursorState[] {
public static move(context: CursorContext, cursors: CursorState[], args: CursorMove.ParsedArguments): PartialCursorState[] {
const inSelectionMode = args.select;
const value = args.value;
@@ -347,7 +347,7 @@ export class CursorMoveCommands {
case CursorMove.Direction.ViewPortIfOutside: {
// Move to a position inside the viewport
const visibleViewRange = context.getCompletelyVisibleViewRange();
let result: CursorState[] = [];
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
result[i] = this.findPositionInViewportIfOutside(context, cursor, visibleViewRange, inSelectionMode);
@@ -360,7 +360,7 @@ export class CursorMoveCommands {
}
public static findPositionInViewportIfOutside(context: CursorContext, cursor: CursorState, visibleViewRange: Range, inSelectionMode: boolean): CursorState {
public static findPositionInViewportIfOutside(context: CursorContext, cursor: CursorState, visibleViewRange: Range, inSelectionMode: boolean): PartialCursorState {
let viewLineNumber = cursor.viewState.position.lineNumber;
if (visibleViewRange.startLineNumber <= viewLineNumber && viewLineNumber <= visibleViewRange.endLineNumber - 1) {
@@ -405,8 +405,8 @@ export class CursorMoveCommands {
return Math.max(startLineNumber, range.endLineNumber - count + 1);
}
private static _moveLeft(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, noOfColumns: number): CursorState[] {
let result: CursorState[] = [];
private static _moveLeft(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, noOfColumns: number): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
@@ -426,8 +426,8 @@ export class CursorMoveCommands {
return result;
}
private static _moveHalfLineLeft(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): CursorState[] {
let result: CursorState[] = [];
private static _moveHalfLineLeft(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
const viewLineNumber = cursor.viewState.position.lineNumber;
@@ -437,8 +437,8 @@ export class CursorMoveCommands {
return result;
}
private static _moveRight(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, noOfColumns: number): CursorState[] {
let result: CursorState[] = [];
private static _moveRight(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, noOfColumns: number): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
let newViewState = MoveOperations.moveRight(context.config, context.viewModel, cursor.viewState, inSelectionMode, noOfColumns);
@@ -457,8 +457,8 @@ export class CursorMoveCommands {
return result;
}
private static _moveHalfLineRight(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): CursorState[] {
let result: CursorState[] = [];
private static _moveHalfLineRight(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
const viewLineNumber = cursor.viewState.position.lineNumber;
@@ -468,8 +468,8 @@ export class CursorMoveCommands {
return result;
}
private static _moveDownByViewLines(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, linesCount: number): CursorState[] {
let result: CursorState[] = [];
private static _moveDownByViewLines(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, linesCount: number): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
result[i] = CursorState.fromViewState(MoveOperations.moveDown(context.config, context.viewModel, cursor.viewState, inSelectionMode, linesCount));
@@ -477,8 +477,8 @@ export class CursorMoveCommands {
return result;
}
private static _moveDownByModelLines(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, linesCount: number): CursorState[] {
let result: CursorState[] = [];
private static _moveDownByModelLines(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, linesCount: number): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
result[i] = CursorState.fromModelState(MoveOperations.moveDown(context.config, context.model, cursor.modelState, inSelectionMode, linesCount));
@@ -486,8 +486,8 @@ export class CursorMoveCommands {
return result;
}
private static _moveUpByViewLines(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, linesCount: number): CursorState[] {
let result: CursorState[] = [];
private static _moveUpByViewLines(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, linesCount: number): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
result[i] = CursorState.fromViewState(MoveOperations.moveUp(context.config, context.viewModel, cursor.viewState, inSelectionMode, linesCount));
@@ -495,8 +495,8 @@ export class CursorMoveCommands {
return result;
}
private static _moveUpByModelLines(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, linesCount: number): CursorState[] {
let result: CursorState[] = [];
private static _moveUpByModelLines(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean, linesCount: number): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
result[i] = CursorState.fromModelState(MoveOperations.moveUp(context.config, context.model, cursor.modelState, inSelectionMode, linesCount));
@@ -504,16 +504,16 @@ export class CursorMoveCommands {
return result;
}
private static _moveToViewPosition(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, toViewLineNumber: number, toViewColumn: number): CursorState {
private static _moveToViewPosition(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, toViewLineNumber: number, toViewColumn: number): PartialCursorState {
return CursorState.fromViewState(cursor.viewState.move(inSelectionMode, toViewLineNumber, toViewColumn, 0));
}
private static _moveToModelPosition(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, toModelLineNumber: number, toModelColumn: number): CursorState {
private static _moveToModelPosition(context: CursorContext, cursor: CursorState, inSelectionMode: boolean, toModelLineNumber: number, toModelColumn: number): PartialCursorState {
return CursorState.fromModelState(cursor.modelState.move(inSelectionMode, toModelLineNumber, toModelColumn, 0));
}
private static _moveToViewMinColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): CursorState[] {
let result: CursorState[] = [];
private static _moveToViewMinColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
const viewLineNumber = cursor.viewState.position.lineNumber;
@@ -523,8 +523,8 @@ export class CursorMoveCommands {
return result;
}
private static _moveToViewFirstNonWhitespaceColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): CursorState[] {
let result: CursorState[] = [];
private static _moveToViewFirstNonWhitespaceColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
const viewLineNumber = cursor.viewState.position.lineNumber;
@@ -534,8 +534,8 @@ export class CursorMoveCommands {
return result;
}
private static _moveToViewCenterColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): CursorState[] {
let result: CursorState[] = [];
private static _moveToViewCenterColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
const viewLineNumber = cursor.viewState.position.lineNumber;
@@ -545,8 +545,8 @@ export class CursorMoveCommands {
return result;
}
private static _moveToViewMaxColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): CursorState[] {
let result: CursorState[] = [];
private static _moveToViewMaxColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
const viewLineNumber = cursor.viewState.position.lineNumber;
@@ -556,8 +556,8 @@ export class CursorMoveCommands {
return result;
}
private static _moveToViewLastNonWhitespaceColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): CursorState[] {
let result: CursorState[] = [];
private static _moveToViewLastNonWhitespaceColumn(context: CursorContext, cursors: CursorState[], inSelectionMode: boolean): PartialCursorState[] {
let result: PartialCursorState[] = [];
for (let i = 0, len = cursors.length; i < len; i++) {
const cursor = cursors[i];
const viewLineNumber = cursor.viewState.position.lineNumber;
@@ -49,12 +49,12 @@ export class WordOperations {
return { start: start, end: end, wordType: wordType, nextCharClass: nextCharClass };
}
private static _findPreviousWordOnLine(wordSeparators: WordCharacterClassifier, model: ICursorSimpleModel, position: Position): IFindWordResult {
private static _findPreviousWordOnLine(wordSeparators: WordCharacterClassifier, model: ICursorSimpleModel, position: Position): IFindWordResult | null {
let lineContent = model.getLineContent(position.lineNumber);
return this._doFindPreviousWordOnLine(lineContent, wordSeparators, position);
}
private static _doFindPreviousWordOnLine(lineContent: string, wordSeparators: WordCharacterClassifier, position: Position): IFindWordResult {
private static _doFindPreviousWordOnLine(lineContent: string, wordSeparators: WordCharacterClassifier, position: Position): IFindWordResult | null {
let wordType = WordType.None;
for (let chIndex = position.column - 2; chIndex >= 0; chIndex--) {
let chCode = lineContent.charCodeAt(chIndex);
@@ -103,12 +103,12 @@ export class WordOperations {
return len;
}
private static _findNextWordOnLine(wordSeparators: WordCharacterClassifier, model: ICursorSimpleModel, position: Position): IFindWordResult {
private static _findNextWordOnLine(wordSeparators: WordCharacterClassifier, model: ICursorSimpleModel, position: Position): IFindWordResult | null {
let lineContent = model.getLineContent(position.lineNumber);
return this._doFindNextWordOnLine(lineContent, wordSeparators, position);
}
private static _doFindNextWordOnLine(lineContent: string, wordSeparators: WordCharacterClassifier, position: Position): IFindWordResult {
private static _doFindNextWordOnLine(lineContent: string, wordSeparators: WordCharacterClassifier, position: Position): IFindWordResult | null {
let wordType = WordType.None;
let len = lineContent.length;
@@ -324,7 +324,7 @@ export class WordOperations {
return new Position(lineNumber, maxColumn);
}
protected static _deleteWordLeftWhitespace(model: ICursorSimpleModel, position: Position): Range {
protected static _deleteWordLeftWhitespace(model: ICursorSimpleModel, position: Position): Range | null {
const lineContent = model.getLineContent(position.lineNumber);
const startIndex = position.column - 2;
const lastNonWhitespace = strings.lastNonWhitespaceIndex(lineContent, startIndex);
@@ -334,7 +334,7 @@ export class WordOperations {
return null;
}
public static deleteWordLeft(wordSeparators: WordCharacterClassifier, model: ICursorSimpleModel, selection: Selection, whitespaceHeuristics: boolean, wordNavigationType: WordNavigationType): Range {
public static deleteWordLeft(wordSeparators: WordCharacterClassifier, model: ICursorSimpleModel, selection: Selection, whitespaceHeuristics: boolean, wordNavigationType: WordNavigationType): Range | null {
if (!selection.isEmpty()) {
return selection;
}
@@ -409,7 +409,7 @@ export class WordOperations {
return len;
}
protected static _deleteWordRightWhitespace(model: ICursorSimpleModel, position: Position): Range {
protected static _deleteWordRightWhitespace(model: ICursorSimpleModel, position: Position): Range | null {
const lineContent = model.getLineContent(position.lineNumber);
const startIndex = position.column - 1;
const firstNonWhitespace = this._findFirstNonWhitespaceChar(lineContent, startIndex);
@@ -420,7 +420,7 @@ export class WordOperations {
return null;
}
public static deleteWordRight(wordSeparators: WordCharacterClassifier, model: ICursorSimpleModel, selection: Selection, whitespaceHeuristics: boolean, wordNavigationType: WordNavigationType): Range {
public static deleteWordRight(wordSeparators: WordCharacterClassifier, model: ICursorSimpleModel, selection: Selection, whitespaceHeuristics: boolean, wordNavigationType: WordNavigationType): Range | null {
if (!selection.isEmpty()) {
return selection;
}
@@ -503,16 +503,15 @@ export class WordOperations {
if (!inSelectionMode) {
// Entering word selection for the first time
const isTouchingPrevWord = (prevWord && prevWord.wordType === WordType.Regular && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end);
const isTouchingNextWord = (nextWord && nextWord.wordType === WordType.Regular && nextWord.start <= position.column - 1 && position.column - 1 <= nextWord.end);
let startColumn: number;
let endColumn: number;
if (isTouchingPrevWord) {
if (prevWord && prevWord.wordType === WordType.Regular && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) {
// isTouchingPrevWord
startColumn = prevWord.start + 1;
endColumn = prevWord.end + 1;
} else if (isTouchingNextWord) {
} else if (nextWord && nextWord.wordType === WordType.Regular && nextWord.start <= position.column - 1 && position.column - 1 <= nextWord.end) {
// isTouchingNextWord
startColumn = nextWord.start + 1;
endColumn = nextWord.end + 1;
} else {
@@ -534,16 +533,15 @@ export class WordOperations {
);
}
const isInsidePrevWord = (prevWord && prevWord.wordType === WordType.Regular && prevWord.start < position.column - 1 && position.column - 1 < prevWord.end);
const isInsideNextWord = (nextWord && nextWord.wordType === WordType.Regular && nextWord.start < position.column - 1 && position.column - 1 < nextWord.end);
let startColumn: number;
let endColumn: number;
if (isInsidePrevWord) {
if (prevWord && prevWord.wordType === WordType.Regular && prevWord.start < position.column - 1 && position.column - 1 < prevWord.end) {
// isInsidePrevWord
startColumn = prevWord.start + 1;
endColumn = prevWord.end + 1;
} else if (isInsideNextWord) {
} else if (nextWord && nextWord.wordType === WordType.Regular && nextWord.start < position.column - 1 && position.column - 1 < nextWord.end) {
// isInsideNextWord
startColumn = nextWord.start + 1;
endColumn = nextWord.end + 1;
} else {
@@ -575,42 +573,46 @@ export class WordOperations {
export class WordPartOperations extends WordOperations {
public static deleteWordPartLeft(wordSeparators: WordCharacterClassifier, model: ICursorSimpleModel, selection: Selection, whitespaceHeuristics: boolean): Range {
const candidates = [
const candidates = enforceDefined([
WordOperations.deleteWordLeft(wordSeparators, model, selection, whitespaceHeuristics, WordNavigationType.WordStart),
WordOperations.deleteWordLeft(wordSeparators, model, selection, whitespaceHeuristics, WordNavigationType.WordEnd),
WordOperations._deleteWordPartLeft(model, selection)
];
]);
candidates.sort(Range.compareRangesUsingEnds);
return candidates[2];
}
public static deleteWordPartRight(wordSeparators: WordCharacterClassifier, model: ICursorSimpleModel, selection: Selection, whitespaceHeuristics: boolean): Range {
const candidates = [
const candidates = enforceDefined([
WordOperations.deleteWordRight(wordSeparators, model, selection, whitespaceHeuristics, WordNavigationType.WordStart),
WordOperations.deleteWordRight(wordSeparators, model, selection, whitespaceHeuristics, WordNavigationType.WordEnd),
WordOperations._deleteWordPartRight(model, selection)
];
]);
candidates.sort(Range.compareRangesUsingStarts);
return candidates[0];
}
public static moveWordPartLeft(wordSeparators: WordCharacterClassifier, model: ICursorSimpleModel, position: Position): Position {
const candidates = [
const candidates = enforceDefined([
WordOperations.moveWordLeft(wordSeparators, model, position, WordNavigationType.WordStart),
WordOperations.moveWordLeft(wordSeparators, model, position, WordNavigationType.WordEnd),
WordOperations._moveWordPartLeft(model, position)
];
]);
candidates.sort(Position.compare);
return candidates[2];
}
public static moveWordPartRight(wordSeparators: WordCharacterClassifier, model: ICursorSimpleModel, position: Position): Position {
const candidates = [
const candidates = enforceDefined([
WordOperations.moveWordRight(wordSeparators, model, position, WordNavigationType.WordStart),
WordOperations.moveWordRight(wordSeparators, model, position, WordNavigationType.WordEnd),
WordOperations._moveWordPartRight(model, position)
];
]);
candidates.sort(Position.compare);
return candidates[0];
}
}
function enforceDefined<T>(arr: (T | undefined | null)[]): T[] {
return <T[]>arr.filter(el => Boolean(el));
}
+2 -5
View File
@@ -14,13 +14,10 @@ export class OneCursor {
public modelState: SingleCursorState;
public viewState: SingleCursorState;
private _selTrackedRange: string;
private _selTrackedRange: string | null;
private _trackSelection: boolean;
constructor(context: CursorContext) {
this.modelState = null;
this.viewState = null;
this._selTrackedRange = null;
this._trackSelection = true;
@@ -62,7 +59,7 @@ export class OneCursor {
}
public readSelectionFromMarkers(context: CursorContext): Selection {
const range = context.model._getTrackedRange(this._selTrackedRange);
const range = context.model._getTrackedRange(this._selTrackedRange!)!;
if (this.modelState.selection.getDirection() === SelectionDirection.LTR) {
return new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
}
+6 -4
View File
@@ -172,14 +172,14 @@ export class Range {
/**
* A intersection of the two ranges.
*/
public intersectRanges(range: IRange): Range {
public intersectRanges(range: IRange): Range | null {
return Range.intersectRanges(this, range);
}
/**
* A intersection of the two ranges.
*/
public static intersectRanges(a: IRange, b: IRange): Range {
public static intersectRanges(a: IRange, b: IRange): Range | null {
let resultStartLineNumber = a.startLineNumber;
let resultStartColumn = a.startColumn;
let resultEndLineNumber = a.endLineNumber;
@@ -223,7 +223,7 @@ export class Range {
/**
* Test if range `a` equals `b`.
*/
public static equalsRange(a: IRange, b: IRange): boolean {
public static equalsRange(a: IRange | null, b: IRange | null): boolean {
return (
!!a &&
!!b &&
@@ -292,7 +292,9 @@ export class Range {
/**
* Create a `Range` from an `IRange`.
*/
public static lift(range: IRange): Range {
public static lift(range: undefined | null): null;
public static lift(range: IRange): Range;
public static lift(range: IRange | undefined | null): Range | null {
if (!range) {
return null;
}
+2
View File
@@ -10,6 +10,8 @@
export class RGBA8 {
_rgba8Brand: void;
static Empty = new RGBA8(0, 0, 0, 0);
/**
* Red: integer in [0-255]
*/
+2 -2
View File
@@ -32,7 +32,7 @@ class StringBuilder implements IStringBuilder {
private readonly _capacity: number;
private readonly _buffer: Uint16Array;
private _completedStrings: string[];
private _completedStrings: string[] | null;
private _bufferLength: number;
constructor(capacity: number) {
@@ -104,7 +104,7 @@ class StringBuilder implements IStringBuilder {
// This string does not fit in the remaining buffer space
this._flushBuffer();
this._completedStrings[this._completedStrings.length] = str;
this._completedStrings![this._completedStrings!.length] = str;
return;
}
+5 -5
View File
@@ -238,14 +238,14 @@ class LineChange implements ILineChange {
public originalEndLineNumber: number;
public modifiedStartLineNumber: number;
public modifiedEndLineNumber: number;
public charChanges: CharChange[];
public charChanges: CharChange[] | undefined;
constructor(
originalStartLineNumber: number,
originalEndLineNumber: number,
modifiedStartLineNumber: number,
modifiedEndLineNumber: number,
charChanges: CharChange[]
charChanges: CharChange[] | undefined
) {
this.originalStartLineNumber = originalStartLineNumber;
this.originalEndLineNumber = originalEndLineNumber;
@@ -259,7 +259,7 @@ class LineChange implements ILineChange {
let originalEndLineNumber: number;
let modifiedStartLineNumber: number;
let modifiedEndLineNumber: number;
let charChanges: CharChange[];
let charChanges: CharChange[] | undefined = undefined;
if (diffChange.originalLength === 0) {
originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart) - 1;
@@ -477,7 +477,7 @@ export class DiffComputer {
return;
}
let charChanges: CharChange[];
let charChanges: CharChange[] | undefined = undefined;
if (this.shouldComputeCharChanges) {
charChanges = [new CharChange(
originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn,
@@ -512,7 +512,7 @@ export class DiffComputer {
prevChange.originalEndLineNumber = originalLineNumber;
prevChange.modifiedEndLineNumber = modifiedLineNumber;
if (this.shouldComputeCharChanges) {
prevChange.charChanges.push(new CharChange(
prevChange.charChanges!.push(new CharChange(
originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn,
modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn
));
+2 -2
View File
@@ -22,7 +22,7 @@ export interface IEditOperationBuilder {
* @param range The range to replace (delete). May be empty to represent a simple insert.
* @param text The text to replace with. May be null to represent a simple delete.
*/
addEditOperation(range: Range, text: string): void;
addEditOperation(range: Range, text: string | null): void;
/**
* Add a new edit operation (a replace operation).
@@ -142,7 +142,7 @@ export interface ICharChange extends IChange {
* A line change
*/
export interface ILineChange extends IChange {
readonly charChanges: ICharChange[];
readonly charChanges: ICharChange[] | undefined;
}
/**
+16 -16
View File
@@ -28,24 +28,24 @@ export namespace EditorContextKeys {
export const hasSingleSelection: ContextKeyExpr = hasMultipleSelections.toNegated();
export const tabMovesFocus = new RawContextKey<boolean>('editorTabMovesFocus', false);
export const tabDoesNotMoveFocus: ContextKeyExpr = tabMovesFocus.toNegated();
export const isInEmbeddedEditor = new RawContextKey<boolean>('isInEmbeddedEditor', undefined);
export const isInEmbeddedEditor = new RawContextKey<boolean>('isInEmbeddedEditor', false);
export const canUndo = new RawContextKey<boolean>('canUndo', false);
export const canRedo = new RawContextKey<boolean>('canRedo', false);
// -- mode context keys
export const languageId = new RawContextKey<string>('editorLangId', undefined);
export const hasCompletionItemProvider = new RawContextKey<boolean>('editorHasCompletionItemProvider', undefined);
export const hasCodeActionsProvider = new RawContextKey<boolean>('editorHasCodeActionsProvider', undefined);
export const hasCodeLensProvider = new RawContextKey<boolean>('editorHasCodeLensProvider', undefined);
export const hasDefinitionProvider = new RawContextKey<boolean>('editorHasDefinitionProvider', undefined);
export const hasImplementationProvider = new RawContextKey<boolean>('editorHasImplementationProvider', undefined);
export const hasTypeDefinitionProvider = new RawContextKey<boolean>('editorHasTypeDefinitionProvider', undefined);
export const hasHoverProvider = new RawContextKey<boolean>('editorHasHoverProvider', undefined);
export const hasDocumentHighlightProvider = new RawContextKey<boolean>('editorHasDocumentHighlightProvider', undefined);
export const hasDocumentSymbolProvider = new RawContextKey<boolean>('editorHasDocumentSymbolProvider', undefined);
export const hasReferenceProvider = new RawContextKey<boolean>('editorHasReferenceProvider', undefined);
export const hasRenameProvider = new RawContextKey<boolean>('editorHasRenameProvider', undefined);
export const hasDocumentFormattingProvider = new RawContextKey<boolean>('editorHasDocumentFormattingProvider', undefined);
export const hasDocumentSelectionFormattingProvider = new RawContextKey<boolean>('editorHasDocumentSelectionFormattingProvider', undefined);
export const hasSignatureHelpProvider = new RawContextKey<boolean>('editorHasSignatureHelpProvider', undefined);
export const languageId = new RawContextKey<string>('editorLangId', '');
export const hasCompletionItemProvider = new RawContextKey<boolean>('editorHasCompletionItemProvider', false);
export const hasCodeActionsProvider = new RawContextKey<boolean>('editorHasCodeActionsProvider', false);
export const hasCodeLensProvider = new RawContextKey<boolean>('editorHasCodeLensProvider', false);
export const hasDefinitionProvider = new RawContextKey<boolean>('editorHasDefinitionProvider', false);
export const hasImplementationProvider = new RawContextKey<boolean>('editorHasImplementationProvider', false);
export const hasTypeDefinitionProvider = new RawContextKey<boolean>('editorHasTypeDefinitionProvider', false);
export const hasHoverProvider = new RawContextKey<boolean>('editorHasHoverProvider', false);
export const hasDocumentHighlightProvider = new RawContextKey<boolean>('editorHasDocumentHighlightProvider', false);
export const hasDocumentSymbolProvider = new RawContextKey<boolean>('editorHasDocumentSymbolProvider', false);
export const hasReferenceProvider = new RawContextKey<boolean>('editorHasReferenceProvider', false);
export const hasRenameProvider = new RawContextKey<boolean>('editorHasRenameProvider', false);
export const hasDocumentFormattingProvider = new RawContextKey<boolean>('editorHasDocumentFormattingProvider', false);
export const hasDocumentSelectionFormattingProvider = new RawContextKey<boolean>('editorHasDocumentSelectionFormattingProvider', false);
export const hasSignatureHelpProvider = new RawContextKey<boolean>('editorHasSignatureHelpProvider', false);
}
+31 -31
View File
@@ -58,15 +58,15 @@ export interface IModelDecorationOptions {
/**
* CSS class name describing the decoration.
*/
className?: string;
className?: string | null;
/**
* Message to be rendered when hovering over the glyph margin decoration.
*/
glyphMarginHoverMessage?: IMarkdownString | IMarkdownString[];
glyphMarginHoverMessage?: IMarkdownString | IMarkdownString[] | null;
/**
* Array of MarkdownString to render as the decoration message.
*/
hoverMessage?: IMarkdownString | IMarkdownString[];
hoverMessage?: IMarkdownString | IMarkdownString[] | null;
/**
* Should the decoration expand to encompass a whole line.
*/
@@ -89,25 +89,25 @@ export interface IModelDecorationOptions {
/**
* If set, render this decoration in the overview ruler.
*/
overviewRuler?: IModelDecorationOverviewRulerOptions;
overviewRuler?: IModelDecorationOverviewRulerOptions | null;
/**
* If set, the decoration will be rendered in the glyph margin with this CSS class name.
*/
glyphMarginClassName?: string;
glyphMarginClassName?: string | null;
/**
* If set, the decoration will be rendered in the lines decorations with this CSS class name.
*/
linesDecorationsClassName?: string;
linesDecorationsClassName?: string | null;
/**
* If set, the decoration will be rendered in the margin (covering its full width) with this CSS class name.
*/
marginClassName?: string;
marginClassName?: string | null;
/**
* If set, the decoration will be rendered inline with the text with this CSS class name.
* Please use this only for CSS rules that must impact the text. For example, use `className`
* to have a background color decoration.
*/
inlineClassName?: string;
inlineClassName?: string | null;
/**
* If there is an `inlineClassName` which affects letter spacing.
*/
@@ -115,11 +115,11 @@ export interface IModelDecorationOptions {
/**
* If set, the decoration will be rendered before the text with this CSS class name.
*/
beforeContentClassName?: string;
beforeContentClassName?: string | null;
/**
* If set, the decoration will be rendered after the text with this CSS class name.
*/
afterContentClassName?: string;
afterContentClassName?: string | null;
}
/**
@@ -305,7 +305,7 @@ export interface IIdentifiedSingleEditOperation {
* An identifier associated with this single edit operation.
* @internal
*/
identifier?: ISingleEditOperationIdentifier;
identifier?: ISingleEditOperationIdentifier | null;
/**
* The range to replace. This can be empty to emulate a simple insert.
*/
@@ -313,7 +313,7 @@ export interface IIdentifiedSingleEditOperation {
/**
* The text to replace with. This can be null to emulate a simple delete.
*/
text: string;
text: string | null;
/**
* This indicates that this operation has "insert" semantics.
* i.e. forceMoveMarkers = true => if `range` is collapsed, all markers at the position will be moved.
@@ -412,12 +412,12 @@ export class FindMatch {
_findMatchBrand: void;
public readonly range: Range;
public readonly matches: string[];
public readonly matches: string[] | null;
/**
* @internal
*/
constructor(range: Range, matches: string[]) {
constructor(range: Range, matches: string[] | null) {
this.range = range;
this.matches = matches;
}
@@ -719,7 +719,7 @@ export interface ITextModel {
* @param captureMatches The result will contain the captured groups.
* @return The range where the next match is. It is null if no next match has been found.
*/
findNextMatch(searchString: string, searchStart: IPosition, isRegex: boolean, matchCase: boolean, wordSeparators: string | null, captureMatches: boolean): FindMatch;
findNextMatch(searchString: string, searchStart: IPosition, isRegex: boolean, matchCase: boolean, wordSeparators: string | null, captureMatches: boolean): FindMatch | null;
/**
* Search the model for the previous match. Loops to the end of the model if needed.
* @param searchString The string used to search. If it is a regular expression, set `isRegex` to true.
@@ -730,7 +730,7 @@ export interface ITextModel {
* @param captureMatches The result will contain the captured groups.
* @return The range where the previous match is. It is null if no previous match has been found.
*/
findPreviousMatch(searchString: string, searchStart: IPosition, isRegex: boolean, matchCase: boolean, wordSeparators: string | null, captureMatches: boolean): FindMatch;
findPreviousMatch(searchString: string, searchStart: IPosition, isRegex: boolean, matchCase: boolean, wordSeparators: string | null, captureMatches: boolean): FindMatch | null;
/**
* Force tokenization information for `lineNumber` to be accurate.
@@ -788,7 +788,7 @@ export interface ITextModel {
* @param position The position to look for a word.
* @return The word under or besides `position`. Might be null.
*/
getWordAtPosition(position: IPosition): IWordAtPosition;
getWordAtPosition(position: IPosition): IWordAtPosition | null;
/**
* Get the word under or besides `position` trimmed to `position`.column
@@ -804,7 +804,7 @@ export interface ITextModel {
* @return The range of the matching bracket, or null if the bracket match was not found.
* @internal
*/
findMatchingBracketUp(bracket: string, position: IPosition): Range;
findMatchingBracketUp(bracket: string, position: IPosition): Range | null;
/**
* Find the first bracket in the model before `position`.
@@ -812,7 +812,7 @@ export interface ITextModel {
* @return The info for the first bracket before `position`, or null if there are no more brackets before `positions`.
* @internal
*/
findPrevBracket(position: IPosition): IFoundBracket;
findPrevBracket(position: IPosition): IFoundBracket | null;
/**
* Find the first bracket in the model after `position`.
@@ -820,7 +820,7 @@ export interface ITextModel {
* @return The info for the first bracket after `position`, or null if there are no more brackets after `positions`.
* @internal
*/
findNextBracket(position: IPosition): IFoundBracket;
findNextBracket(position: IPosition): IFoundBracket | null;
/**
* Given a `position`, if the position is on top or near a bracket,
@@ -828,7 +828,7 @@ export interface ITextModel {
* @param position The position at which to look for a bracket.
* @internal
*/
matchBracket(position: IPosition): [Range, Range];
matchBracket(position: IPosition): [Range, Range] | null;
/**
* @internal
@@ -848,7 +848,7 @@ export interface ITextModel {
* @param ownerId Identifies the editor id in which these decorations should appear. If no `ownerId` is provided, the decorations will appear in all editors that attach this model.
* @internal
*/
changeDecorations<T>(callback: (changeAccessor: IModelDecorationsChangeAccessor) => T, ownerId?: number): T;
changeDecorations<T>(callback: (changeAccessor: IModelDecorationsChangeAccessor) => T, ownerId?: number): T | null;
/**
* Perform a minimum ammount of operations, in order to transform the decorations
@@ -874,14 +874,14 @@ export interface ITextModel {
* @param id The decoration id.
* @return The decoration options or null if the decoration was not found.
*/
getDecorationOptions(id: string): IModelDecorationOptions;
getDecorationOptions(id: string): IModelDecorationOptions | null;
/**
* Get the range associated with a decoration.
* @param id The decoration id.
* @return The decoration range or null if the decoration was not found.
*/
getDecorationRange(id: string): Range;
getDecorationRange(id: string): Range | null;
/**
* Gets all the decorations for the line `lineNumber` as an array.
@@ -929,12 +929,12 @@ export interface ITextModel {
/**
* @internal
*/
_getTrackedRange(id: string): Range;
_getTrackedRange(id: string): Range | null;
/**
* @internal
*/
_setTrackedRange(id: string, newRange: Range, newStickiness: TrackedRangeStickiness): string;
_setTrackedRange(id: string | null, newRange: Range | null, newStickiness: TrackedRangeStickiness): string | null;
/**
* Normalize a string containing whitespace according to indentation rules (converts to spaces or to tabs).
@@ -971,7 +971,7 @@ export interface ITextModel {
* @param cursorStateComputer A callback that can compute the resulting cursors state after the edit operations have been executed.
* @return The cursor state returned by the `cursorStateComputer`.
*/
pushEditOperations(beforeCursorState: Selection[], editOperations: IIdentifiedSingleEditOperation[], cursorStateComputer: ICursorStateComputer): Selection[];
pushEditOperations(beforeCursorState: Selection[], editOperations: IIdentifiedSingleEditOperation[], cursorStateComputer: ICursorStateComputer): Selection[] | null;
/**
* Change the end of line sequence. This is the preferred way of
@@ -998,7 +998,7 @@ export interface ITextModel {
* The inverse edit operations will be pushed on the redo stack.
* @internal
*/
undo(): Selection[];
undo(): Selection[] | null;
/**
* Is there anything in the undo stack?
@@ -1011,7 +1011,7 @@ export interface ITextModel {
* The inverse edit operations will be pushed on the undo stack.
* @internal
*/
redo(): Selection[];
redo(): Selection[] | null;
/**
* Is there anything in the redo stack?
@@ -1143,7 +1143,7 @@ export interface ITextBuffer {
setEOL(newEOL: '\r\n' | '\n'): void;
applyEdits(rawOperations: IIdentifiedSingleEditOperation[], recordTrimAutoWhitespace: boolean): ApplyEditsResult;
findMatchesLineByLine?(searchRange: Range, searchData: SearchData, captureMatches: boolean, limitResultCount: number): FindMatch[];
findMatchesLineByLine(searchRange: Range, searchData: SearchData, captureMatches: boolean, limitResultCount: number): FindMatch[];
}
/**
@@ -1154,7 +1154,7 @@ export class ApplyEditsResult {
constructor(
public readonly reverseEdits: IIdentifiedSingleEditOperation[],
public readonly changes: IInternalModelContentChange[],
public readonly trimAutoWhitespaceLineNumbers: number[]
public readonly trimAutoWhitespaceLineNumbers: number[] | null
) { }
}
+18 -18
View File
@@ -14,8 +14,8 @@ interface IEditOperation {
interface IStackElement {
readonly beforeVersionId: number;
readonly beforeCursorState: Selection[];
readonly afterCursorState: Selection[];
readonly beforeCursorState: Selection[] | null;
readonly afterCursorState: Selection[] | null;
readonly afterVersionId: number;
undo(model: TextModel): void;
@@ -25,7 +25,7 @@ interface IStackElement {
class EditStackElement implements IStackElement {
public readonly beforeVersionId: number;
public readonly beforeCursorState: Selection[];
public afterCursorState: Selection[];
public afterCursorState: Selection[] | null;
public afterVersionId: number;
public editOperations: IEditOperation[];
@@ -68,8 +68,8 @@ function getModelEOL(model: TextModel): EndOfLineSequence {
class EOLStackElement implements IStackElement {
public readonly beforeVersionId: number;
public readonly beforeCursorState: Selection[];
public readonly afterCursorState: Selection[];
public readonly beforeCursorState: Selection[] | null;
public readonly afterCursorState: Selection[] | null;
public afterVersionId: number;
public eol: EndOfLineSequence;
@@ -96,14 +96,14 @@ class EOLStackElement implements IStackElement {
}
export interface IUndoRedoResult {
selections: Selection[];
selections: Selection[] | null;
recordedVersionId: number;
}
export class EditStack {
private model: TextModel;
private currentOpenStackElement: IStackElement;
private currentOpenStackElement: IStackElement | null;
private past: IStackElement[];
private future: IStackElement[];
@@ -145,11 +145,11 @@ export class EditStack {
this.pushStackElement();
}
public pushEditOperation(beforeCursorState: Selection[], editOperations: IIdentifiedSingleEditOperation[], cursorStateComputer: ICursorStateComputer): Selection[] {
public pushEditOperation(beforeCursorState: Selection[], editOperations: IIdentifiedSingleEditOperation[], cursorStateComputer: ICursorStateComputer): Selection[] | null {
// No support for parallel universes :(
this.future = [];
let stackElement: EditStackElement = null;
let stackElement: EditStackElement | null = null;
if (this.currentOpenStackElement) {
if (this.currentOpenStackElement instanceof EditStackElement) {
@@ -168,13 +168,13 @@ export class EditStack {
operations: this.model.applyEdits(editOperations)
};
stackElement.editOperations.push(inverseEditOperation);
stackElement.afterCursorState = EditStack._computeCursorState(cursorStateComputer, inverseEditOperation.operations);
stackElement.afterVersionId = this.model.getVersionId();
return stackElement.afterCursorState;
stackElement!.editOperations.push(inverseEditOperation);
stackElement!.afterCursorState = EditStack._computeCursorState(cursorStateComputer, inverseEditOperation.operations);
stackElement!.afterVersionId = this.model.getVersionId();
return stackElement!.afterCursorState;
}
private static _computeCursorState(cursorStateComputer: ICursorStateComputer, inverseEditOperations: IIdentifiedSingleEditOperation[]): Selection[] {
private static _computeCursorState(cursorStateComputer: ICursorStateComputer, inverseEditOperations: IIdentifiedSingleEditOperation[]): Selection[] | null {
try {
return cursorStateComputer ? cursorStateComputer(inverseEditOperations) : null;
} catch (e) {
@@ -183,12 +183,12 @@ export class EditStack {
}
}
public undo(): IUndoRedoResult {
public undo(): IUndoRedoResult | null {
this.pushStackElement();
if (this.past.length > 0) {
const pastStackElement = this.past.pop();
const pastStackElement = this.past.pop()!;
try {
pastStackElement.undo(this.model);
@@ -213,10 +213,10 @@ export class EditStack {
return (this.past.length > 0);
}
public redo(): IUndoRedoResult {
public redo(): IUndoRedoResult | null {
if (this.future.length > 0) {
const futureStackElement = this.future.pop();
const futureStackElement = this.future.pop()!;
try {
futureStackElement.redo(this.model);

Some files were not shown because too many files have changed in this diff Show More