diff --git a/build/gulpfile.hygiene.js b/build/gulpfile.hygiene.js index 605da28ff3dc4..fc7d78fcf341a 100644 --- a/build/gulpfile.hygiene.js +++ b/build/gulpfile.hygiene.js @@ -9,6 +9,7 @@ const gulp = require('gulp'); const filter = require('gulp-filter'); const es = require('event-stream'); const gulptslint = require('gulp-tslint'); +const tsfmt = require('typescript-formatter'); const tslint = require('tslint'); const all = [ @@ -159,6 +160,24 @@ const hygiene = exports.hygiene = (some, options) => { this.emit('data', file); }); + const formatting = es.map(function (file, cb) { + + tsfmt.processString(file.path, file.contents.toString('utf8'), { + verify: true, + tsfmt: true, + // verbose: true + }).then(result => { + if (result.error) { + console.error(result.message); + errorCount++; + } + cb(null, file); + + }, err => { + cb(err); + }); + }); + const tsl = es.through(function(file) { const configuration = tslint.findConfiguration(null, '.'); const options = { configuration, formatter: 'json', rulesDirectory: 'build/lib/tslint' }; @@ -183,6 +202,7 @@ const hygiene = exports.hygiene = (some, options) => { .pipe(filter(copyrightFilter)) .pipe(copyrights) .pipe(filter(tslintFilter)) + .pipe(formatting) .pipe(tsl) .pipe(es.through(null, function () { if (errorCount > 0) { diff --git a/extensions/configuration-editing/src/extension.ts b/extensions/configuration-editing/src/extension.ts index bb9175fed3307..e338cd3d42a62 100644 --- a/extensions/configuration-editing/src/extension.ts +++ b/extensions/configuration-editing/src/extension.ts @@ -6,7 +6,7 @@ 'use strict'; import * as vscode from 'vscode'; -import {getLocation} from 'jsonc-parser'; +import { getLocation } from 'jsonc-parser'; export function activate(context) { @@ -15,7 +15,7 @@ export function activate(context) { } -function registerKeybindingsCompletions() : vscode.Disposable { +function registerKeybindingsCompletions(): vscode.Disposable { const commands = vscode.commands.getCommands(true); return vscode.languages.registerCompletionItemProvider({ pattern: '**/keybindings.json' }, { diff --git a/extensions/css/client/src/colorDecorators.ts b/extensions/css/client/src/colorDecorators.ts index b4135c6b5e042..959b44565e113 100644 --- a/extensions/css/client/src/colorDecorators.ts +++ b/extensions/css/client/src/colorDecorators.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {window, workspace, DecorationOptions, DecorationRenderOptions, Disposable, Range, TextDocument, TextEditor} from 'vscode'; +import { window, workspace, DecorationOptions, DecorationRenderOptions, Disposable, Range, TextDocument, TextEditor } from 'vscode'; const MAX_DECORATORS = 500; @@ -30,7 +30,7 @@ export function activateColorDecorations(decoratorProvider: (uri: string) => The let colorsDecorationType = window.createTextEditorDecorationType(decorationType); disposables.push(colorsDecorationType); - let pendingUpdateRequests : { [key:string]: NodeJS.Timer; } = {}; + let pendingUpdateRequests: { [key: string]: NodeJS.Timer; } = {}; // we care about all visible editors window.visibleTextEditors.forEach(editor => { diff --git a/extensions/css/client/src/cssMain.ts b/extensions/css/client/src/cssMain.ts index 64e05cc5d1d46..59fe3a74bb40e 100644 --- a/extensions/css/client/src/cssMain.ts +++ b/extensions/css/client/src/cssMain.ts @@ -6,9 +6,9 @@ import * as path from 'path'; -import {languages, window, commands, ExtensionContext} from 'vscode'; -import {LanguageClient, LanguageClientOptions, ServerOptions, TransportKind, RequestType, Range, TextEdit, Protocol2Code} from 'vscode-languageclient'; -import {activateColorDecorations} from './colorDecorators'; +import { languages, window, commands, ExtensionContext } from 'vscode'; +import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind, RequestType, Range, TextEdit, Protocol2Code } from 'vscode-languageclient'; +import { activateColorDecorations } from './colorDecorators'; import * as nls from 'vscode-nls'; let localize = nls.loadMessageBundle(); diff --git a/extensions/css/server/src/cssServerMain.ts b/extensions/css/server/src/cssServerMain.ts index 751be2baefd6f..32a6523a7512e 100644 --- a/extensions/css/server/src/cssServerMain.ts +++ b/extensions/css/server/src/cssServerMain.ts @@ -9,8 +9,8 @@ import { TextDocuments, TextDocument, InitializeParams, InitializeResult, RequestType } from 'vscode-languageserver'; -import {getCSSLanguageService, getSCSSLanguageService, getLESSLanguageService, LanguageSettings, LanguageService, Stylesheet} from 'vscode-css-languageservice'; -import {getLanguageModelCache} from './languageModelCache'; +import { getCSSLanguageService, getSCSSLanguageService, getLESSLanguageService, LanguageSettings, LanguageService, Stylesheet } from 'vscode-css-languageservice'; +import { getLanguageModelCache } from './languageModelCache'; namespace ColorSymbolRequest { export const type: RequestType = { get method() { return 'css/colorSymbols'; } }; @@ -62,7 +62,7 @@ connection.onInitialize((params: InitializeParams): InitializeResult => { }; }); -let languageServices : { [id:string]: LanguageService} = { +let languageServices: { [id: string]: LanguageService } = { css: getCSSLanguageService(), scss: getSCSSLanguageService(), less: getLESSLanguageService() @@ -90,7 +90,7 @@ function updateConfiguration(settings: Settings) { documents.all().forEach(triggerValidation); } -let pendingValidationRequests : { [uri:string]: NodeJS.Timer } = {}; +let pendingValidationRequests: { [uri: string]: NodeJS.Timer } = {}; const validationDelayMs = 200; // The content of a text document has changed. This event is emitted diff --git a/extensions/css/server/src/languageModelCache.ts b/extensions/css/server/src/languageModelCache.ts index dce68bed9a32c..b12f77b52a61d 100644 --- a/extensions/css/server/src/languageModelCache.ts +++ b/extensions/css/server/src/languageModelCache.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {TextDocument} from 'vscode-languageserver'; +import { TextDocument } from 'vscode-languageserver'; export interface LanguageModelCache { get(document: TextDocument): T; @@ -12,8 +12,8 @@ export interface LanguageModelCache { dispose(): void; } -export function getLanguageModelCache(maxEntries: number, cleanupIntervalTimeInSec: number, parse: (document: TextDocument) => T) : LanguageModelCache { - let languageModels: { [uri:string]: {version:number, languageId: string, cTime: number, languageModel: T}} = {}; +export function getLanguageModelCache(maxEntries: number, cleanupIntervalTimeInSec: number, parse: (document: TextDocument) => T): LanguageModelCache { + let languageModels: { [uri: string]: { version: number, languageId: string, cTime: number, languageModel: T } } = {}; let nModels = 0; let cleanupInterval = void 0; @@ -32,7 +32,7 @@ export function getLanguageModelCache(maxEntries: number, cleanupIntervalTime } return { - get(document: TextDocument) : T { + get(document: TextDocument): T { let version = document.version; let languageId = document.languageId; let languageModelInfo = languageModels[document.uri]; @@ -41,7 +41,7 @@ export function getLanguageModelCache(maxEntries: number, cleanupIntervalTime return languageModelInfo.languageModel; } let languageModel = parse(document); - languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now()}; + languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now() }; if (!languageModelInfo) { nModels++; } diff --git a/extensions/css/server/src/typings/promise.d.ts b/extensions/css/server/src/typings/promise.d.ts index 31b97cb9580a3..925c943df50a6 100644 --- a/extensions/css/server/src/typings/promise.d.ts +++ b/extensions/css/server/src/typings/promise.d.ts @@ -31,8 +31,8 @@ interface Thenable { * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ - then(onfulfilled?: (value: R) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Thenable; - then(onfulfilled?: (value: R) => TResult | Thenable, onrejected?: (reason: any) => void): Thenable; + then(onfulfilled?: (value: R) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Thenable; + then(onfulfilled?: (value: R) => TResult | Thenable, onrejected?: (reason: any) => void): Thenable; } /** @@ -45,15 +45,15 @@ interface Promise extends Thenable { * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ - then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Promise; - then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => void): Promise; + then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Promise; + then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => void): Promise; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ - catch(onrejected?: (reason: any) => T | Thenable): Promise; + catch(onrejected?: (reason: any) => T | Thenable): Promise; } interface PromiseConstructor { @@ -63,7 +63,7 @@ interface PromiseConstructor { * a resolve callback used resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ - new (executor: (resolve: (value?: T | Thenable) => void, reject: (reason?: any) => void) => void): Promise; + new (executor: (resolve: (value?: T | Thenable) => void, reject: (reason?: any) => void) => void): Promise; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises @@ -71,7 +71,7 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - all(values: Array>): Promise; + all(values: Array>): Promise; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved @@ -79,34 +79,34 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - race(values: Array>): Promise; + race(values: Array>): Promise; /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ - reject(reason: any): Promise; + reject(reason: any): Promise; /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ - reject(reason: any): Promise; + reject(reason: any): Promise; /** * Creates a new resolved promise for the provided value. * @param value A promise. * @returns A promise whose internal state matches the provided promise. */ - resolve(value: T | Thenable): Promise; + resolve(value: T | Thenable): Promise; /** * Creates a new resolved promise . * @returns A resolved promise. */ - resolve(): Promise; + resolve(): Promise; } declare var Promise: PromiseConstructor; diff --git a/extensions/html/client/src/htmlEmptyTagsShared.ts b/extensions/html/client/src/htmlEmptyTagsShared.ts index 250fa18be0e80..872b3880aba1c 100644 --- a/extensions/html/client/src/htmlEmptyTagsShared.ts +++ b/extensions/html/client/src/htmlEmptyTagsShared.ts @@ -3,4 +3,4 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -export const EMPTY_ELEMENTS:string[] = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr']; +export const EMPTY_ELEMENTS: string[] = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr']; diff --git a/extensions/html/client/src/htmlMain.ts b/extensions/html/client/src/htmlMain.ts index 2273bc99c8d55..11e09c8d0ecc1 100644 --- a/extensions/html/client/src/htmlMain.ts +++ b/extensions/html/client/src/htmlMain.ts @@ -6,9 +6,9 @@ import * as path from 'path'; -import {languages, ExtensionContext, IndentAction} from 'vscode'; -import {LanguageClient, LanguageClientOptions, ServerOptions, TransportKind} from 'vscode-languageclient'; -import {EMPTY_ELEMENTS} from './htmlEmptyTagsShared'; +import { languages, ExtensionContext, IndentAction } from 'vscode'; +import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind } from 'vscode-languageclient'; +import { EMPTY_ELEMENTS } from './htmlEmptyTagsShared'; import * as nls from 'vscode-nls'; let localize = nls.loadMessageBundle(); @@ -50,7 +50,7 @@ export function activate(context: ExtensionContext) { languages.setLanguageConfiguration('html', { wordPattern: /("(?:[^\\\"]*(?:\\.)?)*"?)|('(?:[^\\\']*(?:\\.)?)*'?)|[^\s<>={}\[\],]+/, - onEnterRules:[ + onEnterRules: [ { beforeText: new RegExp(`<(?!(?:${EMPTY_ELEMENTS.join('|')}))([_:\\w][_:\\w-.\\d]*)([^/>]*(?!/)>)[^<]*$`, 'i'), afterText: /^<\/([_:\w][_:\w-.\d]*)\s*>$/i, @@ -65,7 +65,7 @@ export function activate(context: ExtensionContext) { languages.setLanguageConfiguration('handlebars', { wordPattern: /("(?:[^\\\"]*(?:\\.)?)*"?)|('(?:[^\\\']*(?:\\.)?)*'?)|[^\s<>={}\[\],]+/, - onEnterRules:[ + onEnterRules: [ { beforeText: new RegExp(`<(?!(?:${EMPTY_ELEMENTS.join('|')}))([_:\\w][_:\\w-.\\d]*)([^/>]*(?!/)>)[^<]*$`, 'i'), afterText: /^<\/([_:\w][_:\w-.\d]*)\s*>$/i, @@ -80,7 +80,7 @@ export function activate(context: ExtensionContext) { languages.setLanguageConfiguration('razor', { wordPattern: /("(?:[^\\\"]*(?:\\.)?)*"?)|('(?:[^\\\']*(?:\\.)?)*'?)|[^\s<>={}\[\],]+/, - onEnterRules:[ + onEnterRules: [ { beforeText: new RegExp(`<(?!(?:${EMPTY_ELEMENTS.join('|')}))([_:\\w][_:\\w-.\\d]*)([^/>]*(?!/)>)[^<]*$`, 'i'), afterText: /^<\/([_:\w][_:\w-.\d]*)\s*>$/i, diff --git a/extensions/html/server/src/htmlServerMain.ts b/extensions/html/server/src/htmlServerMain.ts index 89fc06408e2cd..7fd6263335299 100644 --- a/extensions/html/server/src/htmlServerMain.ts +++ b/extensions/html/server/src/htmlServerMain.ts @@ -4,10 +4,10 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {createConnection, IConnection, TextDocuments, InitializeParams, InitializeResult} from 'vscode-languageserver'; +import { createConnection, IConnection, TextDocuments, InitializeParams, InitializeResult } from 'vscode-languageserver'; -import {HTMLDocument, getLanguageService, CompletionConfiguration, HTMLFormatConfiguration} from 'vscode-html-languageservice'; -import {getLanguageModelCache} from './languageModelCache'; +import { HTMLDocument, getLanguageService, CompletionConfiguration, HTMLFormatConfiguration } from 'vscode-html-languageservice'; +import { getLanguageModelCache } from './languageModelCache'; import * as nls from 'vscode-nls'; diff --git a/extensions/html/server/src/languageModelCache.ts b/extensions/html/server/src/languageModelCache.ts index dce68bed9a32c..b12f77b52a61d 100644 --- a/extensions/html/server/src/languageModelCache.ts +++ b/extensions/html/server/src/languageModelCache.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {TextDocument} from 'vscode-languageserver'; +import { TextDocument } from 'vscode-languageserver'; export interface LanguageModelCache { get(document: TextDocument): T; @@ -12,8 +12,8 @@ export interface LanguageModelCache { dispose(): void; } -export function getLanguageModelCache(maxEntries: number, cleanupIntervalTimeInSec: number, parse: (document: TextDocument) => T) : LanguageModelCache { - let languageModels: { [uri:string]: {version:number, languageId: string, cTime: number, languageModel: T}} = {}; +export function getLanguageModelCache(maxEntries: number, cleanupIntervalTimeInSec: number, parse: (document: TextDocument) => T): LanguageModelCache { + let languageModels: { [uri: string]: { version: number, languageId: string, cTime: number, languageModel: T } } = {}; let nModels = 0; let cleanupInterval = void 0; @@ -32,7 +32,7 @@ export function getLanguageModelCache(maxEntries: number, cleanupIntervalTime } return { - get(document: TextDocument) : T { + get(document: TextDocument): T { let version = document.version; let languageId = document.languageId; let languageModelInfo = languageModels[document.uri]; @@ -41,7 +41,7 @@ export function getLanguageModelCache(maxEntries: number, cleanupIntervalTime return languageModelInfo.languageModel; } let languageModel = parse(document); - languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now()}; + languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now() }; if (!languageModelInfo) { nModels++; } diff --git a/extensions/html/server/src/typings/promise.d.ts b/extensions/html/server/src/typings/promise.d.ts index 31b97cb9580a3..925c943df50a6 100644 --- a/extensions/html/server/src/typings/promise.d.ts +++ b/extensions/html/server/src/typings/promise.d.ts @@ -31,8 +31,8 @@ interface Thenable { * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ - then(onfulfilled?: (value: R) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Thenable; - then(onfulfilled?: (value: R) => TResult | Thenable, onrejected?: (reason: any) => void): Thenable; + then(onfulfilled?: (value: R) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Thenable; + then(onfulfilled?: (value: R) => TResult | Thenable, onrejected?: (reason: any) => void): Thenable; } /** @@ -45,15 +45,15 @@ interface Promise extends Thenable { * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ - then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Promise; - then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => void): Promise; + then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Promise; + then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => void): Promise; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ - catch(onrejected?: (reason: any) => T | Thenable): Promise; + catch(onrejected?: (reason: any) => T | Thenable): Promise; } interface PromiseConstructor { @@ -63,7 +63,7 @@ interface PromiseConstructor { * a resolve callback used resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ - new (executor: (resolve: (value?: T | Thenable) => void, reject: (reason?: any) => void) => void): Promise; + new (executor: (resolve: (value?: T | Thenable) => void, reject: (reason?: any) => void) => void): Promise; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises @@ -71,7 +71,7 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - all(values: Array>): Promise; + all(values: Array>): Promise; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved @@ -79,34 +79,34 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - race(values: Array>): Promise; + race(values: Array>): Promise; /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ - reject(reason: any): Promise; + reject(reason: any): Promise; /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ - reject(reason: any): Promise; + reject(reason: any): Promise; /** * Creates a new resolved promise for the provided value. * @param value A promise. * @returns A promise whose internal state matches the provided promise. */ - resolve(value: T | Thenable): Promise; + resolve(value: T | Thenable): Promise; /** * Creates a new resolved promise . * @returns A resolved promise. */ - resolve(): Promise; + resolve(): Promise; } declare var Promise: PromiseConstructor; diff --git a/extensions/javascript/src/features/bowerJSONContribution.ts b/extensions/javascript/src/features/bowerJSONContribution.ts index c2034433ce86f..42a26dbb69535 100644 --- a/extensions/javascript/src/features/bowerJSONContribution.ts +++ b/extensions/javascript/src/features/bowerJSONContribution.ts @@ -4,37 +4,37 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {MarkedString, CompletionItemKind, CompletionItem, DocumentSelector} from 'vscode'; -import {IJSONContribution, ISuggestionsCollector} from './jsonContributions'; -import {XHRRequest} from 'request-light'; -import {Location} from 'jsonc-parser'; -import {textToMarkedString} from './markedTextUtil'; +import { MarkedString, CompletionItemKind, CompletionItem, DocumentSelector } from 'vscode'; +import { IJSONContribution, ISuggestionsCollector } from './jsonContributions'; +import { XHRRequest } from 'request-light'; +import { Location } from 'jsonc-parser'; +import { textToMarkedString } from './markedTextUtil'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); export class BowerJSONContribution implements IJSONContribution { - private topRanked = ['twitter','bootstrap','angular-1.1.6','angular-latest','angulerjs','d3','myjquery','jq','abcdef1234567890','jQuery','jquery-1.11.1','jquery', - 'sushi-vanilla-x-data','font-awsome','Font-Awesome','font-awesome','fontawesome','html5-boilerplate','impress.js','homebrew', - 'backbone','moment1','momentjs','moment','linux','animate.css','animate-css','reveal.js','jquery-file-upload','blueimp-file-upload','threejs','express','chosen', - 'normalize-css','normalize.css','semantic','semantic-ui','Semantic-UI','modernizr','underscore','underscore1', - 'material-design-icons','ionic','chartjs','Chart.js','nnnick-chartjs','select2-ng','select2-dist','phantom','skrollr','scrollr','less.js','leancss','parser-lib', - 'hui','bootstrap-languages','async','gulp','jquery-pjax','coffeescript','hammer.js','ace','leaflet','jquery-mobile','sweetalert','typeahead.js','soup','typehead.js', - 'sails','codeigniter2']; + private topRanked = ['twitter', 'bootstrap', 'angular-1.1.6', 'angular-latest', 'angulerjs', 'd3', 'myjquery', 'jq', 'abcdef1234567890', 'jQuery', 'jquery-1.11.1', 'jquery', + 'sushi-vanilla-x-data', 'font-awsome', 'Font-Awesome', 'font-awesome', 'fontawesome', 'html5-boilerplate', 'impress.js', 'homebrew', + 'backbone', 'moment1', 'momentjs', 'moment', 'linux', 'animate.css', 'animate-css', 'reveal.js', 'jquery-file-upload', 'blueimp-file-upload', 'threejs', 'express', 'chosen', + 'normalize-css', 'normalize.css', 'semantic', 'semantic-ui', 'Semantic-UI', 'modernizr', 'underscore', 'underscore1', + 'material-design-icons', 'ionic', 'chartjs', 'Chart.js', 'nnnick-chartjs', 'select2-ng', 'select2-dist', 'phantom', 'skrollr', 'scrollr', 'less.js', 'leancss', 'parser-lib', + 'hui', 'bootstrap-languages', 'async', 'gulp', 'jquery-pjax', 'coffeescript', 'hammer.js', 'ace', 'leaflet', 'jquery-mobile', 'sweetalert', 'typeahead.js', 'soup', 'typehead.js', + 'sails', 'codeigniter2']; public constructor(private xhr: XHRRequest) { } public getDocumentSelector(): DocumentSelector { - return [{ language: 'json', pattern: '**/bower.json' }, { language: 'json', pattern: '**/.bower.json' }]; + return [{ language: 'json', pattern: '**/bower.json' }, { language: 'json', pattern: '**/.bower.json' }]; } public collectDefaultSuggestions(resource: string, collector: ISuggestionsCollector): Thenable { let defaultValue = { 'name': '{{name}}', 'description': '{{description}}', - 'authors': [ '{{author}}' ], + 'authors': ['{{author}}'], 'version': '{{1.0.0}}', 'main': '{{pathToMain}}', 'dependencies': {} @@ -46,19 +46,19 @@ export class BowerJSONContribution implements IJSONContribution { return Promise.resolve(null); } - public collectPropertySuggestions(resource: string, location: Location, currentWord: string, addValue: boolean, isLast:boolean, collector: ISuggestionsCollector) : Thenable { + public collectPropertySuggestions(resource: string, location: Location, currentWord: string, addValue: boolean, isLast: boolean, collector: ISuggestionsCollector): Thenable { if ((location.matches(['dependencies']) || location.matches(['devDependencies']))) { if (currentWord.length > 0) { let queryUrl = 'https://bower.herokuapp.com/packages/search/' + encodeURIComponent(currentWord); return this.xhr({ - url : queryUrl + url: queryUrl }).then((success) => { if (success.status === 200) { try { let obj = JSON.parse(success.responseText); if (Array.isArray(obj)) { - let results = <{name:string; description:string;}[]> obj; + let results = <{ name: string; description: string; }[]>obj; for (let i = 0; i < results.length; i++) { let name = results[i].name; let description = results[i].description || ''; @@ -126,7 +126,7 @@ export class BowerJSONContribution implements IJSONContribution { return Promise.resolve(null); } - public resolveSuggestion(item: CompletionItem) : Thenable { + public resolveSuggestion(item: CompletionItem): Thenable { if (item.kind === CompletionItemKind.Property && item.documentation === '') { return this.getInfo(item.label).then(documentation => { if (documentation) { @@ -143,12 +143,12 @@ export class BowerJSONContribution implements IJSONContribution { let queryUrl = 'https://bower.herokuapp.com/packages/' + encodeURIComponent(pack); return this.xhr({ - url : queryUrl + url: queryUrl }).then((success) => { try { let obj = JSON.parse(success.responseText); if (obj && obj.url) { - let url : string = obj.url; + let url: string = obj.url; if (url.indexOf('git://') === 0) { url = url.substring(6); } @@ -170,7 +170,7 @@ export class BowerJSONContribution implements IJSONContribution { if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']))) { let pack = location.path[location.path.length - 1]; if (typeof pack === 'string') { - let htmlContent : MarkedString[] = []; + let htmlContent: MarkedString[] = []; htmlContent.push(localize('json.bower.package.hover', '{0}', pack)); return this.getInfo(pack).then(documentation => { if (documentation) { diff --git a/extensions/javascript/src/features/jsonContributions.ts b/extensions/javascript/src/features/jsonContributions.ts index ffa70cbdc1768..e82f8b193e4e7 100644 --- a/extensions/javascript/src/features/jsonContributions.ts +++ b/extensions/javascript/src/features/jsonContributions.ts @@ -4,34 +4,36 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {Location, getLocation, createScanner, SyntaxKind, ScanError} from 'jsonc-parser'; -import {basename} from 'path'; -import {BowerJSONContribution} from './bowerJSONContribution'; -import {PackageJSONContribution} from './packageJSONContribution'; -import {XHRRequest} from 'request-light'; +import { Location, getLocation, createScanner, SyntaxKind, ScanError } from 'jsonc-parser'; +import { basename } from 'path'; +import { BowerJSONContribution } from './bowerJSONContribution'; +import { PackageJSONContribution } from './packageJSONContribution'; +import { XHRRequest } from 'request-light'; -import {CompletionItem, CompletionItemProvider, CompletionList, TextDocument, Position, Hover, HoverProvider, - CancellationToken, Range, TextEdit, MarkedString, DocumentSelector, languages, Disposable} from 'vscode'; +import { + CompletionItem, CompletionItemProvider, CompletionList, TextDocument, Position, Hover, HoverProvider, + CancellationToken, Range, TextEdit, MarkedString, DocumentSelector, languages, Disposable +} from 'vscode'; export interface ISuggestionsCollector { add(suggestion: CompletionItem): void; - error(message:string): void; - log(message:string): void; + error(message: string): void; + log(message: string): void; setAsIncomplete(): void; } export interface IJSONContribution { getDocumentSelector(): DocumentSelector; - getInfoContribution(fileName: string, location: Location) : Thenable; - collectPropertySuggestions(fileName: string, location: Location, currentWord: string, addValue: boolean, isLast:boolean, result: ISuggestionsCollector) : Thenable; + getInfoContribution(fileName: string, location: Location): Thenable; + collectPropertySuggestions(fileName: string, location: Location, currentWord: string, addValue: boolean, isLast: boolean, result: ISuggestionsCollector): Thenable; collectValueSuggestions(fileName: string, location: Location, result: ISuggestionsCollector): Thenable; collectDefaultSuggestions(fileName: string, result: ISuggestionsCollector): Thenable; resolveSuggestion?(item: CompletionItem): Thenable; } -export function addJSONProviders(xhr: XHRRequest) : Disposable { +export function addJSONProviders(xhr: XHRRequest): Disposable { let contributions = [new PackageJSONContribution(xhr), new BowerJSONContribution(xhr)]; - let subscriptions : Disposable[] = []; + let subscriptions: Disposable[] = []; contributions.forEach(contribution => { let selector = contribution.getDocumentSelector(); subscriptions.push(languages.registerCompletionItemProvider(selector, new JSONCompletionItemProvider(contribution), '.', '$')); @@ -72,7 +74,7 @@ export class JSONCompletionItemProvider implements CompletionItemProvider { constructor(private jsonContribution: IJSONContribution) { } - public resolveCompletionItem(item: CompletionItem, token: CancellationToken) : Thenable { + public resolveCompletionItem(item: CompletionItem, token: CancellationToken): Thenable { if (this.jsonContribution.resolveSuggestion) { let resolver = this.jsonContribution.resolveSuggestion(item); if (resolver) { @@ -87,7 +89,7 @@ export class JSONCompletionItemProvider implements CompletionItemProvider { let fileName = basename(document.fileName); let currentWord = this.getCurrentWord(document, position); - let overwriteRange : Range; + let overwriteRange: Range; let items: CompletionItem[] = []; let isIncomplete = false; @@ -116,7 +118,7 @@ export class JSONCompletionItemProvider implements CompletionItemProvider { log: (message: string) => console.log(message) }; - let collectPromise : Thenable = null; + let collectPromise: Thenable = null; if (location.isAtPropertyKey) { let addValue = !location.previousNode || !location.previousNode.columnOffset; @@ -146,15 +148,15 @@ export class JSONCompletionItemProvider implements CompletionItemProvider { while (i >= 0 && ' \t\n\r\v":{[,'.indexOf(text.charAt(i)) === -1) { i--; } - return text.substring(i+1, position.character); + return text.substring(i + 1, position.character); } - private isLast(document: TextDocument, position: Position):boolean { + private isLast(document: TextDocument, position: Position): boolean { let scanner = createScanner(document.getText(), true); scanner.setPosition(document.offsetAt(position)); let nextToken = scanner.scan(); if (nextToken === SyntaxKind.StringLiteral && scanner.getTokenError() === ScanError.UnexpectedEndOfString) { - nextToken= scanner.scan(); + nextToken = scanner.scan(); } return nextToken === SyntaxKind.CloseBraceToken || nextToken === SyntaxKind.EOF; } diff --git a/extensions/javascript/src/features/markedTextUtil.ts b/extensions/javascript/src/features/markedTextUtil.ts index 97f3198b80cd9..b4a9aaaf3e9ac 100644 --- a/extensions/javascript/src/features/markedTextUtil.ts +++ b/extensions/javascript/src/features/markedTextUtil.ts @@ -4,8 +4,8 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {MarkedString} from 'vscode'; +import { MarkedString } from 'vscode'; -export function textToMarkedString(text: string) : MarkedString { +export function textToMarkedString(text: string): MarkedString { return text.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash } \ No newline at end of file diff --git a/extensions/javascript/src/features/packageJSONContribution.ts b/extensions/javascript/src/features/packageJSONContribution.ts index e7107bef81199..6c8a54f261d6e 100644 --- a/extensions/javascript/src/features/packageJSONContribution.ts +++ b/extensions/javascript/src/features/packageJSONContribution.ts @@ -4,11 +4,11 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {MarkedString, CompletionItemKind, CompletionItem, DocumentSelector} from 'vscode'; -import {IJSONContribution, ISuggestionsCollector} from './jsonContributions'; -import {XHRRequest} from 'request-light'; -import {Location} from 'jsonc-parser'; -import {textToMarkedString} from './markedTextUtil'; +import { MarkedString, CompletionItemKind, CompletionItem, DocumentSelector } from 'vscode'; +import { IJSONContribution, ISuggestionsCollector } from './jsonContributions'; +import { XHRRequest } from 'request-light'; +import { Location } from 'jsonc-parser'; +import { textToMarkedString } from './markedTextUtil'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); @@ -17,7 +17,7 @@ let LIMIT = 40; export class PackageJSONContribution implements IJSONContribution { - private mostDependedOn = [ 'lodash', 'async', 'underscore', 'request', 'commander', 'express', 'debug', 'chalk', 'colors', 'q', 'coffee-script', + private mostDependedOn = ['lodash', 'async', 'underscore', 'request', 'commander', 'express', 'debug', 'chalk', 'colors', 'q', 'coffee-script', 'mkdirp', 'optimist', 'through2', 'yeoman-generator', 'moment', 'bluebird', 'glob', 'gulp-util', 'minimist', 'cheerio', 'jade', 'redis', 'node-uuid', 'socket', 'io', 'uglify-js', 'winston', 'through', 'fs-extra', 'handlebars', 'body-parser', 'rimraf', 'mime', 'semver', 'mongodb', 'jquery', 'grunt', 'connect', 'yosay', 'underscore', 'string', 'xml2js', 'ejs', 'mongoose', 'marked', 'extend', 'mocha', 'superagent', 'js-yaml', 'xtend', @@ -25,7 +25,7 @@ export class PackageJSONContribution implements IJSONContribution { 'jsdom', 'stylus', 'when', 'readable-stream', 'aws-sdk', 'concat-stream', 'chai', 'Thenable', 'wrench']; public getDocumentSelector(): DocumentSelector { - return [{ language: 'json', pattern: '**/package.json' }]; + return [{ language: 'json', pattern: '**/package.json' }]; } public constructor(private xhr: XHRRequest) { @@ -47,20 +47,20 @@ export class PackageJSONContribution implements IJSONContribution { return Promise.resolve(null); } - public collectPropertySuggestions(resource: string, location: Location, currentWord: string, addValue: boolean, isLast:boolean, collector: ISuggestionsCollector) : Thenable { + public collectPropertySuggestions(resource: string, location: Location, currentWord: string, addValue: boolean, isLast: boolean, collector: ISuggestionsCollector): Thenable { if ((location.matches(['dependencies']) || location.matches(['devDependencies']) || location.matches(['optionalDependencies']) || location.matches(['peerDependencies']))) { - let queryUrl : string; + let queryUrl: string; if (currentWord.length > 0) { - queryUrl = 'https://skimdb.npmjs.com/registry/_design/app/_view/browseAll?group_level=1&limit=' + LIMIT + '&start_key=%5B%22' + encodeURIComponent(currentWord) + '%22%5D&end_key=%5B%22'+ encodeURIComponent(currentWord + 'z') + '%22,%7B%7D%5D'; + queryUrl = 'https://skimdb.npmjs.com/registry/_design/app/_view/browseAll?group_level=1&limit=' + LIMIT + '&start_key=%5B%22' + encodeURIComponent(currentWord) + '%22%5D&end_key=%5B%22' + encodeURIComponent(currentWord + 'z') + '%22,%7B%7D%5D'; return this.xhr({ - url : queryUrl + url: queryUrl }).then((success) => { if (success.status === 200) { try { let obj = JSON.parse(success.responseText); if (obj && Array.isArray(obj.rows)) { - let results = <{ key: string[]; }[]> obj.rows; + let results = <{ key: string[]; }[]>obj.rows; for (let i = 0; i < results.length; i++) { let keys = results[i].key; if (Array.isArray(keys) && keys.length > 0) { @@ -124,7 +124,7 @@ export class PackageJSONContribution implements IJSONContribution { if (typeof currentKey === 'string') { let queryUrl = 'http://registry.npmjs.org/' + encodeURIComponent(currentKey).replace('%40', '@'); return this.xhr({ - url : queryUrl + url: queryUrl }).then((success) => { try { let obj = JSON.parse(success.responseText); @@ -163,7 +163,7 @@ export class PackageJSONContribution implements IJSONContribution { return null; } - public resolveSuggestion(item: CompletionItem) : Thenable { + public resolveSuggestion(item: CompletionItem): Thenable { if (item.kind === CompletionItemKind.Property && item.documentation === '') { return this.getInfo(item.label).then(infos => { if (infos.length > 0) { @@ -183,12 +183,12 @@ export class PackageJSONContribution implements IJSONContribution { let queryUrl = 'http://registry.npmjs.org/' + encodeURIComponent(pack).replace('%40', '@'); return this.xhr({ - url : queryUrl + url: queryUrl }).then((success) => { try { let obj = JSON.parse(success.responseText); if (obj) { - let result : string[] = []; + let result: string[] = []; if (obj.description) { result.push(obj.description); } @@ -211,7 +211,7 @@ export class PackageJSONContribution implements IJSONContribution { if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']) || location.matches(['optionalDependencies', '*']) || location.matches(['peerDependencies', '*']))) { let pack = location.path[location.path.length - 1]; if (typeof pack === 'string') { - let htmlContent : MarkedString[] = []; + let htmlContent: MarkedString[] = []; htmlContent.push(localize('json.npm.package.hover', '{0}', pack)); return this.getInfo(pack).then(infos => { infos.forEach(info => { diff --git a/extensions/javascript/src/javascriptMain.ts b/extensions/javascript/src/javascriptMain.ts index e386e14e4ed33..92dc3e82b70e0 100644 --- a/extensions/javascript/src/javascriptMain.ts +++ b/extensions/javascript/src/javascriptMain.ts @@ -5,15 +5,15 @@ 'use strict'; -import {addJSONProviders} from './features/jsonContributions'; +import { addJSONProviders } from './features/jsonContributions'; import * as httpRequest from 'request-light'; -import {ExtensionContext, env, workspace} from 'vscode'; +import { ExtensionContext, env, workspace } from 'vscode'; import * as nls from 'vscode-nls'; export function activate(context: ExtensionContext): any { - nls.config({locale: env.language}); + nls.config({ locale: env.language }); configureHttpRequest(); workspace.onDidChangeConfiguration(e => configureHttpRequest()); diff --git a/extensions/json/client/src/jsonMain.ts b/extensions/json/client/src/jsonMain.ts index 2b86fc57dd60d..10ef18a39dc16 100644 --- a/extensions/json/client/src/jsonMain.ts +++ b/extensions/json/client/src/jsonMain.ts @@ -6,8 +6,8 @@ import * as path from 'path'; -import {workspace, languages, ExtensionContext, extensions, Uri} from 'vscode'; -import {LanguageClient, LanguageClientOptions, RequestType, ServerOptions, TransportKind, NotificationType} from 'vscode-languageclient'; +import { workspace, languages, ExtensionContext, extensions, Uri } from 'vscode'; +import { LanguageClient, LanguageClientOptions, RequestType, ServerOptions, TransportKind, NotificationType } from 'vscode-languageclient'; import TelemetryReporter from 'vscode-extension-telemetry'; import * as nls from 'vscode-nls'; @@ -97,8 +97,8 @@ export function activate(context: ExtensionContext) { }); } -function getSchemaAssociation(context: ExtensionContext) : ISchemaAssociations { - let associations : ISchemaAssociations = {}; +function getSchemaAssociation(context: ExtensionContext): ISchemaAssociations { + let associations: ISchemaAssociations = {}; extensions.all.forEach(extension => { let packageJSON = extension.packageJSON; if (packageJSON && packageJSON.contributes && packageJSON.contributes.jsonValidation) { diff --git a/extensions/json/client/src/typings/vscode-extension-telemetry.d.ts b/extensions/json/client/src/typings/vscode-extension-telemetry.d.ts index 4b2981b9b24be..f6177ef27a652 100644 --- a/extensions/json/client/src/typings/vscode-extension-telemetry.d.ts +++ b/extensions/json/client/src/typings/vscode-extension-telemetry.d.ts @@ -1,6 +1,6 @@ declare module 'vscode-extension-telemetry' { export default class TelemetryReporter { - constructor(extensionId: string,extensionVersion: string, key: string); + constructor(extensionId: string, extensionVersion: string, key: string); sendTelemetryEvent(eventName: string, properties?: { [key: string]: string }, measures?: { [key: string]: number }): void; } } \ No newline at end of file diff --git a/extensions/json/server/src/jsonServerMain.ts b/extensions/json/server/src/jsonServerMain.ts index 3340ba905f4f7..93f510d8770ff 100644 --- a/extensions/json/server/src/jsonServerMain.ts +++ b/extensions/json/server/src/jsonServerMain.ts @@ -9,17 +9,17 @@ import { TextDocuments, TextDocument, InitializeParams, InitializeResult, NotificationType, RequestType } from 'vscode-languageserver'; -import {xhr, XHRResponse, configure as configureHttpRequests, getErrorStatusDescription} from 'request-light'; +import { xhr, XHRResponse, configure as configureHttpRequests, getErrorStatusDescription } from 'request-light'; import path = require('path'); import fs = require('fs'); import URI from './utils/uri'; import * as URL from 'url'; import Strings = require('./utils/strings'); -import {JSONDocument, JSONSchema, LanguageSettings, getLanguageService} from 'vscode-json-languageservice'; -import {ProjectJSONContribution} from './jsoncontributions/projectJSONContribution'; -import {GlobPatternContribution} from './jsoncontributions/globPatternContribution'; -import {FileAssociationContribution} from './jsoncontributions/fileAssociationContribution'; -import {getLanguageModelCache} from './languageModelCache'; +import { JSONDocument, JSONSchema, LanguageSettings, getLanguageService } from 'vscode-json-languageservice'; +import { ProjectJSONContribution } from './jsoncontributions/projectJSONContribution'; +import { GlobPatternContribution } from './jsoncontributions/globPatternContribution'; +import { FileAssociationContribution } from './jsoncontributions/fileAssociationContribution'; +import { getLanguageModelCache } from './languageModelCache'; import * as nls from 'vscode-nls'; nls.config(process.env['VSCODE_NLS_CONFIG']); @@ -76,7 +76,7 @@ let workspaceContext = { } }; -let schemaRequestService = (uri:string): Thenable => { +let schemaRequestService = (uri: string): Thenable => { if (Strings.startsWith(uri, 'file://')) { let fsPath = URI.parse(uri).fsPath; return new Promise((c, e) => { @@ -153,7 +153,7 @@ connection.onNotification(SchemaAssociationNotification.type, associations => { }); function updateConfiguration() { - let languageSettings : LanguageSettings = { + let languageSettings: LanguageSettings = { validate: true, allowComments: true, schemas: [] @@ -204,7 +204,7 @@ documents.onDidClose(event => { connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] }); }); -let pendingValidationRequests : { [uri: string]: NodeJS.Timer; } = {}; +let pendingValidationRequests: { [uri: string]: NodeJS.Timer; } = {}; const validationDelayMs = 200; function cleanPendingValidation(textDocument: TextDocument): void { diff --git a/extensions/json/server/src/jsoncontributions/fileAssociationContribution.ts b/extensions/json/server/src/jsoncontributions/fileAssociationContribution.ts index 0b9b2b57537e3..3d5a6e669fb10 100644 --- a/extensions/json/server/src/jsoncontributions/fileAssociationContribution.ts +++ b/extensions/json/server/src/jsoncontributions/fileAssociationContribution.ts @@ -4,9 +4,9 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {MarkedString, CompletionItemKind, CompletionItem} from 'vscode-languageserver'; +import { MarkedString, CompletionItemKind, CompletionItem } from 'vscode-languageserver'; import Strings = require('../utils/strings'); -import {JSONWorkerContribution, JSONPath, CompletionsCollector} from 'vscode-json-languageservice'; +import { JSONWorkerContribution, JSONPath, CompletionsCollector } from 'vscode-json-languageservice'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); @@ -17,12 +17,12 @@ let globProperties: CompletionItem[] = [ ]; export class FileAssociationContribution implements JSONWorkerContribution { - private languageIds:string[]; + private languageIds: string[]; constructor() { } - public setLanguageIds(ids:string[]): void { + public setLanguageIds(ids: string[]): void { this.languageIds = ids; } diff --git a/extensions/json/server/src/jsoncontributions/globPatternContribution.ts b/extensions/json/server/src/jsoncontributions/globPatternContribution.ts index d2a3b873eec12..bb3eb6bd8027d 100644 --- a/extensions/json/server/src/jsoncontributions/globPatternContribution.ts +++ b/extensions/json/server/src/jsoncontributions/globPatternContribution.ts @@ -4,9 +4,9 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {MarkedString, CompletionItemKind, CompletionItem} from 'vscode-languageserver'; +import { MarkedString, CompletionItemKind, CompletionItem } from 'vscode-languageserver'; import Strings = require('../utils/strings'); -import {JSONWorkerContribution, JSONPath, CompletionsCollector} from 'vscode-json-languageservice'; +import { JSONWorkerContribution, JSONPath, CompletionsCollector } from 'vscode-json-languageservice'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); diff --git a/extensions/json/server/src/jsoncontributions/projectJSONContribution.ts b/extensions/json/server/src/jsoncontributions/projectJSONContribution.ts index 6a458db385c8c..7fa207b3627fc 100644 --- a/extensions/json/server/src/jsoncontributions/projectJSONContribution.ts +++ b/extensions/json/server/src/jsoncontributions/projectJSONContribution.ts @@ -4,11 +4,11 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {MarkedString, CompletionItemKind, CompletionItem} from 'vscode-languageserver'; +import { MarkedString, CompletionItemKind, CompletionItem } from 'vscode-languageserver'; import Strings = require('../utils/strings'); -import {XHRResponse, getErrorStatusDescription} from 'request-light'; -import {JSONWorkerContribution, JSONPath, CompletionsCollector} from 'vscode-json-languageservice'; -import {xhr} from 'request-light'; +import { XHRResponse, getErrorStatusDescription } from 'request-light'; +import { JSONWorkerContribution, JSONPath, CompletionsCollector } from 'vscode-json-languageservice'; +import { xhr } from 'request-light'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); @@ -29,7 +29,7 @@ interface NugetServices { export class ProjectJSONContribution implements JSONWorkerContribution { - private cachedProjects: { [id: string]: { version: string, description: string, time: number }} = {}; + private cachedProjects: { [id: string]: { version: string, description: string, time: number } } = {}; private cacheSize: number = 0; private nugetIndexPromise: Thenable; @@ -40,7 +40,7 @@ export class ProjectJSONContribution implements JSONWorkerContribution { return Strings.endsWith(resource, '/project.json'); } - private completeWithCache(id: string, item: CompletionItem) : boolean { + private completeWithCache(id: string, item: CompletionItem): boolean { let entry = this.cachedProjects[id]; if (entry) { if (new Date().getTime() - entry.time > CACHE_EXPIRY) { @@ -57,10 +57,10 @@ export class ProjectJSONContribution implements JSONWorkerContribution { } private addCached(id: string, version: string, description: string) { - this.cachedProjects[id] = { version, description, time: new Date().getTime()}; + this.cachedProjects[id] = { version, description, time: new Date().getTime() }; this.cacheSize++; if (this.cacheSize > 50) { - let currentTime = new Date().getTime() ; + let currentTime = new Date().getTime(); for (let id in this.cachedProjects) { let entry = this.cachedProjects[id]; if (currentTime - entry.time > CACHE_EXPIRY) { @@ -71,12 +71,12 @@ export class ProjectJSONContribution implements JSONWorkerContribution { } } - private getNugetIndex() : Thenable { + private getNugetIndex(): Thenable { if (!this.nugetIndexPromise) { this.nugetIndexPromise = this.makeJSONRequest(FEED_INDEX_URL).then(indexContent => { - let services : NugetServices = {}; + let services: NugetServices = {}; if (indexContent && Array.isArray(indexContent.resources)) { - let resources = indexContent.resources; + let resources = indexContent.resources; for (let i = resources.length - 1; i >= 0; i--) { let type = resources[i]['@type']; let id = resources[i]['@id']; @@ -91,7 +91,7 @@ export class ProjectJSONContribution implements JSONWorkerContribution { return this.nugetIndexPromise; } - private getNugetService(serviceType: string) : Thenable { + private getNugetService(serviceType: string): Thenable { return this.getNugetIndex().then(services => { let serviceURL = services[serviceType]; if (!serviceURL) { @@ -116,13 +116,13 @@ export class ProjectJSONContribution implements JSONWorkerContribution { return null; } - private makeJSONRequest(url: string) : Thenable { + private makeJSONRequest(url: string): Thenable { return xhr({ - url : url + url: url }).then(success => { if (success.status === 200) { try { - return JSON.parse(success.responseText); + return JSON.parse(success.responseText); } catch (e) { return Promise.reject(localize('json.nugget.error.invalidformat', '{0} is not a valid JSON document', url)); } @@ -133,19 +133,19 @@ export class ProjectJSONContribution implements JSONWorkerContribution { }); } - public collectPropertyCompletions(resource: string, location: JSONPath, currentWord: string, addValue: boolean, isLast:boolean, result: CompletionsCollector) : Thenable { + public collectPropertyCompletions(resource: string, location: JSONPath, currentWord: string, addValue: boolean, isLast: boolean, result: CompletionsCollector): Thenable { if (this.isProjectJSONFile(resource) && (matches(location, ['dependencies']) || matches(location, ['frameworks', '*', 'dependencies']) || matches(location, ['frameworks', '*', 'frameworkAssemblies']))) { return this.getNugetService('SearchAutocompleteService').then(service => { - let queryUrl : string; + let queryUrl: string; if (currentWord.length > 0) { - queryUrl = service + '?q=' + encodeURIComponent(currentWord) +'&take=' + LIMIT; + queryUrl = service + '?q=' + encodeURIComponent(currentWord) + '&take=' + LIMIT; } else { queryUrl = service + '?take=' + LIMIT; } return this.makeJSONRequest(queryUrl).then(resultObj => { if (Array.isArray(resultObj.data)) { - let results = resultObj.data; + let results = resultObj.data; for (let i = 0; i < results.length; i++) { let name = results[i]; let insertText = JSON.stringify(name); @@ -155,7 +155,7 @@ export class ProjectJSONContribution implements JSONWorkerContribution { insertText += ','; } } - let item : CompletionItem = { kind: CompletionItemKind.Property, label: name, insertText: insertText, filterText: JSON.stringify(name)}; + let item: CompletionItem = { kind: CompletionItemKind.Property, label: name, insertText: insertText, filterText: JSON.stringify(name) }; if (!this.completeWithCache(name, item)) { item.data = RESOLVE_ID + name; } @@ -181,7 +181,7 @@ export class ProjectJSONContribution implements JSONWorkerContribution { let queryUrl = service + currentKey + '/index.json'; return this.makeJSONRequest(queryUrl).then(obj => { if (Array.isArray(obj.versions)) { - let results = obj.versions; + let results = obj.versions; for (let i = 0; i < results.length; i++) { let curr = results[i]; let name = JSON.stringify(curr); @@ -205,15 +205,15 @@ export class ProjectJSONContribution implements JSONWorkerContribution { public getInfoContribution(resource: string, location: JSONPath): Thenable { if (this.isProjectJSONFile(resource) && (matches(location, ['dependencies', '*']) || matches(location, ['frameworks', '*', 'dependencies', '*']) || matches(location, ['frameworks', '*', 'frameworkAssemblies', '*']))) { - let pack = location[location.length - 1]; + let pack = location[location.length - 1]; return this.getNugetService('SearchQueryService').then(service => { - let queryUrl = service + '?q=' + encodeURIComponent(pack) +'&take=' + 5; + let queryUrl = service + '?q=' + encodeURIComponent(pack) + '&take=' + 5; return this.makeJSONRequest(queryUrl).then(resultObj => { - let htmlContent : MarkedString[] = []; + let htmlContent: MarkedString[] = []; htmlContent.push(localize('json.nugget.package.hover', '{0}', pack)); if (Array.isArray(resultObj.data)) { - let results = resultObj.data; + let results = resultObj.data; for (let i = 0; i < results.length; i++) { let res = results[i]; this.addCached(res.id, res.version, res.description); @@ -233,24 +233,24 @@ export class ProjectJSONContribution implements JSONWorkerContribution { return null; }); }, (error) => { - return null; + return null; }); } return null; } - public resolveSuggestion(item: CompletionItem) : Thenable { + public resolveSuggestion(item: CompletionItem): Thenable { if (item.data && Strings.startsWith(item.data, RESOLVE_ID)) { let pack = item.data.substring(RESOLVE_ID.length); if (this.completeWithCache(pack, item)) { return Promise.resolve(item); } return this.getNugetService('SearchQueryService').then(service => { - let queryUrl = service + '?q=' + encodeURIComponent(pack) +'&take=' + 10; + let queryUrl = service + '?q=' + encodeURIComponent(pack) + '&take=' + 10; return this.makeJSONRequest(queryUrl).then(resultObj => { let itemResolved = false; if (Array.isArray(resultObj.data)) { - let results = resultObj.data; + let results = resultObj.data; for (let i = 0; i < results.length; i++) { let curr = results[i]; this.addCached(curr.id, curr.version, curr.description); diff --git a/extensions/json/server/src/languageModelCache.ts b/extensions/json/server/src/languageModelCache.ts index dce68bed9a32c..b12f77b52a61d 100644 --- a/extensions/json/server/src/languageModelCache.ts +++ b/extensions/json/server/src/languageModelCache.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {TextDocument} from 'vscode-languageserver'; +import { TextDocument } from 'vscode-languageserver'; export interface LanguageModelCache { get(document: TextDocument): T; @@ -12,8 +12,8 @@ export interface LanguageModelCache { dispose(): void; } -export function getLanguageModelCache(maxEntries: number, cleanupIntervalTimeInSec: number, parse: (document: TextDocument) => T) : LanguageModelCache { - let languageModels: { [uri:string]: {version:number, languageId: string, cTime: number, languageModel: T}} = {}; +export function getLanguageModelCache(maxEntries: number, cleanupIntervalTimeInSec: number, parse: (document: TextDocument) => T): LanguageModelCache { + let languageModels: { [uri: string]: { version: number, languageId: string, cTime: number, languageModel: T } } = {}; let nModels = 0; let cleanupInterval = void 0; @@ -32,7 +32,7 @@ export function getLanguageModelCache(maxEntries: number, cleanupIntervalTime } return { - get(document: TextDocument) : T { + get(document: TextDocument): T { let version = document.version; let languageId = document.languageId; let languageModelInfo = languageModels[document.uri]; @@ -41,7 +41,7 @@ export function getLanguageModelCache(maxEntries: number, cleanupIntervalTime return languageModelInfo.languageModel; } let languageModel = parse(document); - languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now()}; + languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now() }; if (!languageModelInfo) { nModels++; } diff --git a/extensions/json/server/src/typings/promise.d.ts b/extensions/json/server/src/typings/promise.d.ts index 31b97cb9580a3..925c943df50a6 100644 --- a/extensions/json/server/src/typings/promise.d.ts +++ b/extensions/json/server/src/typings/promise.d.ts @@ -31,8 +31,8 @@ interface Thenable { * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ - then(onfulfilled?: (value: R) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Thenable; - then(onfulfilled?: (value: R) => TResult | Thenable, onrejected?: (reason: any) => void): Thenable; + then(onfulfilled?: (value: R) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Thenable; + then(onfulfilled?: (value: R) => TResult | Thenable, onrejected?: (reason: any) => void): Thenable; } /** @@ -45,15 +45,15 @@ interface Promise extends Thenable { * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ - then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Promise; - then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => void): Promise; + then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => TResult | Thenable): Promise; + then(onfulfilled?: (value: T) => TResult | Thenable, onrejected?: (reason: any) => void): Promise; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ - catch(onrejected?: (reason: any) => T | Thenable): Promise; + catch(onrejected?: (reason: any) => T | Thenable): Promise; } interface PromiseConstructor { @@ -63,7 +63,7 @@ interface PromiseConstructor { * a resolve callback used resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ - new (executor: (resolve: (value?: T | Thenable) => void, reject: (reason?: any) => void) => void): Promise; + new (executor: (resolve: (value?: T | Thenable) => void, reject: (reason?: any) => void) => void): Promise; /** * Creates a Promise that is resolved with an array of results when all of the provided Promises @@ -71,7 +71,7 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - all(values: Array>): Promise; + all(values: Array>): Promise; /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved @@ -79,34 +79,34 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - race(values: Array>): Promise; + race(values: Array>): Promise; /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ - reject(reason: any): Promise; + reject(reason: any): Promise; /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ - reject(reason: any): Promise; + reject(reason: any): Promise; /** * Creates a new resolved promise for the provided value. * @param value A promise. * @returns A promise whose internal state matches the provided promise. */ - resolve(value: T | Thenable): Promise; + resolve(value: T | Thenable): Promise; /** * Creates a new resolved promise . * @returns A resolved promise. */ - resolve(): Promise; + resolve(): Promise; } declare var Promise: PromiseConstructor; diff --git a/extensions/json/server/src/utils/uri.ts b/extensions/json/server/src/utils/uri.ts index a6efdd739f780..9394a87681c85 100644 --- a/extensions/json/server/src/utils/uri.ts +++ b/extensions/json/server/src/utils/uri.ts @@ -302,7 +302,7 @@ export default class URI { // when occurring in paths - otherwise the result // cannot be parsed back again let lastIdx = 0; - while(true) { + while (true) { let idx = path.indexOf(URI._slash, lastIdx); if (idx === -1) { parts.push(encoder(path.substring(lastIdx)).replace(/[#?]/, _encode)); @@ -323,7 +323,7 @@ export default class URI { } public toJSON(): any { - return { + return { scheme: this.scheme, authority: this.authority, path: this.path, diff --git a/extensions/markdown/src/extension.ts b/extensions/markdown/src/extension.ts index 37c788fa4e2a2..79136041ea11c 100644 --- a/extensions/markdown/src/extension.ts +++ b/extensions/markdown/src/extension.ts @@ -92,8 +92,8 @@ function showPreview(uri?: Uri, sideBySide: boolean = false) { `Preview '${path.basename(resource.fsPath)}'`); telemetryReporter.sendTelemetryEvent('openPreview', { - where : sideBySide ? 'sideBySide' : 'inPlace', - how : (uri instanceof Uri) ? 'action' : 'pallete' + where: sideBySide ? 'sideBySide' : 'inPlace', + how: (uri instanceof Uri) ? 'action' : 'pallete' }); return thenable; @@ -151,14 +151,14 @@ function getPackageInfo(context: ExtensionContext): IPackageInfo { interface IRenderer { - render(text: string) : string; + render(text: string): string; } class MDDocumentContentProvider implements TextDocumentContentProvider { private _context: ExtensionContext; private _onDidChange = new EventEmitter(); - private _waiting : boolean; - private _renderer : IRenderer; + private _waiting: boolean; + private _renderer: IRenderer; constructor(context: ExtensionContext) { this._context = context; @@ -166,7 +166,7 @@ class MDDocumentContentProvider implements TextDocumentContentProvider { this._renderer = this.createRenderer(); } - private createRenderer() : IRenderer { + private createRenderer(): IRenderer { const hljs = require('highlight.js'); const mdnh = require('markdown-it-named-headers'); const md = require('markdown-it')({ @@ -183,15 +183,15 @@ class MDDocumentContentProvider implements TextDocumentContentProvider { return md; } - private getMediaPath(mediaFile) : string { + private getMediaPath(mediaFile): string { return this._context.asAbsolutePath(path.join('media', mediaFile)); } - private isAbsolute(p) : boolean { + private isAbsolute(p): boolean { return path.normalize(p + '/') === path.normalize(path.resolve(p) + '/'); } - private fixHref(resource: Uri, href: string) : string { + private fixHref(resource: Uri, href: string): string { if (href) { // Use href if it is already an URL if (Uri.parse(href).scheme) { diff --git a/extensions/markdown/src/typings/vscode-extension-telemetry.d.ts b/extensions/markdown/src/typings/vscode-extension-telemetry.d.ts index 4b2981b9b24be..f6177ef27a652 100644 --- a/extensions/markdown/src/typings/vscode-extension-telemetry.d.ts +++ b/extensions/markdown/src/typings/vscode-extension-telemetry.d.ts @@ -1,6 +1,6 @@ declare module 'vscode-extension-telemetry' { export default class TelemetryReporter { - constructor(extensionId: string,extensionVersion: string, key: string); + constructor(extensionId: string, extensionVersion: string, key: string); sendTelemetryEvent(eventName: string, properties?: { [key: string]: string }, measures?: { [key: string]: number }): void; } } \ No newline at end of file diff --git a/extensions/php/src/features/completionItemProvider.ts b/extensions/php/src/features/completionItemProvider.ts index 7977b274aee9a..94bd75e4e5cbb 100644 --- a/extensions/php/src/features/completionItemProvider.ts +++ b/extensions/php/src/features/completionItemProvider.ts @@ -5,7 +5,7 @@ 'use strict'; -import {CompletionItemProvider, CompletionItem, CompletionItemKind, CancellationToken, TextDocument, Position, Range, TextEdit} from 'vscode'; +import { CompletionItemProvider, CompletionItem, CompletionItemKind, CancellationToken, TextDocument, Position, Range, TextEdit } from 'vscode'; import phpGlobals = require('./phpGlobals'); export default class PHPCompletionItemProvider implements CompletionItemProvider { @@ -14,19 +14,19 @@ export default class PHPCompletionItemProvider implements CompletionItemProvider public provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken): Promise { let result: CompletionItem[] = []; - var range = document.getWordRangeAtPosition(position); + var range = document.getWordRangeAtPosition(position); var prefix = range ? document.getText(range) : ''; if (!range) { range = new Range(position, position); } - - var added : any = {}; - var createNewProposal = function(kind: CompletionItemKind, name: string, entry: phpGlobals.IEntry) : CompletionItem { - var proposal : CompletionItem = new CompletionItem(name); + + var added: any = {}; + var createNewProposal = function (kind: CompletionItemKind, name: string, entry: phpGlobals.IEntry): CompletionItem { + var proposal: CompletionItem = new CompletionItem(name); proposal.kind = kind; if (entry) { if (entry.description) { - proposal.documentation= entry.description; + proposal.documentation = entry.description; } if (entry.signature) { proposal.detail = entry.signature; @@ -35,14 +35,14 @@ export default class PHPCompletionItemProvider implements CompletionItemProvider return proposal; }; - var matches = (name:string) => { + var matches = (name: string) => { return prefix.length === 0 || name.length >= prefix.length && name.substr(0, prefix.length) === prefix; }; - + if (matches('php') && range.start.character >= 2) { let twoBeforePosition = new Position(range.start.line, range.start.character - 2); let beforeWord = document.getText(new Range(twoBeforePosition, range.start)); - + if (beforeWord === '= 0; } - public next() : number { + public next(): number { if (this.offset < 0) { if (this.lineNumber > 0) { this.lineNumber--; @@ -92,7 +92,7 @@ export default class PHPSignatureHelpProvider implements SignatureHelpProvider { var re = /\w*\s+\&?\$[\w_\.]+|void/g; var match: RegExpExecArray = null; while ((match = re.exec(paramsString)) !== null) { - signatureInfo.parameters.push({ label: match[0], documentation: ''}); + signatureInfo.parameters.push({ label: match[0], documentation: '' }); } let ret = new SignatureHelp(); ret.signatures.push(signatureInfo); @@ -101,7 +101,7 @@ export default class PHPSignatureHelpProvider implements SignatureHelpProvider { return Promise.resolve(ret); } - private readArguments(iterator: BackwardIterator) : number { + private readArguments(iterator: BackwardIterator): number { var parentNesting = 0; var bracketNesting = 0; var curlyNesting = 0; @@ -136,8 +136,8 @@ export default class PHPSignatureHelpProvider implements SignatureHelpProvider { return -1; } - private isIdentPart(ch:number) : boolean { - if(ch === _USC || // _ + private isIdentPart(ch: number): boolean { + if (ch === _USC || // _ ch >= _a && ch <= _z || // a-z ch >= _A && ch <= _Z || // A-Z ch >= _0 && ch <= _9 || // 0/9 @@ -148,7 +148,7 @@ export default class PHPSignatureHelpProvider implements SignatureHelpProvider { return false; } - private readIdent(iterator: BackwardIterator) : string { + private readIdent(iterator: BackwardIterator): string { var identStarted = false; var ident = ''; while (iterator.hasNext()) { @@ -158,7 +158,7 @@ export default class PHPSignatureHelpProvider implements SignatureHelpProvider { } if (this.isIdentPart(ch)) { identStarted = true; - ident= String.fromCharCode(ch) + ident; + ident = String.fromCharCode(ch) + ident; } else if (identStarted) { return ident; } diff --git a/extensions/php/src/features/utils/markedTextUtil.ts b/extensions/php/src/features/utils/markedTextUtil.ts index 97f3198b80cd9..b4a9aaaf3e9ac 100644 --- a/extensions/php/src/features/utils/markedTextUtil.ts +++ b/extensions/php/src/features/utils/markedTextUtil.ts @@ -4,8 +4,8 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {MarkedString} from 'vscode'; +import { MarkedString } from 'vscode'; -export function textToMarkedString(text: string) : MarkedString { +export function textToMarkedString(text: string): MarkedString { return text.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash } \ No newline at end of file diff --git a/extensions/php/src/features/validationProvider.ts b/extensions/php/src/features/validationProvider.ts index aea88a0b2b324..911b4448d384b 100644 --- a/extensions/php/src/features/validationProvider.ts +++ b/extensions/php/src/features/validationProvider.ts @@ -70,7 +70,7 @@ namespace RunTrigger { onSave: 'onSave', onType: 'onType' }; - export let from = function(value: string): RunTrigger { + export let from = function (value: string): RunTrigger { if (value === 'onType') { return RunTrigger.onType; } else { @@ -108,7 +108,7 @@ export default class PHPValidationProvider { this.loadConfiguration(); vscode.workspace.onDidOpenTextDocument(this.triggerValidate, this, subscriptions); - vscode.workspace.onDidCloseTextDocument((textDocument)=> { + vscode.workspace.onDidCloseTextDocument((textDocument) => { this.diagnosticCollection.delete(textDocument.uri); delete this.delayers[textDocument.uri.toString()]; }, null, subscriptions); @@ -158,7 +158,7 @@ export default class PHPValidationProvider { delayer = new ThrottledDelayer(this.trigger === RunTrigger.onType ? 250 : 0); this.delayers[key] = delayer; } - delayer.trigger(() => this.doValidate(textDocument) ); + delayer.trigger(() => this.doValidate(textDocument)); } private doValidate(textDocument: vscode.TextDocument): Promise { diff --git a/extensions/php/src/phpMain.ts b/extensions/php/src/phpMain.ts index 3cb964d1e0298..4ebc68e31da63 100644 --- a/extensions/php/src/phpMain.ts +++ b/extensions/php/src/phpMain.ts @@ -14,7 +14,7 @@ import { ExtensionContext, languages, env } from 'vscode'; import * as nls from 'vscode-nls'; export function activate(context: ExtensionContext): any { - nls.config({locale: env.language}); + nls.config({ locale: env.language }); // add providers context.subscriptions.push(languages.registerCompletionItemProvider('php', new PHPCompletionItemProvider(), '.', '$')); diff --git a/extensions/php/typings/mocha.d.ts b/extensions/php/typings/mocha.d.ts index 7b23f5d181642..f677473dcdd76 100644 --- a/extensions/php/typings/mocha.d.ts +++ b/extensions/php/typings/mocha.d.ts @@ -5,9 +5,9 @@ declare function run(): void; -declare function suite(name: string, fn: (err?)=>void); -declare function test(name: string, fn: (done?: (err?)=>void)=>void); -declare function suiteSetup(fn: (done?: (err?)=>void)=>void); -declare function suiteTeardown(fn: (done?: (err?)=>void)=>void); -declare function setup(fn: (done?: (err?)=>void)=>void); -declare function teardown(fn: (done?: (err?)=>void)=>void); +declare function suite(name: string, fn: (err?) => void); +declare function test(name: string, fn: (done?: (err?) => void) => void); +declare function suiteSetup(fn: (done?: (err?) => void) => void); +declare function suiteTeardown(fn: (done?: (err?) => void) => void); +declare function setup(fn: (done?: (err?) => void) => void); +declare function teardown(fn: (done?: (err?) => void) => void); diff --git a/extensions/typescript/src/features/referenceProvider.ts b/extensions/typescript/src/features/referenceProvider.ts index c597b6997a7a0..2a7668c2a3c95 100644 --- a/extensions/typescript/src/features/referenceProvider.ts +++ b/extensions/typescript/src/features/referenceProvider.ts @@ -14,7 +14,7 @@ export default class TypeScriptReferenceSupport implements ReferenceProvider { private client: ITypescriptServiceClient; - public tokens:string[] = []; + public tokens: string[] = []; public constructor(client: ITypescriptServiceClient) { this.client = client; diff --git a/extensions/typescript/src/features/workspaceSymbolProvider.ts b/extensions/typescript/src/features/workspaceSymbolProvider.ts index 1fced2f10fbde..da63560fcd6f7 100644 --- a/extensions/typescript/src/features/workspaceSymbolProvider.ts +++ b/extensions/typescript/src/features/workspaceSymbolProvider.ts @@ -7,7 +7,7 @@ import { workspace, window, Uri, WorkspaceSymbolProvider, SymbolInformation, SymbolKind, Range, Location, CancellationToken } from 'vscode'; -import * as Proto from '../protocol'; +import * as Proto from '../protocol'; import { ITypescriptServiceClient } from '../typescriptService'; let _kindMapping: { [kind: string]: SymbolKind } = Object.create(null); @@ -28,7 +28,7 @@ export default class TypeScriptWorkspaceSymbolProvider implements WorkspaceSymbo this.modeId = modeId; } - public provideWorkspaceSymbols(search: string, token :CancellationToken): Promise { + public provideWorkspaceSymbols(search: string, token: CancellationToken): Promise { // typescript wants to have a resource even when asking // general questions so we check the active editor. If this // doesn't match we take the first TS document. @@ -54,14 +54,14 @@ export default class TypeScriptWorkspaceSymbolProvider implements WorkspaceSymbo return Promise.resolve([]); } - let args:Proto.NavtoRequestArgs = { + let args: Proto.NavtoRequestArgs = { file: this.client.asAbsolutePath(uri), searchValue: search }; if (!args.file) { return Promise.resolve([]); } - return this.client.execute('navto', args, token).then((response):SymbolInformation[] => { + return this.client.execute('navto', args, token).then((response): SymbolInformation[] => { let data = response.body; if (data) { let result: SymbolInformation[] = []; diff --git a/extensions/typescript/src/protocol.const.ts b/extensions/typescript/src/protocol.const.ts index 842aa608926a2..f555df66c172b 100644 --- a/extensions/typescript/src/protocol.const.ts +++ b/extensions/typescript/src/protocol.const.ts @@ -6,42 +6,42 @@ 'use strict'; export class Kind { - public static unknown:string = ''; - public static keyword:string = 'keyword'; - public static script:string = 'script'; - public static module:string = 'module'; - public static class:string = 'class'; - public static interface:string = 'interface'; - public static type:string = 'type'; - public static enum:string = 'enum'; - public static variable:string = 'var'; - public static localVariable:string = 'local var'; - public static function:string = 'function'; - public static localFunction:string = 'local function'; - public static memberFunction:string = 'method'; - public static memberGetAccessor:string = 'getter'; - public static memberSetAccessor:string = 'setter'; - public static memberVariable:string = 'property'; - public static constructorImplementation:string = 'constructor'; - public static callSignature:string = 'call'; - public static indexSignature:string = 'index'; - public static constructSignature:string = 'construct'; - public static parameter:string = 'parameter'; - public static typeParameter:string = 'type parameter'; - public static primitiveType:string = 'primitive type'; - public static label:string = 'label'; - public static alias:string = 'alias'; - public static const:string = 'const'; - public static let:string = 'let'; - public static warning:string = 'warning'; + public static unknown: string = ''; + public static keyword: string = 'keyword'; + public static script: string = 'script'; + public static module: string = 'module'; + public static class: string = 'class'; + public static interface: string = 'interface'; + public static type: string = 'type'; + public static enum: string = 'enum'; + public static variable: string = 'var'; + public static localVariable: string = 'local var'; + public static function: string = 'function'; + public static localFunction: string = 'local function'; + public static memberFunction: string = 'method'; + public static memberGetAccessor: string = 'getter'; + public static memberSetAccessor: string = 'setter'; + public static memberVariable: string = 'property'; + public static constructorImplementation: string = 'constructor'; + public static callSignature: string = 'call'; + public static indexSignature: string = 'index'; + public static constructSignature: string = 'construct'; + public static parameter: string = 'parameter'; + public static typeParameter: string = 'type parameter'; + public static primitiveType: string = 'primitive type'; + public static label: string = 'label'; + public static alias: string = 'alias'; + public static const: string = 'const'; + public static let: string = 'let'; + public static warning: string = 'warning'; } export class KindModifier { - public static none:string = ''; - public static staticMember:string = 'public static'; - public static privateMember:string = 'private'; - public static protectedMember:string = 'protected'; - public static exported:string = 'export'; - public static ambient:string = 'declare'; - public static static:string = 'static'; + public static none: string = ''; + public static staticMember: string = 'public static'; + public static privateMember: string = 'private'; + public static protectedMember: string = 'protected'; + public static exported: string = 'export'; + public static ambient: string = 'declare'; + public static static: string = 'static'; } \ No newline at end of file diff --git a/extensions/typescript/src/protocol.d.ts b/extensions/typescript/src/protocol.d.ts index 4baab7e617742..061d41fe9dbfd 100644 --- a/extensions/typescript/src/protocol.d.ts +++ b/extensions/typescript/src/protocol.d.ts @@ -4,428 +4,428 @@ * ------------------------------------------------------------------------------------------ */ /** - * A TypeScript Server message - */ + * A TypeScript Server message + */ export interface Message { - /** - * Sequence number of the message - */ - seq: number; + /** + * Sequence number of the message + */ + seq: number; - /** - * One of "request", "response", or "event" - */ - type: string; + /** + * One of "request", "response", or "event" + */ + type: string; } /** - * Client-initiated request message - */ + * Client-initiated request message + */ export interface Request extends Message { - /** - * The command to execute - */ - command: string; + /** + * The command to execute + */ + command: string; - /** - * Object containing arguments for the command - */ - arguments?: any; + /** + * Object containing arguments for the command + */ + arguments?: any; } /** - * Request to reload the project structure for all the opened files - */ + * Request to reload the project structure for all the opened files + */ export interface ReloadProjectsRequest extends Message { } /** - * Server-initiated event message - */ + * Server-initiated event message + */ export interface Event extends Message { - /** - * Name of event - */ - event: string; + /** + * Name of event + */ + event: string; - /** - * Event-specific information - */ - body?: any; + /** + * Event-specific information + */ + body?: any; } /** - * Response by server to client request message. - */ + * Response by server to client request message. + */ export interface Response extends Message { - /** - * Sequence number of the request message. - */ - request_seq: number; + /** + * Sequence number of the request message. + */ + request_seq: number; - /** - * Outcome of the request. - */ - success: boolean; + /** + * Outcome of the request. + */ + success: boolean; - /** - * The command requested. - */ - command: string; + /** + * The command requested. + */ + command: string; - /** - * Contains error message if success === false. - */ - message?: string; + /** + * Contains error message if success === false. + */ + message?: string; - /** - * Contains message body if success === true. - */ - body?: any; + /** + * Contains message body if success === true. + */ + body?: any; } /** - * Arguments for FileRequest messages. - */ + * Arguments for FileRequest messages. + */ export interface FileRequestArgs { - /** - * The file for the request (absolute pathname required). - */ - file: string; + /** + * The file for the request (absolute pathname required). + */ + file: string; } /** - * Arguments for ProjectInfoRequest request. - */ + * Arguments for ProjectInfoRequest request. + */ export interface ProjectInfoRequestArgs extends FileRequestArgs { - /** - * Indicate if the file name list of the project is needed - */ - needFileNameList: boolean; + /** + * Indicate if the file name list of the project is needed + */ + needFileNameList: boolean; } /** - * A request to get the project information of the current file - */ + * A request to get the project information of the current file + */ export interface ProjectInfoRequest extends Request { - arguments: ProjectInfoRequestArgs; + arguments: ProjectInfoRequestArgs; } /** - * Response message body for "projectInfo" request - */ + * Response message body for "projectInfo" request + */ export interface ProjectInfo { - /** - * For configured project, this is the normalized path of the 'tsconfig.json' file - * For inferred project, this is undefined - */ - configFileName: string; - /** - * The list of normalized file name in the project, including 'lib.d.ts' - */ - fileNames?: string[]; - /** - * Indicates if the project has a active language service instance - */ - languageServiceDisabled?: boolean; -} - -/** - * Response message for "projectInfo" request - */ + /** + * For configured project, this is the normalized path of the 'tsconfig.json' file + * For inferred project, this is undefined + */ + configFileName: string; + /** + * The list of normalized file name in the project, including 'lib.d.ts' + */ + fileNames?: string[]; + /** + * Indicates if the project has a active language service instance + */ + languageServiceDisabled?: boolean; +} + +/** + * Response message for "projectInfo" request + */ export interface ProjectInfoResponse extends Response { - body?: ProjectInfo; + body?: ProjectInfo; } /** - * Request whose sole parameter is a file name. - */ + * Request whose sole parameter is a file name. + */ export interface FileRequest extends Request { - arguments: FileRequestArgs; + arguments: FileRequestArgs; } /** - * Instances of this interface specify a location in a source file: - * (file, line, character offset), where line and character offset are 1-based. - */ + * Instances of this interface specify a location in a source file: + * (file, line, character offset), where line and character offset are 1-based. + */ export interface FileLocationRequestArgs extends FileRequestArgs { - /** - * The line number for the request (1-based). - */ - line: number; + /** + * The line number for the request (1-based). + */ + line: number; - /** - * The character offset (on the line) for the request (1-based). - */ - offset: number; + /** + * The character offset (on the line) for the request (1-based). + */ + offset: number; } /** - * A request whose arguments specify a file location (file, line, col). - */ + * A request whose arguments specify a file location (file, line, col). + */ export interface FileLocationRequest extends FileRequest { - arguments: FileLocationRequestArgs; + arguments: FileLocationRequestArgs; } /** - * Arguments in document highlight request; include: filesToSearch, file, - * line, offset. - */ + * Arguments in document highlight request; include: filesToSearch, file, + * line, offset. + */ export interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { - /** - * List of files to search for document highlights. - */ - filesToSearch: string[]; + /** + * List of files to search for document highlights. + */ + filesToSearch: string[]; } /** - * Go to definition request; value of command field is - * "definition". Return response giving the file locations that - * define the symbol found in file at location line, col. - */ + * Go to definition request; value of command field is + * "definition". Return response giving the file locations that + * define the symbol found in file at location line, col. + */ export interface DefinitionRequest extends FileLocationRequest { } /** - * Go to type request; value of command field is - * "typeDefinition". Return response giving the file locations that - * define the type for the symbol found in file at location line, col. - */ + * Go to type request; value of command field is + * "typeDefinition". Return response giving the file locations that + * define the type for the symbol found in file at location line, col. + */ export interface TypeDefinitionRequest extends FileLocationRequest { } /** - * Location in source code expressed as (one-based) line and character offset. - */ + * Location in source code expressed as (one-based) line and character offset. + */ export interface Location { - line: number; - offset: number; + line: number; + offset: number; } /** - * Object found in response messages defining a span of text in source code. - */ + * Object found in response messages defining a span of text in source code. + */ export interface TextSpan { - /** - * First character of the definition. - */ - start: Location; + /** + * First character of the definition. + */ + start: Location; - /** - * One character past last character of the definition. - */ - end: Location; + /** + * One character past last character of the definition. + */ + end: Location; } /** - * Object found in response messages defining a span of text in a specific source file. - */ + * Object found in response messages defining a span of text in a specific source file. + */ export interface FileSpan extends TextSpan { - /** - * File containing text span. - */ - file: string; + /** + * File containing text span. + */ + file: string; } /** - * Definition response message. Gives text range for definition. - */ + * Definition response message. Gives text range for definition. + */ export interface DefinitionResponse extends Response { - body?: FileSpan[]; + body?: FileSpan[]; } /** - * Definition response message. Gives text range for definition. - */ + * Definition response message. Gives text range for definition. + */ export interface TypeDefinitionResponse extends Response { - body?: FileSpan[]; + body?: FileSpan[]; } /** - * Get occurrences request; value of command field is - * "occurrences". Return response giving spans that are relevant - * in the file at a given line and column. - */ + * Get occurrences request; value of command field is + * "occurrences". Return response giving spans that are relevant + * in the file at a given line and column. + */ export interface OccurrencesRequest extends FileLocationRequest { } export interface OccurrencesResponseItem extends FileSpan { - /** - * True if the occurrence is a write location, false otherwise. - */ - isWriteAccess: boolean; + /** + * True if the occurrence is a write location, false otherwise. + */ + isWriteAccess: boolean; } export interface OccurrencesResponse extends Response { - body?: OccurrencesResponseItem[]; + body?: OccurrencesResponseItem[]; } /** - * Get document highlights request; value of command field is - * "documentHighlights". Return response giving spans that are relevant - * in the file at a given line and column. - */ + * Get document highlights request; value of command field is + * "documentHighlights". Return response giving spans that are relevant + * in the file at a given line and column. + */ export interface DocumentHighlightsRequest extends FileLocationRequest { - arguments: DocumentHighlightsRequestArgs; + arguments: DocumentHighlightsRequestArgs; } export interface HighlightSpan extends TextSpan { - kind: string; + kind: string; } export interface DocumentHighlightsItem { - /** - * File containing highlight spans. - */ - file: string; + /** + * File containing highlight spans. + */ + file: string; - /** - * Spans to highlight in file. - */ - highlightSpans: HighlightSpan[]; + /** + * Spans to highlight in file. + */ + highlightSpans: HighlightSpan[]; } export interface DocumentHighlightsResponse extends Response { - body?: DocumentHighlightsItem[]; + body?: DocumentHighlightsItem[]; } /** - * Find references request; value of command field is - * "references". Return response giving the file locations that - * reference the symbol found in file at location line, col. - */ + * Find references request; value of command field is + * "references". Return response giving the file locations that + * reference the symbol found in file at location line, col. + */ export interface ReferencesRequest extends FileLocationRequest { } export interface ReferencesResponseItem extends FileSpan { - /** Text of line containing the reference. Including this - * with the response avoids latency of editor loading files - * to show text of reference line (the server already has - * loaded the referencing files). - */ - lineText: string; + /** Text of line containing the reference. Including this + * with the response avoids latency of editor loading files + * to show text of reference line (the server already has + * loaded the referencing files). + */ + lineText: string; - /** - * True if reference is a write location, false otherwise. - */ - isWriteAccess: boolean; + /** + * True if reference is a write location, false otherwise. + */ + isWriteAccess: boolean; - /** - * True if reference is a definition, false otherwise. - */ - isDefinition: boolean; + /** + * True if reference is a definition, false otherwise. + */ + isDefinition: boolean; } /** - * The body of a "references" response message. - */ + * The body of a "references" response message. + */ export interface ReferencesResponseBody { - /** - * The file locations referencing the symbol. - */ - refs: ReferencesResponseItem[]; + /** + * The file locations referencing the symbol. + */ + refs: ReferencesResponseItem[]; - /** - * The name of the symbol. - */ - symbolName: string; + /** + * The name of the symbol. + */ + symbolName: string; - /** - * The start character offset of the symbol (on the line provided by the references request). - */ - symbolStartOffset: number; + /** + * The start character offset of the symbol (on the line provided by the references request). + */ + symbolStartOffset: number; - /** - * The full display name of the symbol. - */ - symbolDisplayString: string; + /** + * The full display name of the symbol. + */ + symbolDisplayString: string; } /** - * Response to "references" request. - */ + * Response to "references" request. + */ export interface ReferencesResponse extends Response { - body?: ReferencesResponseBody; + body?: ReferencesResponseBody; } export interface RenameRequestArgs extends FileLocationRequestArgs { - findInComments?: boolean; - findInStrings?: boolean; + findInComments?: boolean; + findInStrings?: boolean; } /** - * Rename request; value of command field is "rename". Return - * response giving the file locations that reference the symbol - * found in file at location line, col. Also return full display - * name of the symbol so that client can print it unambiguously. - */ + * Rename request; value of command field is "rename". Return + * response giving the file locations that reference the symbol + * found in file at location line, col. Also return full display + * name of the symbol so that client can print it unambiguously. + */ export interface RenameRequest extends FileLocationRequest { - arguments: RenameRequestArgs; + arguments: RenameRequestArgs; } /** - * Information about the item to be renamed. - */ + * Information about the item to be renamed. + */ export interface RenameInfo { - /** - * True if item can be renamed. - */ - canRename: boolean; + /** + * True if item can be renamed. + */ + canRename: boolean; - /** - * Error message if item can not be renamed. - */ - localizedErrorMessage?: string; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage?: string; - /** - * Display name of the item to be renamed. - */ - displayName: string; + /** + * Display name of the item to be renamed. + */ + displayName: string; - /** - * Full display name of item to be renamed. - */ - fullDisplayName: string; + /** + * Full display name of item to be renamed. + */ + fullDisplayName: string; - /** - * The items's kind (such as 'className' or 'parameterName' or plain 'text'). - */ - kind: string; + /** + * The items's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; } /** * A group of text spans, all in 'file'. */ export interface SpanGroup { - /** The file to which the spans apply */ - file: string; - /** The text spans in this group */ - locs: TextSpan[]; + /** The file to which the spans apply */ + file: string; + /** The text spans in this group */ + locs: TextSpan[]; } export interface RenameResponseBody { - /** - * Information about the item to be renamed. - */ - info: RenameInfo; + /** + * Information about the item to be renamed. + */ + info: RenameInfo; - /** - * An array of span groups (one per file) that refer to the item to be renamed. - */ - locs: SpanGroup[]; + /** + * An array of span groups (one per file) that refer to the item to be renamed. + */ + locs: SpanGroup[]; } /** - * Rename response message. - */ + * Rename response message. + */ export interface RenameResponse extends Response { - body?: RenameResponseBody; + body?: RenameResponseBody; } /** @@ -433,20 +433,20 @@ export interface RenameResponse extends Response { */ export interface EditorOptions { - /** Number of spaces for each tab. Default value is 4. */ - tabSize?: number; + /** Number of spaces for each tab. Default value is 4. */ + tabSize?: number; - /** Number of spaces to indent during formatting. Default value is 4. */ - indentSize?: number; + /** Number of spaces to indent during formatting. Default value is 4. */ + indentSize?: number; - /** Number of additional spaces to indent during formatting to preserve base indentation (ex. script block indentation). Default value is 0. */ - baseIndentSize?: number; + /** Number of additional spaces to indent during formatting to preserve base indentation (ex. script block indentation). Default value is 0. */ + baseIndentSize?: number; - /** The new line character to be used. Default value is the OS line delimiter. */ - newLineCharacter?: string; + /** The new line character to be used. Default value is the OS line delimiter. */ + newLineCharacter?: string; - /** Whether tabs should be converted to spaces. Default value is true. */ - convertTabsToSpaces?: boolean; + /** Whether tabs should be converted to spaces. Default value is true. */ + convertTabsToSpaces?: boolean; } /** @@ -454,374 +454,374 @@ export interface EditorOptions { */ export interface FormatOptions extends EditorOptions { - /** Defines space handling after a comma delimiter. Default value is true. */ - insertSpaceAfterCommaDelimiter?: boolean; + /** Defines space handling after a comma delimiter. Default value is true. */ + insertSpaceAfterCommaDelimiter?: boolean; - /** Defines space handling after a semicolon in a for statement. Default value is true */ - insertSpaceAfterSemicolonInForStatements?: boolean; + /** Defines space handling after a semicolon in a for statement. Default value is true */ + insertSpaceAfterSemicolonInForStatements?: boolean; - /** Defines space handling after a binary operator. Default value is true. */ - insertSpaceBeforeAndAfterBinaryOperators?: boolean; + /** Defines space handling after a binary operator. Default value is true. */ + insertSpaceBeforeAndAfterBinaryOperators?: boolean; - /** Defines space handling after keywords in control flow statement. Default value is true. */ - insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + /** Defines space handling after keywords in control flow statement. Default value is true. */ + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; - /** Defines space handling after function keyword for anonymous functions. Default value is false. */ - insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + /** Defines space handling after function keyword for anonymous functions. Default value is false. */ + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; - /** Defines space handling after opening and before closing non empty parenthesis. Default value is false. */ - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + /** Defines space handling after opening and before closing non empty parenthesis. Default value is false. */ + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; - /** Defines space handling after opening and before closing non empty brackets. Default value is false. */ - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + /** Defines space handling after opening and before closing non empty brackets. Default value is false. */ + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; - /** Defines whether an open brace is put onto a new line for functions or not. Default value is false. */ - placeOpenBraceOnNewLineForFunctions?: boolean; + /** Defines whether an open brace is put onto a new line for functions or not. Default value is false. */ + placeOpenBraceOnNewLineForFunctions?: boolean; - /** Defines whether an open brace is put onto a new line for control blocks or not. Default value is false. */ - placeOpenBraceOnNewLineForControlBlocks?: boolean; + /** Defines whether an open brace is put onto a new line for control blocks or not. Default value is false. */ + placeOpenBraceOnNewLineForControlBlocks?: boolean; - /** Index operator */ - [key: string]: string | number | boolean | undefined; + /** Index operator */ + [key: string]: string | number | boolean | undefined; } /** - * Information found in a configure request. - */ + * Information found in a configure request. + */ export interface ConfigureRequestArguments { - /** - * Information about the host, for example 'Emacs 24.4' or - * 'Sublime Text version 3075' - */ - hostInfo?: string; + /** + * Information about the host, for example 'Emacs 24.4' or + * 'Sublime Text version 3075' + */ + hostInfo?: string; - /** - * Sets a folder that can be used by the tsserver to store - * meta data information. - */ - metaDataDirectory?: string; + /** + * Sets a folder that can be used by the tsserver to store + * meta data information. + */ + metaDataDirectory?: string; - /** - * Turns the tsserver into auto diagnostice mode. When in - * auto diagnostic mode the server will automatically generate - * diagnostics and send them to the client without requests - */ - autoDiagnostics?: boolean; + /** + * Turns the tsserver into auto diagnostice mode. When in + * auto diagnostic mode the server will automatically generate + * diagnostics and send them to the client without requests + */ + autoDiagnostics?: boolean; - /** - * If present, tab settings apply only to this file. - */ - file?: string; + /** + * If present, tab settings apply only to this file. + */ + file?: string; - /** - * The format options to use during formatting and other code editing features. - */ - formatOptions?: FormatOptions; + /** + * The format options to use during formatting and other code editing features. + */ + formatOptions?: FormatOptions; } /** - * Configure request; value of command field is "configure". Specifies - * host information, such as host type, tab size, and indent size. - */ + * Configure request; value of command field is "configure". Specifies + * host information, such as host type, tab size, and indent size. + */ export interface ConfigureRequest extends Request { - arguments: ConfigureRequestArguments; + arguments: ConfigureRequestArguments; } /** - * Response to "configure" request. This is just an acknowledgement, so - * no body field is required. - */ + * Response to "configure" request. This is just an acknowledgement, so + * no body field is required. + */ export interface ConfigureResponse extends Response { } /** - * Information found in an "open" request. - */ + * Information found in an "open" request. + */ export interface OpenRequestArgs extends FileRequestArgs { - /** - * Used when a version of the file content is known to be more up to date than the one on disk. - * Then the known content will be used upon opening instead of the disk copy - */ - fileContent?: string; - /** - * Used to specify the script kind of the file explicitly. It could be one of the following: - * "TS", "JS", "TSX", "JSX" - */ - scriptKindName?: "TS" | "JS" | "TSX" | "JSX"; -} - -/** - * Open request; value of command field is "open". Notify the - * server that the client has file open. The server will not - * monitor the filesystem for changes in this file and will assume - * that the client is updating the server (using the change and/or - * reload messages) when the file changes. Server does not currently - * send a response to an open request. - */ + /** + * Used when a version of the file content is known to be more up to date than the one on disk. + * Then the known content will be used upon opening instead of the disk copy + */ + fileContent?: string; + /** + * Used to specify the script kind of the file explicitly. It could be one of the following: + * "TS", "JS", "TSX", "JSX" + */ + scriptKindName?: "TS" | "JS" | "TSX" | "JSX"; +} + +/** + * Open request; value of command field is "open". Notify the + * server that the client has file open. The server will not + * monitor the filesystem for changes in this file and will assume + * that the client is updating the server (using the change and/or + * reload messages) when the file changes. Server does not currently + * send a response to an open request. + */ export interface OpenRequest extends Request { - arguments: OpenRequestArgs; + arguments: OpenRequestArgs; } /** - * Exit request; value of command field is "exit". Ask the server process - * to exit. - */ + * Exit request; value of command field is "exit". Ask the server process + * to exit. + */ export interface ExitRequest extends Request { } /** - * Close request; value of command field is "close". Notify the - * server that the client has closed a previously open file. If - * file is still referenced by open files, the server will resume - * monitoring the filesystem for changes to file. Server does not - * currently send a response to a close request. - */ + * Close request; value of command field is "close". Notify the + * server that the client has closed a previously open file. If + * file is still referenced by open files, the server will resume + * monitoring the filesystem for changes to file. Server does not + * currently send a response to a close request. + */ export interface CloseRequest extends FileRequest { } /** - * Quickinfo request; value of command field is - * "quickinfo". Return response giving a quick type and - * documentation string for the symbol found in file at location - * line, col. - */ + * Quickinfo request; value of command field is + * "quickinfo". Return response giving a quick type and + * documentation string for the symbol found in file at location + * line, col. + */ export interface QuickInfoRequest extends FileLocationRequest { } /** - * Body of QuickInfoResponse. - */ + * Body of QuickInfoResponse. + */ export interface QuickInfoResponseBody { - /** - * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). - */ - kind: string; + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; - /** - * Starting file location of symbol. - */ - start: Location; + /** + * Starting file location of symbol. + */ + start: Location; - /** - * One past last character of symbol. - */ - end: Location; + /** + * One past last character of symbol. + */ + end: Location; - /** - * Type and kind of symbol. - */ - displayString: string; + /** + * Type and kind of symbol. + */ + displayString: string; - /** - * Documentation associated with symbol. - */ - documentation: string; + /** + * Documentation associated with symbol. + */ + documentation: string; } /** - * Quickinfo response message. - */ + * Quickinfo response message. + */ export interface QuickInfoResponse extends Response { - body?: QuickInfoResponseBody; + body?: QuickInfoResponseBody; } /** - * Arguments for format messages. - */ + * Arguments for format messages. + */ export interface FormatRequestArgs extends FileLocationRequestArgs { - /** - * Last line of range for which to format text in file. - */ - endLine: number; + /** + * Last line of range for which to format text in file. + */ + endLine: number; - /** - * Character offset on last line of range for which to format text in file. - */ - endOffset: number; + /** + * Character offset on last line of range for which to format text in file. + */ + endOffset: number; } /** - * Format request; value of command field is "format". Return - * response giving zero or more edit instructions. The edit - * instructions will be sorted in file order. Applying the edit - * instructions in reverse to file will result in correctly - * reformatted text. - */ + * Format request; value of command field is "format". Return + * response giving zero or more edit instructions. The edit + * instructions will be sorted in file order. Applying the edit + * instructions in reverse to file will result in correctly + * reformatted text. + */ export interface FormatRequest extends FileLocationRequest { - arguments: FormatRequestArgs; + arguments: FormatRequestArgs; } /** - * Object found in response messages defining an editing - * instruction for a span of text in source code. The effect of - * this instruction is to replace the text starting at start and - * ending one character before end with newText. For an insertion, - * the text span is empty. For a deletion, newText is empty. - */ + * Object found in response messages defining an editing + * instruction for a span of text in source code. The effect of + * this instruction is to replace the text starting at start and + * ending one character before end with newText. For an insertion, + * the text span is empty. For a deletion, newText is empty. + */ export interface CodeEdit { - /** - * First character of the text span to edit. - */ - start: Location; + /** + * First character of the text span to edit. + */ + start: Location; - /** - * One character past last character of the text span to edit. - */ - end: Location; + /** + * One character past last character of the text span to edit. + */ + end: Location; - /** - * Replace the span defined above with this string (may be - * the empty string). - */ - newText: string; + /** + * Replace the span defined above with this string (may be + * the empty string). + */ + newText: string; } /** - * Format and format on key response message. - */ + * Format and format on key response message. + */ export interface FormatResponse extends Response { - body?: CodeEdit[]; + body?: CodeEdit[]; } /** - * Arguments for format on key messages. - */ + * Arguments for format on key messages. + */ export interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { - /** - * Key pressed (';', '\n', or '}'). - */ - key: string; + /** + * Key pressed (';', '\n', or '}'). + */ + key: string; } /** - * Format on key request; value of command field is - * "formatonkey". Given file location and key typed (as string), - * return response giving zero or more edit instructions. The - * edit instructions will be sorted in file order. Applying the - * edit instructions in reverse to file will result in correctly - * reformatted text. - */ + * Format on key request; value of command field is + * "formatonkey". Given file location and key typed (as string), + * return response giving zero or more edit instructions. The + * edit instructions will be sorted in file order. Applying the + * edit instructions in reverse to file will result in correctly + * reformatted text. + */ export interface FormatOnKeyRequest extends FileLocationRequest { - arguments: FormatOnKeyRequestArgs; + arguments: FormatOnKeyRequestArgs; } /** - * Arguments for completions messages. - */ + * Arguments for completions messages. + */ export interface CompletionsRequestArgs extends FileLocationRequestArgs { - /** - * Optional prefix to apply to possible completions. - */ - prefix?: string; + /** + * Optional prefix to apply to possible completions. + */ + prefix?: string; } /** - * Completions request; value of command field is "completions". - * Given a file location (file, line, col) and a prefix (which may - * be the empty string), return the possible completions that - * begin with prefix. - */ + * Completions request; value of command field is "completions". + * Given a file location (file, line, col) and a prefix (which may + * be the empty string), return the possible completions that + * begin with prefix. + */ export interface CompletionsRequest extends FileLocationRequest { - arguments: CompletionsRequestArgs; + arguments: CompletionsRequestArgs; } /** - * Arguments for completion details request. - */ + * Arguments for completion details request. + */ export interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { - /** - * Names of one or more entries for which to obtain details. - */ - entryNames: string[]; + /** + * Names of one or more entries for which to obtain details. + */ + entryNames: string[]; } /** - * Completion entry details request; value of command field is - * "completionEntryDetails". Given a file location (file, line, - * col) and an array of completion entry names return more - * detailed information for each completion entry. - */ + * Completion entry details request; value of command field is + * "completionEntryDetails". Given a file location (file, line, + * col) and an array of completion entry names return more + * detailed information for each completion entry. + */ export interface CompletionDetailsRequest extends FileLocationRequest { - arguments: CompletionDetailsRequestArgs; + arguments: CompletionDetailsRequestArgs; } /** - * Part of a symbol description. - */ + * Part of a symbol description. + */ export interface SymbolDisplayPart { - /** - * Text of an item describing the symbol. - */ - text: string; + /** + * Text of an item describing the symbol. + */ + text: string; - /** - * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). - */ - kind: string; + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; } /** - * An item found in a completion response. - */ + * An item found in a completion response. + */ export interface CompletionEntry { - /** - * The symbol's name. - */ - name: string; - /** - * The symbol's kind (such as 'className' or 'parameterName'). - */ - kind: string; - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers: string; - /** - * A string that is used for comparing completion items so that they can be ordered. This - * is often the same as the name but may be different in certain circumstances. - */ - sortText: string; -} - -/** - * Additional completion entry details, available on demand - */ + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * A string that is used for comparing completion items so that they can be ordered. This + * is often the same as the name but may be different in certain circumstances. + */ + sortText: string; +} + +/** + * Additional completion entry details, available on demand + */ export interface CompletionEntryDetails { - /** - * The symbol's name. - */ - name: string; - /** - * The symbol's kind (such as 'className' or 'parameterName'). - */ - kind: string; - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers: string; - /** - * Display parts of the symbol (similar to quick info). - */ - displayParts: SymbolDisplayPart[]; - - /** - * Documentation strings for the symbol. - */ - documentation: SymbolDisplayPart[]; + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Display parts of the symbol (similar to quick info). + */ + displayParts: SymbolDisplayPart[]; + + /** + * Documentation strings for the symbol. + */ + documentation: SymbolDisplayPart[]; } export interface CompletionsResponse extends Response { - body?: CompletionEntry[]; + body?: CompletionEntry[]; } export interface CompletionDetailsResponse extends Response { - body?: CompletionEntryDetails[]; + body?: CompletionEntryDetails[]; } /** @@ -829,25 +829,25 @@ export interface CompletionDetailsResponse extends Response { */ export interface SignatureHelpParameter { - /** - * The parameter's name - */ - name: string; + /** + * The parameter's name + */ + name: string; - /** - * Documentation of the parameter. - */ - documentation: SymbolDisplayPart[]; + /** + * Documentation of the parameter. + */ + documentation: SymbolDisplayPart[]; - /** - * Display parts of the parameter. - */ - displayParts: SymbolDisplayPart[]; + /** + * Display parts of the parameter. + */ + displayParts: SymbolDisplayPart[]; - /** - * Whether the parameter is optional or not. - */ - isOptional: boolean; + /** + * Whether the parameter is optional or not. + */ + isOptional: boolean; } /** @@ -855,35 +855,35 @@ export interface SignatureHelpParameter { */ export interface SignatureHelpItem { - /** - * Whether the signature accepts a variable number of arguments. - */ - isVariadic: boolean; + /** + * Whether the signature accepts a variable number of arguments. + */ + isVariadic: boolean; - /** - * The prefix display parts. - */ - prefixDisplayParts: SymbolDisplayPart[]; + /** + * The prefix display parts. + */ + prefixDisplayParts: SymbolDisplayPart[]; - /** - * The suffix display parts. - */ - suffixDisplayParts: SymbolDisplayPart[]; + /** + * The suffix display parts. + */ + suffixDisplayParts: SymbolDisplayPart[]; - /** - * The separator display parts. - */ - separatorDisplayParts: SymbolDisplayPart[]; + /** + * The separator display parts. + */ + separatorDisplayParts: SymbolDisplayPart[]; - /** - * The signature helps items for the parameters. - */ - parameters: SignatureHelpParameter[]; + /** + * The signature helps items for the parameters. + */ + parameters: SignatureHelpParameter[]; - /** - * The signature's documentation - */ - documentation: SymbolDisplayPart[]; + /** + * The signature's documentation + */ + documentation: SymbolDisplayPart[]; } /** @@ -891,30 +891,30 @@ export interface SignatureHelpItem { */ export interface SignatureHelpItems { - /** - * The signature help items. - */ - items: SignatureHelpItem[]; + /** + * The signature help items. + */ + items: SignatureHelpItem[]; - /** - * The span for which signature help should appear on a signature - */ - applicableSpan: TextSpan; + /** + * The span for which signature help should appear on a signature + */ + applicableSpan: TextSpan; - /** - * The item selected in the set of available help items. - */ - selectedItemIndex: number; + /** + * The item selected in the set of available help items. + */ + selectedItemIndex: number; - /** - * The argument selected in the set of parameters. - */ - argumentIndex: number; + /** + * The argument selected in the set of parameters. + */ + argumentIndex: number; - /** - * The argument count - */ - argumentCount: number; + /** + * The argument count + */ + argumentCount: number; } /** @@ -924,163 +924,163 @@ export interface SignatureHelpRequestArgs extends FileLocationRequestArgs { } /** - * Signature help request; value of command field is "signatureHelp". - * Given a file location (file, line, col), return the signature - * help. - */ + * Signature help request; value of command field is "signatureHelp". + * Given a file location (file, line, col), return the signature + * help. + */ export interface SignatureHelpRequest extends FileLocationRequest { - arguments: SignatureHelpRequestArgs; + arguments: SignatureHelpRequestArgs; } /** * Response object for a SignatureHelpRequest. */ export interface SignatureHelpResponse extends Response { - body?: SignatureHelpItems; + body?: SignatureHelpItems; } /** - * Synchronous request for semantic diagnostics of one file. - */ + * Synchronous request for semantic diagnostics of one file. + */ export interface SemanticDiagnosticsSyncRequest extends FileRequest { } /** - * Response object for synchronous sematic diagnostics request. - */ + * Response object for synchronous sematic diagnostics request. + */ export interface SemanticDiagnosticsSyncResponse extends Response { - body?: Diagnostic[]; + body?: Diagnostic[]; } /** - * Synchronous request for syntactic diagnostics of one file. - */ + * Synchronous request for syntactic diagnostics of one file. + */ export interface SyntacticDiagnosticsSyncRequest extends FileRequest { } /** - * Response object for synchronous syntactic diagnostics request. - */ + * Response object for synchronous syntactic diagnostics request. + */ export interface SyntacticDiagnosticsSyncResponse extends Response { - body?: Diagnostic[]; + body?: Diagnostic[]; } /** * Arguments for GeterrForProject request. */ export interface GeterrForProjectRequestArgs { - /** - * the file requesting project error list - */ - file: string; + /** + * the file requesting project error list + */ + file: string; - /** - * Delay in milliseconds to wait before starting to compute - * errors for the files in the file list - */ - delay: number; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; } /** - * GeterrForProjectRequest request; value of command field is - * "geterrForProject". It works similarly with 'Geterr', only - * it request for every file in this project. - */ + * GeterrForProjectRequest request; value of command field is + * "geterrForProject". It works similarly with 'Geterr', only + * it request for every file in this project. + */ export interface GeterrForProjectRequest extends Request { - arguments: GeterrForProjectRequestArgs; + arguments: GeterrForProjectRequestArgs; } /** - * Arguments for geterr messages. - */ + * Arguments for geterr messages. + */ export interface GeterrRequestArgs { - /** - * List of file names for which to compute compiler errors. - * The files will be checked in list order. - */ - files: string[]; - - /** - * Delay in milliseconds to wait before starting to compute - * errors for the files in the file list - */ - delay: number; -} - -/** - * Geterr request; value of command field is "geterr". Wait for - * delay milliseconds and then, if during the wait no change or - * reload messages have arrived for the first file in the files - * list, get the syntactic errors for the file, field requests, - * and then get the semantic errors for the file. Repeat with a - * smaller delay for each subsequent file on the files list. Best - * practice for an editor is to send a file list containing each - * file that is currently visible, in most-recently-used order. - */ + /** + * List of file names for which to compute compiler errors. + * The files will be checked in list order. + */ + files: string[]; + + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; +} + +/** + * Geterr request; value of command field is "geterr". Wait for + * delay milliseconds and then, if during the wait no change or + * reload messages have arrived for the first file in the files + * list, get the syntactic errors for the file, field requests, + * and then get the semantic errors for the file. Repeat with a + * smaller delay for each subsequent file on the files list. Best + * practice for an editor is to send a file list containing each + * file that is currently visible, in most-recently-used order. + */ export interface GeterrRequest extends Request { - arguments: GeterrRequestArgs; + arguments: GeterrRequestArgs; } /** - * Item of diagnostic information found in a DiagnosticEvent message. - */ + * Item of diagnostic information found in a DiagnosticEvent message. + */ export interface Diagnostic { - /** - * Starting file location at which text applies. - */ - start: Location; + /** + * Starting file location at which text applies. + */ + start: Location; - /** - * The last file location at which the text applies. - */ - end: Location; + /** + * The last file location at which the text applies. + */ + end: Location; - /** - * Text of diagnostic message. - */ - text: string; + /** + * Text of diagnostic message. + */ + text: string; } export interface DiagnosticEventBody { - /** - * The file for which diagnostic information is reported. - */ - file: string; + /** + * The file for which diagnostic information is reported. + */ + file: string; - /** - * An array of diagnostic information items. - */ - diagnostics: Diagnostic[]; + /** + * An array of diagnostic information items. + */ + diagnostics: Diagnostic[]; - /** - * Information about the current length of the build queue. - */ - queueLength?: number; + /** + * Information about the current length of the build queue. + */ + queueLength?: number; } /** - * Event message for "syntaxDiag" and "semanticDiag" event types. - * These events provide syntactic and semantic errors for a file. - */ + * Event message for "syntaxDiag" and "semanticDiag" event types. + * These events provide syntactic and semantic errors for a file. + */ export interface DiagnosticEvent extends Event { - body?: DiagnosticEventBody; + body?: DiagnosticEventBody; } export interface ConfigFileDiagnosticEventBody { - /** - * The file which trigged the searching and error-checking of the config file - */ - triggerFile: string; + /** + * The file which trigged the searching and error-checking of the config file + */ + triggerFile: string; - /** - * The name of the found config file. - */ - configFile: string; + /** + * The name of the found config file. + */ + configFile: string; - /** - * An arry of diagnostic information items for the found config file. - */ - diagnostics: Diagnostic[]; + /** + * An arry of diagnostic information items for the found config file. + */ + diagnostics: Diagnostic[]; } /** @@ -1088,223 +1088,223 @@ export interface ConfigFileDiagnosticEventBody { * This event provides errors for a found config file. */ export interface ConfigFileDiagnosticEvent extends Event { - body?: ConfigFileDiagnosticEventBody; - event: "configFileDiag"; + body?: ConfigFileDiagnosticEventBody; + event: "configFileDiag"; } /** - * Arguments for reload request. - */ + * Arguments for reload request. + */ export interface ReloadRequestArgs extends FileRequestArgs { - /** - * Name of temporary file from which to reload file - * contents. May be same as file. - */ - tmpfile: string; + /** + * Name of temporary file from which to reload file + * contents. May be same as file. + */ + tmpfile: string; } /** - * Reload request message; value of command field is "reload". - * Reload contents of file with name given by the 'file' argument - * from temporary file with name given by the 'tmpfile' argument. - * The two names can be identical. - */ + * Reload request message; value of command field is "reload". + * Reload contents of file with name given by the 'file' argument + * from temporary file with name given by the 'tmpfile' argument. + * The two names can be identical. + */ export interface ReloadRequest extends FileRequest { - arguments: ReloadRequestArgs; + arguments: ReloadRequestArgs; } /** - * Response to "reload" request. This is just an acknowledgement, so - * no body field is required. - */ + * Response to "reload" request. This is just an acknowledgement, so + * no body field is required. + */ export interface ReloadResponse extends Response { } /** - * Arguments for saveto request. - */ + * Arguments for saveto request. + */ export interface SavetoRequestArgs extends FileRequestArgs { - /** - * Name of temporary file into which to save server's view of - * file contents. - */ - tmpfile: string; + /** + * Name of temporary file into which to save server's view of + * file contents. + */ + tmpfile: string; } /** - * Saveto request message; value of command field is "saveto". - * For debugging purposes, save to a temporaryfile (named by - * argument 'tmpfile') the contents of file named by argument - * 'file'. The server does not currently send a response to a - * "saveto" request. - */ + * Saveto request message; value of command field is "saveto". + * For debugging purposes, save to a temporaryfile (named by + * argument 'tmpfile') the contents of file named by argument + * 'file'. The server does not currently send a response to a + * "saveto" request. + */ export interface SavetoRequest extends FileRequest { - arguments: SavetoRequestArgs; + arguments: SavetoRequestArgs; } /** - * Arguments for navto request message. - */ + * Arguments for navto request message. + */ export interface NavtoRequestArgs extends FileRequestArgs { - /** - * Search term to navigate to from current location; term can - * be '.*' or an identifier prefix. - */ - searchValue: string; - /** - * Optional limit on the number of items to return. - */ - maxResultCount?: number; -} - -/** - * Navto request message; value of command field is "navto". - * Return list of objects giving file locations and symbols that - * match the search term given in argument 'searchTerm'. The - * context for the search is given by the named file. - */ + /** + * Search term to navigate to from current location; term can + * be '.*' or an identifier prefix. + */ + searchValue: string; + /** + * Optional limit on the number of items to return. + */ + maxResultCount?: number; +} + +/** + * Navto request message; value of command field is "navto". + * Return list of objects giving file locations and symbols that + * match the search term given in argument 'searchTerm'. The + * context for the search is given by the named file. + */ export interface NavtoRequest extends FileRequest { - arguments: NavtoRequestArgs; + arguments: NavtoRequestArgs; } /** - * An item found in a navto response. - */ + * An item found in a navto response. + */ export interface NavtoItem { - /** - * The symbol's name. - */ - name: string; - - /** - * The symbol's kind (such as 'className' or 'parameterName'). - */ - kind: string; - - /** - * exact, substring, or prefix. - */ - matchKind?: string; - - /** - * If this was a case sensitive or insensitive match. - */ - isCaseSensitive?: boolean; - - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers?: string; - - /** - * The file in which the symbol is found. - */ - file: string; - - /** - * The location within file at which the symbol is found. - */ - start: Location; - - /** - * One past the last character of the symbol. - */ - end: Location; - - /** - * Name of symbol's container symbol (if any); for example, - * the class name if symbol is a class member. - */ - containerName?: string; - - /** - * Kind of symbol's container symbol (if any). - */ - containerKind?: string; -} - -/** - * Navto response message. Body is an array of navto items. Each - * item gives a symbol that matched the search term. - */ + /** + * The symbol's name. + */ + name: string; + + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + + /** + * exact, substring, or prefix. + */ + matchKind?: string; + + /** + * If this was a case sensitive or insensitive match. + */ + isCaseSensitive?: boolean; + + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + + /** + * The file in which the symbol is found. + */ + file: string; + + /** + * The location within file at which the symbol is found. + */ + start: Location; + + /** + * One past the last character of the symbol. + */ + end: Location; + + /** + * Name of symbol's container symbol (if any); for example, + * the class name if symbol is a class member. + */ + containerName?: string; + + /** + * Kind of symbol's container symbol (if any). + */ + containerKind?: string; +} + +/** + * Navto response message. Body is an array of navto items. Each + * item gives a symbol that matched the search term. + */ export interface NavtoResponse extends Response { - body?: NavtoItem[]; + body?: NavtoItem[]; } /** - * Arguments for change request message. - */ + * Arguments for change request message. + */ export interface ChangeRequestArgs extends FormatRequestArgs { - /** - * Optional string to insert at location (file, line, offset). - */ - insertString?: string; + /** + * Optional string to insert at location (file, line, offset). + */ + insertString?: string; } /** - * Change request message; value of command field is "change". - * Update the server's view of the file named by argument 'file'. - * Server does not currently send a response to a change request. - */ + * Change request message; value of command field is "change". + * Update the server's view of the file named by argument 'file'. + * Server does not currently send a response to a change request. + */ export interface ChangeRequest extends FileLocationRequest { - arguments: ChangeRequestArgs; + arguments: ChangeRequestArgs; } /** - * Response to "brace" request. - */ + * Response to "brace" request. + */ export interface BraceResponse extends Response { - body?: TextSpan[]; + body?: TextSpan[]; } /** - * Brace matching request; value of command field is "brace". - * Return response giving the file locations of matching braces - * found in file at location line, offset. - */ + * Brace matching request; value of command field is "brace". + * Return response giving the file locations of matching braces + * found in file at location line, offset. + */ export interface BraceRequest extends FileLocationRequest { } /** - * NavBar items request; value of command field is "navbar". - * Return response giving the list of navigation bar entries - * extracted from the requested file. - */ + * NavBar items request; value of command field is "navbar". + * Return response giving the list of navigation bar entries + * extracted from the requested file. + */ export interface NavBarRequest extends FileRequest { } export interface NavigationBarItem { - /** - * The item's display text. - */ - text: string; + /** + * The item's display text. + */ + text: string; - /** - * The symbol's kind (such as 'className' or 'parameterName'). - */ - kind: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers?: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; - /** - * The definition locations of the item. - */ - spans: TextSpan[]; + /** + * The definition locations of the item. + */ + spans: TextSpan[]; - /** - * Optional children. - */ - childItems?: NavigationBarItem[]; + /** + * Optional children. + */ + childItems?: NavigationBarItem[]; - /** - * Number of levels deep this item should appear. - */ - indent: number; + /** + * Number of levels deep this item should appear. + */ + indent: number; } export interface NavBarResponse extends Response { - body?: NavigationBarItem[]; + body?: NavigationBarItem[]; } \ No newline at end of file diff --git a/extensions/typescript/src/typescriptMain.ts b/extensions/typescript/src/typescriptMain.ts index c57ddb0286294..2e4c1255f7720 100644 --- a/extensions/typescript/src/typescriptMain.ts +++ b/extensions/typescript/src/typescriptMain.ts @@ -14,7 +14,7 @@ import { env, languages, commands, workspace, window, Uri, ExtensionContext, Mem // This must be the first statement otherwise modules might got loaded with // the wrong locale. import * as nls from 'vscode-nls'; -nls.config({locale: env.language}); +nls.config({ locale: env.language }); import * as path from 'path'; @@ -350,7 +350,7 @@ class TypeScriptServiceClientHost implements ITypescriptServiceClientHost { } } if (Is.defined(body.queueLength)) { - BuildStatus.update( { queueLength: body.queueLength }); + BuildStatus.update({ queueLength: body.queueLength }); } } diff --git a/extensions/typescript/src/typescriptService.ts b/extensions/typescript/src/typescriptService.ts index be548bc946d77..9a65195f51821 100644 --- a/extensions/typescript/src/typescriptService.ts +++ b/extensions/typescript/src/typescriptService.ts @@ -55,25 +55,25 @@ export interface ITypescriptServiceClient { experimentalAutoBuild: boolean; apiVersion: APIVersion; - execute(command: 'configure', args: Proto.ConfigureRequestArguments, token?: CancellationToken):Promise; - execute(command: 'open', args: Proto.OpenRequestArgs, expectedResult:boolean, token?: CancellationToken):Promise; - execute(command: 'close', args: Proto.FileRequestArgs, expectedResult:boolean, token?: CancellationToken):Promise; - execute(command: 'change', args: Proto.ChangeRequestArgs, expectedResult:boolean, token?: CancellationToken):Promise; - execute(command: 'geterr', args: Proto.GeterrRequestArgs, expectedResult:boolean, token?: CancellationToken):Promise; - execute(command: 'quickinfo', args: Proto.FileLocationRequestArgs, token?: CancellationToken):Promise; - execute(command: 'completions', args: Proto.CompletionsRequestArgs, token?: CancellationToken):Promise; - execute(commant: 'completionEntryDetails', args: Proto.CompletionDetailsRequestArgs, token?: CancellationToken):Promise; - execute(commant: 'signatureHelp', args: Proto.SignatureHelpRequestArgs, token?: CancellationToken):Promise; - execute(command: 'definition', args: Proto.FileLocationRequestArgs, token?: CancellationToken):Promise; - execute(command: 'references', args: Proto.FileLocationRequestArgs, token?: CancellationToken):Promise; - execute(command: 'navto', args: Proto.NavtoRequestArgs, token?: CancellationToken):Promise; - execute(command: 'navbar', args: Proto.FileRequestArgs, token?: CancellationToken):Promise; - execute(command: 'format', args: Proto.FormatRequestArgs, token?: CancellationToken):Promise; - execute(command: 'formatonkey', args: Proto.FormatOnKeyRequestArgs, token?: CancellationToken):Promise; + execute(command: 'configure', args: Proto.ConfigureRequestArguments, token?: CancellationToken): Promise; + execute(command: 'open', args: Proto.OpenRequestArgs, expectedResult: boolean, token?: CancellationToken): Promise; + execute(command: 'close', args: Proto.FileRequestArgs, expectedResult: boolean, token?: CancellationToken): Promise; + execute(command: 'change', args: Proto.ChangeRequestArgs, expectedResult: boolean, token?: CancellationToken): Promise; + execute(command: 'geterr', args: Proto.GeterrRequestArgs, expectedResult: boolean, token?: CancellationToken): Promise; + execute(command: 'quickinfo', args: Proto.FileLocationRequestArgs, token?: CancellationToken): Promise; + execute(command: 'completions', args: Proto.CompletionsRequestArgs, token?: CancellationToken): Promise; + execute(commant: 'completionEntryDetails', args: Proto.CompletionDetailsRequestArgs, token?: CancellationToken): Promise; + execute(commant: 'signatureHelp', args: Proto.SignatureHelpRequestArgs, token?: CancellationToken): Promise; + execute(command: 'definition', args: Proto.FileLocationRequestArgs, token?: CancellationToken): Promise; + execute(command: 'references', args: Proto.FileLocationRequestArgs, token?: CancellationToken): Promise; + execute(command: 'navto', args: Proto.NavtoRequestArgs, token?: CancellationToken): Promise; + execute(command: 'navbar', args: Proto.FileRequestArgs, token?: CancellationToken): Promise; + execute(command: 'format', args: Proto.FormatRequestArgs, token?: CancellationToken): Promise; + execute(command: 'formatonkey', args: Proto.FormatOnKeyRequestArgs, token?: CancellationToken): Promise; execute(command: 'rename', args: Proto.RenameRequestArgs, token?: CancellationToken): Promise; execute(command: 'occurrences', args: Proto.FileLocationRequestArgs, token?: CancellationToken): Promise; execute(command: 'projectInfo', args: Proto.ProjectInfoRequestArgs, token?: CancellationToken): Promise; - execute(command: 'reloadProjects', args: any, expectedResult:boolean, token?: CancellationToken): Promise; + execute(command: 'reloadProjects', args: any, expectedResult: boolean, token?: CancellationToken): Promise; execute(command: 'reload', args: Proto.ReloadRequestArgs, expectedResult: boolean, token?: CancellationToken): Promise; execute(command: string, args: any, expectedResult: boolean | CancellationToken, token?: CancellationToken): Promise; } \ No newline at end of file diff --git a/extensions/typescript/src/typescriptServiceClient.ts b/extensions/typescript/src/typescriptServiceClient.ts index 0d2d4d8ca3368..2893d4738cd9f 100644 --- a/extensions/typescript/src/typescriptServiceClient.ts +++ b/extensions/typescript/src/typescriptServiceClient.ts @@ -12,9 +12,9 @@ import * as fs from 'fs'; import * as electron from './utils/electron'; import { Reader } from './utils/wireProtocol'; -import { workspace, window, Uri, CancellationToken, OutputChannel, Memento, MessageItem } from 'vscode'; +import { workspace, window, Uri, CancellationToken, OutputChannel, Memento, MessageItem } from 'vscode'; import * as Proto from './protocol'; -import { ITypescriptServiceClient, ITypescriptServiceClientHost, APIVersion } from './typescriptService'; +import { ITypescriptServiceClient, ITypescriptServiceClientHost, APIVersion } from './typescriptService'; import * as VersionStatus from './utils/versionStatus'; import * as is from './utils/is'; @@ -73,7 +73,7 @@ enum MessageAction { close } -interface MyMessageItem extends MessageItem { +interface MyMessageItem extends MessageItem { id: MessageAction; } @@ -261,7 +261,7 @@ export default class TypeScriptServiceClient implements ITypescriptServiceClient return this._packageInfo; } - public logTelemetry(eventName: string, properties?: {[prop: string]: string}) { + public logTelemetry(eventName: string, properties?: { [prop: string]: string }) { if (this.telemetryReporter) { this.telemetryReporter.sendTelemetryEvent(eventName, properties); } @@ -337,7 +337,7 @@ export default class TypeScriptServiceClient implements ITypescriptServiceClient if (!selected || selected.id === MessageAction.close) { return modulePath; } - switch(selected.id) { + switch (selected.id) { case MessageAction.useLocal: let pathValue = './node_modules/typescript/lib'; tsConfig.update('tsdk', pathValue, false); @@ -381,7 +381,7 @@ export default class TypeScriptServiceClient implements ITypescriptServiceClient } - const label = version || localize('versionNumber.custom' ,'custom'); + const label = version || localize('versionNumber.custom', 'custom'); const tooltip = modulePath; VersionStatus.enable(!!this.tsdk || showVersionStatusItem); VersionStatus.setInfo(label, tooltip); @@ -459,7 +459,7 @@ export default class TypeScriptServiceClient implements ITypescriptServiceClient this.lastError = err; this.error('Starting TSServer failed with error.', err); window.showErrorMessage(localize('serverCouldNotBeStarted', 'TypeScript language server couldn\'t be started. Error message is: {0}', err.message || err)); - this.logTelemetry('error', {message: err.message}); + this.logTelemetry('error', { message: err.message }); return; } this.lastStart = Date.now(); @@ -494,7 +494,7 @@ export default class TypeScriptServiceClient implements ITypescriptServiceClient if (this._experimentalAutoBuild && this.storagePath) { try { fs.mkdirSync(this.storagePath); - } catch(error) { + } catch (error) { } this.execute('configure', { autoBuild: true, @@ -521,7 +521,7 @@ export default class TypeScriptServiceClient implements ITypescriptServiceClient let desc = null; try { desc = JSON.parse(contents); - } catch(err) { + } catch (err) { return undefined; } if (!desc.version) { @@ -542,7 +542,7 @@ export default class TypeScriptServiceClient implements ITypescriptServiceClient let startService = true; if (this.numberRestarts > 5) { if (diff < 60 * 1000 /* 1 Minutes */) { - window.showWarningMessage(localize('serverDied','The TypeScript language service died unexpectedly 5 times in the last 5 Minutes. Please consider to open a bug report.')); + window.showWarningMessage(localize('serverDied', 'The TypeScript language service died unexpectedly 5 times in the last 5 Minutes. Please consider to open a bug report.')); } else if (diff < 2 * 1000 /* 2 seconds */) { startService = false; window.showErrorMessage(localize('serverDiedAfterStart', 'The TypeScript language service died 5 times right after it got started. The service will not be restarted. Please open a bug report.')); diff --git a/extensions/typescript/src/typings/vscode-extension-telemetry.d.ts b/extensions/typescript/src/typings/vscode-extension-telemetry.d.ts index 4b2981b9b24be..f6177ef27a652 100644 --- a/extensions/typescript/src/typings/vscode-extension-telemetry.d.ts +++ b/extensions/typescript/src/typings/vscode-extension-telemetry.d.ts @@ -1,6 +1,6 @@ declare module 'vscode-extension-telemetry' { export default class TelemetryReporter { - constructor(extensionId: string,extensionVersion: string, key: string); + constructor(extensionId: string, extensionVersion: string, key: string); sendTelemetryEvent(eventName: string, properties?: { [key: string]: string }, measures?: { [key: string]: number }): void; } } \ No newline at end of file diff --git a/extensions/typescript/src/utils/electron.ts b/extensions/typescript/src/utils/electron.ts index c0bda301689c8..847c7a098bcf8 100644 --- a/extensions/typescript/src/utils/electron.ts +++ b/extensions/typescript/src/utils/electron.ts @@ -17,7 +17,7 @@ export interface IForkOptions { execArgv?: string[]; } -function makeRandomHexString(length:number): string { +function makeRandomHexString(length: number): string { let chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; let result = ''; for (let i = 0; i < length; i++) { @@ -37,10 +37,10 @@ function generatePipeName(): string { return path.join(os.tmpdir(), randomName + '.sock'); } -function generatePatchedEnv(env:any, stdInPipeName:string, stdOutPipeName:string, stdErrPipeName:string): any { +function generatePatchedEnv(env: any, stdInPipeName: string, stdOutPipeName: string, stdErrPipeName: string): any { // Set the two unique pipe names and the electron flag as process env - var newEnv:any = {}; + var newEnv: any = {}; for (var key in env) { newEnv[key] = env[key]; } @@ -53,7 +53,7 @@ function generatePatchedEnv(env:any, stdInPipeName:string, stdOutPipeName:string return newEnv; } -export function fork(modulePath: string, args: string[], options: IForkOptions, callback:(error:any, cp:cp.ChildProcess)=>void): void { +export function fork(modulePath: string, args: string[], options: IForkOptions, callback: (error: any, cp: cp.ChildProcess) => void): void { var callbackCalled = false; var resolve = (result: cp.ChildProcess) => { @@ -63,7 +63,7 @@ export function fork(modulePath: string, args: string[], options: IForkOptions, callbackCalled = true; callback(null, result); }; - var reject = (err:any) => { + var reject = (err: any) => { if (callbackCalled) { return; } @@ -92,7 +92,7 @@ export function fork(modulePath: string, args: string[], options: IForkOptions, let stdOutServer = net.createServer((stdOutStream) => { // The child process will write exactly one chunk with content `ready` when it has installed a listener to the stdin pipe - stdOutStream.once('data', (chunk:Buffer) => { + stdOutStream.once('data', (chunk: Buffer) => { // The child process is sending me the `ready` chunk, time to connect to the stdin pipe childProcess.stdin = net.connect(stdInPipeName); @@ -123,12 +123,12 @@ export function fork(modulePath: string, args: string[], options: IForkOptions, execArgv: options.execArgv }); - childProcess.once('error', (err:Error) => { + childProcess.once('error', (err: Error) => { closeServer(); reject(err); }); - childProcess.once('exit', (err:Error) => { + childProcess.once('exit', (err: Error) => { closeServer(); reject(err); }); diff --git a/extensions/typescript/src/utils/electronForkStart.ts b/extensions/typescript/src/utils/electronForkStart.ts index 83f757240023b..f374ada0086bc 100644 --- a/extensions/typescript/src/utils/electronForkStart.ts +++ b/extensions/typescript/src/utils/electronForkStart.ts @@ -8,9 +8,9 @@ var net = require('net'), var ENABLE_LOGGING = false; -var log = (function() { +var log = (function () { if (!ENABLE_LOGGING) { - return function() {}; + return function () { }; } var isFirst = true; var LOG_LOCATION = 'C:\\stdFork.log'; @@ -34,7 +34,7 @@ log('STDERR_PIPE_NAME: ' + stdErrPipeName); log('ELECTRON_RUN_AS_NODE: ' + process.env['ELECTRON_RUN_AS_NODE']); // stdout redirection to named pipe -(function() { +(function () { log('Beginning stdout redirection...'); // Create a writing stream to the stdout pipe @@ -44,7 +44,7 @@ log('ELECTRON_RUN_AS_NODE: ' + process.env['ELECTRON_RUN_AS_NODE']); stdOutStream.unref(); // handle process.stdout - (process).__defineGetter__('stdout', function() { return stdOutStream; }); + (process).__defineGetter__('stdout', function () { return stdOutStream; }); // Create a writing stream to the stderr pipe var stdErrStream = net.connect(stdErrPipeName); @@ -53,15 +53,15 @@ log('ELECTRON_RUN_AS_NODE: ' + process.env['ELECTRON_RUN_AS_NODE']); stdErrStream.unref(); // handle process.stderr - (process).__defineGetter__('stderr', function() { return stdErrStream; }); + (process).__defineGetter__('stderr', function () { return stdErrStream; }); - var fsWriteSyncString = function(fd, str, position, encoding) { + var fsWriteSyncString = function (fd, str, position, encoding) { // fs.writeSync(fd, string[, position[, encoding]]); var buf = new Buffer(str, encoding || 'utf8'); return fsWriteSyncBuffer(fd, buf, 0, buf.length); }; - var fsWriteSyncBuffer = function(fd, buffer, off, len) { + var fsWriteSyncBuffer = function (fd, buffer, off, len) { off = Math.abs(off | 0); len = Math.abs(len | 0); @@ -97,7 +97,7 @@ log('ELECTRON_RUN_AS_NODE: ' + process.env['ELECTRON_RUN_AS_NODE']); // handle fs.writeSync(1, ...) var originalWriteSync = fs.writeSync; - fs.writeSync = function(fd, data, position, encoding) { + fs.writeSync = function (fd, data, position, encoding) { if (fd !== 1 || fd !== 2) { return originalWriteSync.apply(fs, arguments); } @@ -122,17 +122,17 @@ log('ELECTRON_RUN_AS_NODE: ' + process.env['ELECTRON_RUN_AS_NODE']); })(); // stdin redirection to named pipe -(function() { +(function () { // Begin listening to stdin pipe - var server = net.createServer(function(stream) { + var server = net.createServer(function (stream) { // Stop accepting new connections, keep the existing one alive server.close(); log('Parent process has connected to my stdin. All should be good now.'); // handle process.stdin - (process).__defineGetter__('stdin', function() { + (process).__defineGetter__('stdin', function () { return stream; }); @@ -154,7 +154,7 @@ log('ELECTRON_RUN_AS_NODE: ' + process.env['ELECTRON_RUN_AS_NODE']); log('Finished loading program.'); var stdinIsReferenced = true; - var timer = setInterval(function() { + var timer = setInterval(function () { var listenerCount = ( stream.listeners('data').length + stream.listeners('end').length + @@ -190,7 +190,7 @@ log('ELECTRON_RUN_AS_NODE: ' + process.env['ELECTRON_RUN_AS_NODE']); }); - server.listen(stdInPipeName, function() { + server.listen(stdInPipeName, function () { // signal via stdout that the parent process can now begin writing to stdin pipe process.stdout.write('ready'); }); diff --git a/extensions/typescript/src/utils/projectStatus.ts b/extensions/typescript/src/utils/projectStatus.ts index b58fbf0a0e3df..0a177bb65b369 100644 --- a/extensions/typescript/src/utils/projectStatus.ts +++ b/extensions/typescript/src/utils/projectStatus.ts @@ -6,10 +6,10 @@ 'use strict'; import * as vscode from 'vscode'; -import {ITypescriptServiceClient} from '../typescriptService'; -import {loadMessageBundle} from 'vscode-nls'; -import {dirname, join} from 'path'; -import {exists} from 'fs'; +import { ITypescriptServiceClient } from '../typescriptService'; +import { loadMessageBundle } from 'vscode-nls'; +import { dirname, join } from 'path'; +import { exists } from 'fs'; const localize = loadMessageBundle(); const selector = ['javascript', 'javascriptreact']; @@ -25,7 +25,7 @@ interface Hint { const fileLimit = 500; -export function create(client: ITypescriptServiceClient, isOpen:(path:string)=>Promise, memento: vscode.Memento) { +export function create(client: ITypescriptServiceClient, isOpen: (path: string) => Promise, memento: vscode.Memento) { const toDispose: vscode.Disposable[] = []; const projectHinted: { [k: string]: boolean } = Object.create(null); @@ -157,7 +157,7 @@ export function create(client: ITypescriptServiceClient, isOpen:(path:string)=>P return vscode.Disposable.from(...toDispose); } -function computeLargeRoots(configFileName:string, fileNames: string[]): string[] { +function computeLargeRoots(configFileName: string, fileNames: string[]): string[] { let roots: { [first: string]: number } = Object.create(null); let dir = dirname(configFileName); diff --git a/extensions/typescript/src/utils/wireProtocol.ts b/extensions/typescript/src/utils/wireProtocol.ts index 5dad22dabb80d..7d554d3cced60 100644 --- a/extensions/typescript/src/utils/wireProtocol.ts +++ b/extensions/typescript/src/utils/wireProtocol.ts @@ -7,25 +7,25 @@ import stream = require('stream'); -let DefaultSize:number = 8192; -let ContentLength:string = 'Content-Length: '; -let ContentLengthSize:number = Buffer.byteLength(ContentLength, 'utf8'); -let Blank:number = new Buffer(' ', 'utf8')[0]; -let BackslashR:number = new Buffer('\r', 'utf8')[0]; -let BackslashN:number = new Buffer('\n', 'utf8')[0]; +let DefaultSize: number = 8192; +let ContentLength: string = 'Content-Length: '; +let ContentLengthSize: number = Buffer.byteLength(ContentLength, 'utf8'); +let Blank: number = new Buffer(' ', 'utf8')[0]; +let BackslashR: number = new Buffer('\r', 'utf8')[0]; +let BackslashN: number = new Buffer('\n', 'utf8')[0]; class ProtocolBuffer { - private index:number; - private buffer:Buffer; + private index: number; + private buffer: Buffer; constructor() { this.index = 0; this.buffer = new Buffer(DefaultSize); } - public append(data:string | Buffer):void { - let toAppend:Buffer = null; + public append(data: string | Buffer): void { + let toAppend: Buffer = null; if (Buffer.isBuffer(data)) { toAppend = data; } else { @@ -42,10 +42,10 @@ class ProtocolBuffer { this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize); } } - this.index+= toAppend.length; + this.index += toAppend.length; } - public tryReadContentLength():number { + public tryReadContentLength(): number { let result = -1; let current = 0; // we are utf8 encoding... @@ -57,7 +57,7 @@ class ProtocolBuffer { } current += ContentLengthSize; let start = current; - while(current < this.index && this.buffer[current] !== BackslashR) { + while (current < this.index && this.buffer[current] !== BackslashR) { current++; } if (current + 3 >= this.index || this.buffer[current + 1] !== BackslashN || this.buffer[current + 2] !== BackslashR || this.buffer[current + 3] !== BackslashN) { @@ -70,13 +70,13 @@ class ProtocolBuffer { return result; } - public tryReadContent(length:number):string { + public tryReadContent(length: number): string { if (this.index < length) { return null; } let result = this.buffer.toString('utf8', 0, length); let sourceStart = length; - while(sourceStart < this.index && (this.buffer[sourceStart] === BackslashR || this.buffer[sourceStart] === BackslashN)) { + while (sourceStart < this.index && (this.buffer[sourceStart] === BackslashR || this.buffer[sourceStart] === BackslashN)) { sourceStart++; } this.buffer.copy(this.buffer, 0, sourceStart); @@ -84,8 +84,8 @@ class ProtocolBuffer { return result; } - public tryReadLine():string { - let end:number = 0; + public tryReadLine(): string { + let end: number = 0; while (end < this.index && this.buffer[end] !== BackslashR && this.buffer[end] !== BackslashN) { end++; } @@ -105,7 +105,7 @@ class ProtocolBuffer { return result; } - public get numberOfBytes():number { + public get numberOfBytes(): number { return this.index; } } @@ -116,35 +116,35 @@ export enum ReaderType { } export interface ICallback { - (data:T):void; + (data: T): void; } export class Reader { - private readable:stream.Readable; - private callback:ICallback; - private buffer:ProtocolBuffer; - private nextMessageLength:number; + private readable: stream.Readable; + private callback: ICallback; + private buffer: ProtocolBuffer; + private nextMessageLength: number; - public constructor(readable:stream.Readable, callback:ICallback, type:ReaderType = ReaderType.Length) { + public constructor(readable: stream.Readable, callback: ICallback, type: ReaderType = ReaderType.Length) { this.readable = readable; this.buffer = new ProtocolBuffer(); this.callback = callback; this.nextMessageLength = -1; if (type === ReaderType.Length) { - this.readable.on('data', (data:Buffer) => { + this.readable.on('data', (data: Buffer) => { this.onLengthData(data); }); } else if (type === ReaderType.Line) { - this.readable.on('data', (data:Buffer) => { + this.readable.on('data', (data: Buffer) => { this.onLineData(data); }); } } - private onLengthData(data:Buffer):void { + private onLengthData(data: Buffer): void { this.buffer.append(data); - while(true) { + while (true) { if (this.nextMessageLength === -1) { this.nextMessageLength = this.buffer.tryReadContentLength(); if (this.nextMessageLength === -1) { @@ -161,9 +161,9 @@ export class Reader { } } - private onLineData(data:Buffer):void { + private onLineData(data: Buffer): void { this.buffer.append(data); - while(true) { + while (true) { let msg = this.buffer.tryReadLine(); if (msg === null) { return; @@ -175,15 +175,15 @@ export class Reader { export class Writer { - private writable:stream.Writable; + private writable: stream.Writable; - public constructor(writable:stream.Writable) { + public constructor(writable: stream.Writable) { this.writable = writable; } - public write(msg:T):void { + public write(msg: T): void { let json = JSON.stringify(msg); - let buffer:string[] = [ + let buffer: string[] = [ ContentLength, Buffer.byteLength(json, 'utf8').toString(), '\r\n\r\n', diff --git a/extensions/typescript/typings/mocha.d.ts b/extensions/typescript/typings/mocha.d.ts index 7b23f5d181642..f677473dcdd76 100644 --- a/extensions/typescript/typings/mocha.d.ts +++ b/extensions/typescript/typings/mocha.d.ts @@ -5,9 +5,9 @@ declare function run(): void; -declare function suite(name: string, fn: (err?)=>void); -declare function test(name: string, fn: (done?: (err?)=>void)=>void); -declare function suiteSetup(fn: (done?: (err?)=>void)=>void); -declare function suiteTeardown(fn: (done?: (err?)=>void)=>void); -declare function setup(fn: (done?: (err?)=>void)=>void); -declare function teardown(fn: (done?: (err?)=>void)=>void); +declare function suite(name: string, fn: (err?) => void); +declare function test(name: string, fn: (done?: (err?) => void) => void); +declare function suiteSetup(fn: (done?: (err?) => void) => void); +declare function suiteTeardown(fn: (done?: (err?) => void) => void); +declare function setup(fn: (done?: (err?) => void) => void); +declare function teardown(fn: (done?: (err?) => void) => void); diff --git a/extensions/vscode-api-tests/src/commands.test.ts b/extensions/vscode-api-tests/src/commands.test.ts index 3880094bd014b..0e1cfdd1fa77d 100644 --- a/extensions/vscode-api-tests/src/commands.test.ts +++ b/extensions/vscode-api-tests/src/commands.test.ts @@ -6,12 +6,12 @@ 'use strict'; import * as assert from 'assert'; -import {join} from 'path'; -import {commands, workspace, window, Uri, ViewColumn} from 'vscode'; +import { join } from 'path'; +import { commands, workspace, window, Uri, ViewColumn } from 'vscode'; suite('commands namespace tests', () => { - test('getCommands', function(done) { + test('getCommands', function (done) { let p1 = commands.getCommands().then(commands => { let hasOneWithUnderscore = false; @@ -43,7 +43,7 @@ suite('commands namespace tests', () => { test('command with args', function () { let args: IArguments; - let registration = commands.registerCommand('t1', function() { + let registration = commands.registerCommand('t1', function () { args = arguments; }); @@ -59,7 +59,7 @@ suite('commands namespace tests', () => { test('editorCommand with extra args', function () { let args: IArguments; - let registration = commands.registerTextEditorCommand('t1', function() { + let registration = commands.registerTextEditorCommand('t1', function () { args = arguments; }); diff --git a/extensions/vscode-api-tests/src/editor.test.ts b/extensions/vscode-api-tests/src/editor.test.ts index 6cf498ee9c942..9aef53e053793 100644 --- a/extensions/vscode-api-tests/src/editor.test.ts +++ b/extensions/vscode-api-tests/src/editor.test.ts @@ -6,14 +6,14 @@ 'use strict'; import * as assert from 'assert'; -import {workspace, window, Position, Range, commands} from 'vscode'; -import {createRandomFile, deleteFile, cleanUp} from './utils'; +import { workspace, window, Position, Range, commands } from 'vscode'; +import { createRandomFile, deleteFile, cleanUp } from './utils'; suite('editor tests', () => { teardown(cleanUp); - function withRandomFileEditor(initialContents:string, run:(editor:vscode.TextEditor, doc:vscode.TextDocument)=>Thenable): Thenable { + function withRandomFileEditor(initialContents: string, run: (editor: vscode.TextEditor, doc: vscode.TextDocument) => Thenable): Thenable { return createRandomFile(initialContents).then(file => { return workspace.openTextDocument(file).then(doc => { return window.showTextDocument(doc).then((editor) => { @@ -57,7 +57,7 @@ suite('editor tests', () => { }); }); - function executeReplace(editor:vscode.TextEditor, range:Range, text:string, undoStopBefore:boolean, undoStopAfter: boolean): Thenable { + function executeReplace(editor: vscode.TextEditor, range: Range, text: string, undoStopBefore: boolean, undoStopAfter: boolean): Thenable { return editor.edit((builder) => { builder.replace(range, text); }, { undoStopBefore: undoStopBefore, undoStopAfter: undoStopAfter }); diff --git a/extensions/vscode-api-tests/src/env.test.ts b/extensions/vscode-api-tests/src/env.test.ts index 657b559b5d258..4746255297c2c 100644 --- a/extensions/vscode-api-tests/src/env.test.ts +++ b/extensions/vscode-api-tests/src/env.test.ts @@ -6,18 +6,18 @@ 'use strict'; import * as assert from 'assert'; -import {env} from 'vscode'; +import { env } from 'vscode'; suite('env-namespace', () => { - test('env is set', function() { + test('env is set', function () { assert.equal(typeof env.language, 'string'); assert.equal(typeof env.appName, 'string'); assert.equal(typeof env.machineId, 'string'); assert.equal(typeof env.sessionId, 'string'); }); - test('env is readonly', function() { + test('env is readonly', function () { assert.throws(() => env.language = '234'); assert.throws(() => env.appName = '234'); assert.throws(() => env.machineId = '234'); diff --git a/extensions/vscode-api-tests/src/index.ts b/extensions/vscode-api-tests/src/index.ts index 9147c17154659..984d15dafc5b5 100644 --- a/extensions/vscode-api-tests/src/index.ts +++ b/extensions/vscode-api-tests/src/index.ts @@ -25,4 +25,4 @@ testRunner.configure({ timeout: 10000 }); -export= testRunner; \ No newline at end of file +export = testRunner; \ No newline at end of file diff --git a/extensions/vscode-api-tests/src/languages.test.ts b/extensions/vscode-api-tests/src/languages.test.ts index 4ffb3b1afc7e4..7864899d20aef 100644 --- a/extensions/vscode-api-tests/src/languages.test.ts +++ b/extensions/vscode-api-tests/src/languages.test.ts @@ -6,9 +6,11 @@ 'use strict'; import * as assert from 'assert'; -import {join} from 'path'; -import {languages, workspace, commands, Uri, Diagnostic, Range, Command, Disposable, CancellationToken, - CompletionList, CompletionItem, CompletionItemKind, TextDocument, Position} from 'vscode'; +import { join } from 'path'; +import { + languages, workspace, commands, Uri, Diagnostic, Range, Command, Disposable, CancellationToken, + CompletionList, CompletionItem, CompletionItemKind, TextDocument, Position +} from 'vscode'; suite('languages namespace tests', () => { @@ -76,7 +78,7 @@ suite('languages namespace tests', () => { let proposal = new CompletionItem('foo'); proposal.kind = CompletionItemKind.Property; ran = true; - return [ proposal ]; + return [proposal]; } }); diff --git a/extensions/vscode-api-tests/src/utils.ts b/extensions/vscode-api-tests/src/utils.ts index ea2e3406edd25..d3c755d1cb239 100644 --- a/extensions/vscode-api-tests/src/utils.ts +++ b/extensions/vscode-api-tests/src/utils.ts @@ -9,7 +9,7 @@ import * as assert from 'assert'; import * as vscode from 'vscode'; import * as fs from 'fs'; import * as os from 'os'; -import {join} from 'path'; +import { join } from 'path'; function rndName() { return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 10); diff --git a/extensions/vscode-api-tests/src/window.test.ts b/extensions/vscode-api-tests/src/window.test.ts index 3a5fbb41ab3fa..dab141acd20d0 100644 --- a/extensions/vscode-api-tests/src/window.test.ts +++ b/extensions/vscode-api-tests/src/window.test.ts @@ -6,9 +6,9 @@ 'use strict'; import * as assert from 'assert'; -import {workspace, window, commands, ViewColumn, TextEditorViewColumnChangeEvent, Uri, Selection, Position, CancellationTokenSource, TextEditorSelectionChangeKind} from 'vscode'; -import {join} from 'path'; -import {cleanUp, pathEquals} from './utils'; +import { workspace, window, commands, ViewColumn, TextEditorViewColumnChangeEvent, Uri, Selection, Position, CancellationTokenSource, TextEditorSelectionChangeKind } from 'vscode'; +import { join } from 'path'; +import { cleanUp, pathEquals } from './utils'; suite('window namespace tests', () => { @@ -88,7 +88,7 @@ suite('window namespace tests', () => { const file30Path = join(workspace.rootPath, './30linefile.ts'); let finished = false; - let failOncePlease = (err:Error) => { + let failOncePlease = (err: Error) => { if (finished) { return; } @@ -127,13 +127,13 @@ suite('window namespace tests', () => { workspace.openTextDocument(file10Path).then((doc) => { return window.showTextDocument(doc, ViewColumn.One); }).then((editor10line) => { - editor10line.selection = new Selection(new Position(9,0), new Position(9, 0)); + editor10line.selection = new Selection(new Position(9, 0), new Position(9, 0)); }).then(() => { return workspace.openTextDocument(file30Path); }).then((doc) => { return window.showTextDocument(doc, ViewColumn.One); }).then((editor30line) => { - editor30line.selection = new Selection(new Position(29,0), new Position(29, 0)); + editor30line.selection = new Selection(new Position(29, 0), new Position(29, 0)); }).then(() => { return workspace.openTextDocument(file10Path); }).then((doc) => { diff --git a/extensions/vscode-api-tests/src/workspace.test.ts b/extensions/vscode-api-tests/src/workspace.test.ts index 3ec3b3d5046a6..37c0f9e3f4f2e 100644 --- a/extensions/vscode-api-tests/src/workspace.test.ts +++ b/extensions/vscode-api-tests/src/workspace.test.ts @@ -6,9 +6,9 @@ 'use strict'; import * as assert from 'assert'; -import {workspace, TextDocument, window, Position, Uri, EventEmitter, WorkspaceEdit} from 'vscode'; -import {createRandomFile, deleteFile, cleanUp, pathEquals} from './utils'; -import {join, basename} from 'path'; +import { workspace, TextDocument, window, Position, Uri, EventEmitter, WorkspaceEdit } from 'vscode'; +import { createRandomFile, deleteFile, cleanUp, pathEquals } from './utils'; +import { join, basename } from 'path'; import * as fs from 'fs'; suite('workspace-namespace', () => { @@ -38,7 +38,7 @@ suite('workspace-namespace', () => { assert.ok(config.has('get')); assert.equal(config.get('get'), 'get-prop'); assert.deepEqual(config['get'], config.get); - assert.throws(() => config['get'] = 'get-prop'); + assert.throws(() => config['get'] = 'get-prop'); }); // test('configuration, getConfig/value', () => { diff --git a/extensions/vscode-api-tests/typings/mocha.d.ts b/extensions/vscode-api-tests/typings/mocha.d.ts index 7b23f5d181642..f677473dcdd76 100644 --- a/extensions/vscode-api-tests/typings/mocha.d.ts +++ b/extensions/vscode-api-tests/typings/mocha.d.ts @@ -5,9 +5,9 @@ declare function run(): void; -declare function suite(name: string, fn: (err?)=>void); -declare function test(name: string, fn: (done?: (err?)=>void)=>void); -declare function suiteSetup(fn: (done?: (err?)=>void)=>void); -declare function suiteTeardown(fn: (done?: (err?)=>void)=>void); -declare function setup(fn: (done?: (err?)=>void)=>void); -declare function teardown(fn: (done?: (err?)=>void)=>void); +declare function suite(name: string, fn: (err?) => void); +declare function test(name: string, fn: (done?: (err?) => void) => void); +declare function suiteSetup(fn: (done?: (err?) => void) => void); +declare function suiteTeardown(fn: (done?: (err?) => void) => void); +declare function setup(fn: (done?: (err?) => void) => void); +declare function teardown(fn: (done?: (err?) => void) => void); diff --git a/extensions/vscode-colorize-tests/src/colorizer.test.ts b/extensions/vscode-colorize-tests/src/colorizer.test.ts index b827742e6a6b8..d709300a8394e 100644 --- a/extensions/vscode-colorize-tests/src/colorizer.test.ts +++ b/extensions/vscode-colorize-tests/src/colorizer.test.ts @@ -6,11 +6,11 @@ 'use strict'; import * as assert from 'assert'; -import {commands, Uri} from 'vscode'; -import {join, basename, normalize, dirname} from 'path'; +import { commands, Uri } from 'vscode'; +import { join, basename, normalize, dirname } from 'path'; import * as fs from 'fs'; -function assertUnchangedTokens(testFixurePath:string, done) { +function assertUnchangedTokens(testFixurePath: string, done) { let fileName = basename(testFixurePath); return commands.executeCommand('_workbench.captureSyntaxTokens', Uri.file(testFixurePath)).then(data => { @@ -47,7 +47,7 @@ suite("colorization", () => { let fixturesFiles = fs.readdirSync(extensionColorizeFixturePath); fixturesFiles.forEach(fixturesFile => { // define a test for each fixture - test(extension + '-' + fixturesFile, function(done) { + test(extension + '-' + fixturesFile, function (done) { assertUnchangedTokens(join(extensionColorizeFixturePath, fixturesFile), done); }); }); diff --git a/extensions/vscode-colorize-tests/src/index.ts b/extensions/vscode-colorize-tests/src/index.ts index 9147c17154659..984d15dafc5b5 100644 --- a/extensions/vscode-colorize-tests/src/index.ts +++ b/extensions/vscode-colorize-tests/src/index.ts @@ -25,4 +25,4 @@ testRunner.configure({ timeout: 10000 }); -export= testRunner; \ No newline at end of file +export = testRunner; \ No newline at end of file diff --git a/extensions/vscode-colorize-tests/typings/mocha.d.ts b/extensions/vscode-colorize-tests/typings/mocha.d.ts index 7b23f5d181642..f677473dcdd76 100644 --- a/extensions/vscode-colorize-tests/typings/mocha.d.ts +++ b/extensions/vscode-colorize-tests/typings/mocha.d.ts @@ -5,9 +5,9 @@ declare function run(): void; -declare function suite(name: string, fn: (err?)=>void); -declare function test(name: string, fn: (done?: (err?)=>void)=>void); -declare function suiteSetup(fn: (done?: (err?)=>void)=>void); -declare function suiteTeardown(fn: (done?: (err?)=>void)=>void); -declare function setup(fn: (done?: (err?)=>void)=>void); -declare function teardown(fn: (done?: (err?)=>void)=>void); +declare function suite(name: string, fn: (err?) => void); +declare function test(name: string, fn: (done?: (err?) => void) => void); +declare function suiteSetup(fn: (done?: (err?) => void) => void); +declare function suiteTeardown(fn: (done?: (err?) => void) => void); +declare function setup(fn: (done?: (err?) => void) => void); +declare function teardown(fn: (done?: (err?) => void) => void); diff --git a/package.json b/package.json index 98f8977c72632..e549ca5fd75a2 100644 --- a/package.json +++ b/package.json @@ -89,6 +89,7 @@ "source-map": "^0.4.4", "tslint": "^3.3.0", "typescript": "^2.0.3", + "typescript-formatter": "git+https://github.com/jrieken/typescript-formatter.git#560ea3b", "uglify-js": "2.4.8", "underscore": "^1.8.2", "vinyl": "^0.4.5", diff --git a/src/typings/ansi-regex.d.ts b/src/typings/ansi-regex.d.ts index 8e3004978066a..2bf8b8a4336db 100644 --- a/src/typings/ansi-regex.d.ts +++ b/src/typings/ansi-regex.d.ts @@ -1,5 +1,5 @@ declare module 'ansi-regex' { function result(): RegExp; - module result {} + module result { } export = result; } diff --git a/src/typings/applicationInsights.d.ts b/src/typings/applicationInsights.d.ts index eb84dd31a78ee..9f4ccb2e1d81c 100644 --- a/src/typings/applicationInsights.d.ts +++ b/src/typings/applicationInsights.d.ts @@ -3,62 +3,62 @@ * the auto-collection behavior of the application insights module. */ declare module ApplicationInsights { - var client: any; + var client: any; /** * Initializes a client with the given instrumentation key, if this is not specified, the value will be * read from the environment variable APPINSIGHTS_INSTRUMENTATIONKEY * @returns {ApplicationInsights/Client} a new client */ - function getClient(instrumentationKey?: string): any /*Client*/; + function getClient(instrumentationKey?: string): any /*Client*/; /** * Initializes the default client of the client and sets the default configuration * @param instrumentationKey the instrumentation key to use. Optional, if this is not specified, the value will be * read from the environment variable APPINSIGHTS_INSTRUMENTATIONKEY * @returns {ApplicationInsights} this class */ - function setup(instrumentationKey?: string): typeof ApplicationInsights; + function setup(instrumentationKey?: string): typeof ApplicationInsights; /** * Starts automatic collection of telemetry. Prior to calling start no telemetry will be collected * @returns {ApplicationInsights} this class */ - function start(): typeof ApplicationInsights; + function start(): typeof ApplicationInsights; /** * Sets the state of console tracking (enabled by default) * @param value if true console activity will be sent to Application Insights * @returns {ApplicationInsights} this class */ - function setAutoCollectConsole(value: boolean): typeof ApplicationInsights; + function setAutoCollectConsole(value: boolean): typeof ApplicationInsights; /** * Sets the state of exception tracking (enabled by default) * @param value if true uncaught exceptions will be sent to Application Insights * @returns {ApplicationInsights} this class */ - function setAutoCollectExceptions(value: boolean): typeof ApplicationInsights; + function setAutoCollectExceptions(value: boolean): typeof ApplicationInsights; /** * Sets the state of performance tracking (enabled by default) * @param value if true performance counters will be collected every second and sent to Application Insights * @returns {ApplicationInsights} this class */ - function setAutoCollectPerformance(value: boolean): typeof ApplicationInsights; + function setAutoCollectPerformance(value: boolean): typeof ApplicationInsights; /** * Sets the state of request tracking (enabled by default) * @param value if true requests will be sent to Application Insights * @returns {ApplicationInsights} this class */ - function setAutoCollectRequests(value: boolean): typeof ApplicationInsights; + function setAutoCollectRequests(value: boolean): typeof ApplicationInsights; - /** - * Sets the state of enabling offline mode to cache event when client is offline (disabled by default) - * @param value if true events that happen while client is offline will be cahced on disk, - * client will retry to send events when back online - * @returns {ApplicationInsights} this class - */ - function setOfflineMode(value: boolean): typeof ApplicationInsights; + /** + * Sets the state of enabling offline mode to cache event when client is offline (disabled by default) + * @param value if true events that happen while client is offline will be cahced on disk, + * client will retry to send events when back online + * @returns {ApplicationInsights} this class + */ + function setOfflineMode(value: boolean): typeof ApplicationInsights; /** * Enables verbose debug logging * @returns {ApplicationInsights} this class */ - function enableVerboseLogging(): typeof ApplicationInsights; + function enableVerboseLogging(): typeof ApplicationInsights; } declare module 'applicationinsights' { diff --git a/src/typings/electron.d.ts b/src/typings/electron.d.ts index 3422cd50039b9..330adfe080b06 100644 --- a/src/typings/electron.d.ts +++ b/src/typings/electron.d.ts @@ -432,7 +432,7 @@ declare namespace Electron { dock: Dock; } - type AppPathName = 'home'|'appData'|'userData'|'temp'|'exe'|'module'|'desktop'|'documents'|'downloads'|'music'|'pictures'|'videos'|'pepperFlashSystemPlugin'; + type AppPathName = 'home' | 'appData' | 'userData' | 'temp' | 'exe' | 'module' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'pepperFlashSystemPlugin'; interface ImportCertificateOptions { /** @@ -1653,7 +1653,7 @@ declare namespace Electron { /** * The window icon, when omitted on Windows the executable’s icon would be used as window icon. */ - icon?: NativeImage|string; + icon?: NativeImage | string; /** * Whether window should be shown when created. * Default: true. @@ -1982,7 +1982,7 @@ declare namespace Electron { * An object you can define that will be sent along with the report. * Only string properties are sent correctly, nested objects are not supported. */ - extra?: {[prop: string]: string}; + extra?: { [prop: string]: string }; } interface CrashReport { @@ -2478,7 +2478,7 @@ declare namespace Electron { * In Electron for the APIs that take images, you can pass either file paths * or NativeImage instances. When passing null, an empty image will be used. */ - icon?: NativeImage|string; + icon?: NativeImage | string; /** * If false, the menu item will be greyed out and unclickable. */ @@ -2495,7 +2495,7 @@ declare namespace Electron { * Should be specified for submenu type menu item, when it's specified the * type: 'submenu' can be omitted for the menu item */ - submenu?: Menu|MenuItemOptions[]; + submenu?: Menu | MenuItemOptions[]; /** * Unique within a single menu. If defined then it can be used as a reference * to this item by the position attribute. @@ -3620,7 +3620,7 @@ declare namespace Electron { /** * Creates a new tray icon associated with the image. */ - new(image: NativeImage|string): Tray; + new (image: NativeImage | string): Tray; /** * Destroys the tray icon immediately. */ @@ -3628,7 +3628,7 @@ declare namespace Electron { /** * Sets the image associated with this tray icon. */ - setImage(image: NativeImage|string): void; + setImage(image: NativeImage | string): void; /** * Sets the image associated with this tray icon when pressed. */ @@ -4440,7 +4440,7 @@ declare namespace Electron { */ type StopFindInPageAtion = 'clearSelection' | 'keepSelection' | 'activateSelection'; - type CursorType = 'default' | 'crosshair' | 'pointer' | 'text' | 'wait' | 'help' | 'e-resize' | 'n-resize' | 'ne-resize' | 'nw-resize' | 's-resize' | 'se-resize' | 'sw-resize' | 'w-resize' | 'ns-resize' | 'ew-resize' | 'nesw-resize' | 'nwse-resize' | 'col-resize' | 'row-resize' | 'm-panning' | 'e-panning' | 'n-panning' | 'ne-panning' | 'nw-panning' | 's-panning' | 'se-panning' |'sw-panning' | 'w-panning' | 'move' | 'vertical-text' | 'cell' | 'context-menu' | 'alias' | 'progress' | 'nodrop' | 'copy' | 'none' | 'not-allowed' | 'zoom-in' | 'zoom-out' | 'grab' | 'grabbing' | 'custom'; + type CursorType = 'default' | 'crosshair' | 'pointer' | 'text' | 'wait' | 'help' | 'e-resize' | 'n-resize' | 'ne-resize' | 'nw-resize' | 's-resize' | 'se-resize' | 'sw-resize' | 'w-resize' | 'ns-resize' | 'ew-resize' | 'nesw-resize' | 'nwse-resize' | 'col-resize' | 'row-resize' | 'm-panning' | 'e-panning' | 'n-panning' | 'ne-panning' | 'nw-panning' | 's-panning' | 'se-panning' | 'sw-panning' | 'w-panning' | 'move' | 'vertical-text' | 'cell' | 'context-menu' | 'alias' | 'progress' | 'nodrop' | 'copy' | 'none' | 'not-allowed' | 'zoom-in' | 'zoom-out' | 'grab' | 'grabbing' | 'custom'; interface LoadURLOptions { /** @@ -5256,23 +5256,23 @@ declare namespace Electron { namespace WebViewElement { type Event = ElectronPrivate.GlobalEvent; - interface LoadCommitEvent extends Event { + interface LoadCommitEvent extends Event { url: string; isMainFrame: boolean; } - interface DidFailLoadEvent extends Event { + interface DidFailLoadEvent extends Event { errorCode: number; errorDescription: string; validatedURL: string; isMainFrame: boolean; } - interface DidFrameFinishLoadEvent extends Event { + interface DidFrameFinishLoadEvent extends Event { isMainFrame: boolean; } - interface DidGetResponseDetails extends Event { + interface DidGetResponseDetails extends Event { status: boolean; newURL: string; originalURL: string; diff --git a/src/typings/gc-signals.d.ts b/src/typings/gc-signals.d.ts index cc982d1260c91..be8992af28c94 100644 --- a/src/typings/gc-signals.d.ts +++ b/src/typings/gc-signals.d.ts @@ -1,19 +1,19 @@ declare module 'gc-signals' { - export interface GCSignal { - } + export interface GCSignal { + } /** * Create a new GC signal. When being garbage collected the passed * value is stored for later consumption. */ - export const GCSignal: { - new (id: number): GCSignal; - }; + export const GCSignal: { + new (id: number): GCSignal; + }; /** * Consume ids of garbage collected signals. */ - export function consumeSignals(): number[]; - export function onDidGarbageCollectSignals(callback: (ids: number[]) => any): { - dispose(): void; - }; - export function trackGarbageCollection(obj: any, id: number): number; + export function consumeSignals(): number[]; + export function onDidGarbageCollectSignals(callback: (ids: number[]) => any): { + dispose(): void; + }; + export function trackGarbageCollection(obj: any, id: number): number; } \ No newline at end of file diff --git a/src/typings/getmac.d.ts b/src/typings/getmac.d.ts index eb869d0b892b4..e93b8135456f3 100644 --- a/src/typings/getmac.d.ts +++ b/src/typings/getmac.d.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ declare module getmac { - export function getMac(callback: (error:Error, macAddress:string)=>void): void; + export function getMac(callback: (error: Error, macAddress: string) => void): void; } declare module 'getmac' { diff --git a/src/typings/iconv-lite.d.ts b/src/typings/iconv-lite.d.ts index 15421202705c0..84c54e320cf37 100644 --- a/src/typings/iconv-lite.d.ts +++ b/src/typings/iconv-lite.d.ts @@ -6,13 +6,13 @@ /// declare module 'iconv-lite' { - export function decode(buffer: NodeBuffer, encoding:string, options?:any): string; + export function decode(buffer: NodeBuffer, encoding: string, options?: any): string; - export function encode(content:string, encoding:string, options?:any): NodeBuffer; + export function encode(content: string, encoding: string, options?: any): NodeBuffer; - export function encodingExists(encoding:string): boolean; + export function encodingExists(encoding: string): boolean; - export function decodeStream(encoding:string): NodeJS.ReadWriteStream; + export function decodeStream(encoding: string): NodeJS.ReadWriteStream; - export function encodeStream(encoding:string): NodeJS.ReadWriteStream; + export function encodeStream(encoding: string): NodeJS.ReadWriteStream; } \ No newline at end of file diff --git a/src/typings/lib.array-ext.d.ts b/src/typings/lib.array-ext.d.ts index 845139ace339a..127f64e1fd4b1 100644 --- a/src/typings/lib.array-ext.d.ts +++ b/src/typings/lib.array-ext.d.ts @@ -4,6 +4,6 @@ *--------------------------------------------------------------------------------------------*/ interface ArrayConstructor { - isArray(arg: any): arg is Array; - isArray(arg: any): arg is Array; + isArray(arg: any): arg is Array; + isArray(arg: any): arg is Array; } \ No newline at end of file diff --git a/src/typings/minimist.d.ts b/src/typings/minimist.d.ts index d455d1e755d75..d1e1a05252ac6 100644 --- a/src/typings/minimist.d.ts +++ b/src/typings/minimist.d.ts @@ -9,13 +9,13 @@ declare module 'minimist' { namespace minimist { export interface Opts { // a string or array of strings argument names to always treat as strings - string?: string|string[]; + string?: string | string[]; // a string or array of strings to always treat as booleans - boolean?: boolean|string|string[]; + boolean?: boolean | string | string[]; // an object mapping string names to strings or arrays of string argument names to use - alias?: {[key:string]: string|string[]}; + alias?: { [key: string]: string | string[] }; // an object mapping string argument names to default values - default?: {[key:string]: any}; + default?: { [key: string]: any }; // when true, populate argv._ with everything after the first non-option stopEarly?: boolean; // a function which is invoked with a command line parameter not defined in the opts configuration object. diff --git a/src/typings/mocha.d.ts b/src/typings/mocha.d.ts index 7b23f5d181642..f677473dcdd76 100644 --- a/src/typings/mocha.d.ts +++ b/src/typings/mocha.d.ts @@ -5,9 +5,9 @@ declare function run(): void; -declare function suite(name: string, fn: (err?)=>void); -declare function test(name: string, fn: (done?: (err?)=>void)=>void); -declare function suiteSetup(fn: (done?: (err?)=>void)=>void); -declare function suiteTeardown(fn: (done?: (err?)=>void)=>void); -declare function setup(fn: (done?: (err?)=>void)=>void); -declare function teardown(fn: (done?: (err?)=>void)=>void); +declare function suite(name: string, fn: (err?) => void); +declare function test(name: string, fn: (done?: (err?) => void) => void); +declare function suiteSetup(fn: (done?: (err?) => void) => void); +declare function suiteTeardown(fn: (done?: (err?) => void) => void); +declare function setup(fn: (done?: (err?) => void) => void); +declare function teardown(fn: (done?: (err?) => void) => void); diff --git a/src/typings/node.d.ts b/src/typings/node.d.ts index 6f048fdd03ed4..75e4a80521a6b 100644 --- a/src/typings/node.d.ts +++ b/src/typings/node.d.ts @@ -10,17 +10,17 @@ ************************************************/ interface Error { - stack?: string; + stack?: string; } // compat for TypeScript 1.8 // if you use with --target es3 or --target es5 and use below definitions, // use the lib.es6.d.ts that is bundled with TypeScript 1.8. -interface MapConstructor {} -interface WeakMapConstructor {} -interface SetConstructor {} -interface WeakSetConstructor {} +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } /************************************************ * * @@ -69,20 +69,20 @@ declare function clearImmediate(immediateId: any): void; // Same as module.exports declare var exports: any; declare var SlowBuffer: { - new (str: string, encoding?: string): Buffer; - new (size: number): Buffer; - new (size: Uint8Array): Buffer; - new (array: any[]): Buffer; - prototype: Buffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: Buffer[], totalLength?: number): Buffer; + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (size: Uint8Array): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; }; // Buffer class type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; -interface Buffer extends NodeBuffer {} +interface Buffer extends NodeBuffer { } /** * Raw data is stored in instances of the Buffer class. @@ -96,45 +96,45 @@ declare var Buffer: { * @param str String to store in buffer. * @param encoding encoding to use, optional. Default is 'utf8' */ - new (str: string, encoding?: string): Buffer; + new (str: string, encoding?: string): Buffer; /** * Allocates a new buffer of {size} octets. * * @param size count of octets to allocate. */ - new (size: number): Buffer; + new (size: number): Buffer; /** * Allocates a new buffer containing the given {array} of octets. * * @param array The octets to store. */ - new (array: Uint8Array): Buffer; + new (array: Uint8Array): Buffer; /** * Allocates a new buffer containing the given {array} of octets. * * @param array The octets to store. */ - new (array: any[]): Buffer; + new (array: any[]): Buffer; /** * Copies the passed {buffer} data onto a new {Buffer} instance. * * @param buffer The buffer to copy. */ - new (buffer: Buffer): Buffer; - prototype: Buffer; + new (buffer: Buffer): Buffer; + prototype: Buffer; /** * Returns true if {obj} is a Buffer * * @param obj object to test. */ - isBuffer(obj: any): obj is Buffer; + isBuffer(obj: any): obj is Buffer; /** * Returns true if {encoding} is a valid encoding argument. * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' * * @param encoding string to test. */ - isEncoding(encoding: string): boolean; + isEncoding(encoding: string): boolean; /** * Gives the actual byte length of a string. encoding defaults to 'utf8'. * This is not the same as String.prototype.length since that returns the number of characters in a string. @@ -142,7 +142,7 @@ declare var Buffer: { * @param string string to test. * @param encoding encoding used to evaluate (defaults to 'utf8') */ - byteLength(string: string, encoding?: string): number; + byteLength(string: string, encoding?: string): number; /** * Returns a buffer which is the result of concatenating all the buffers in the list together. * @@ -154,11 +154,11 @@ declare var Buffer: { * @param totalLength Total length of the buffers when concatenated. * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. */ - concat(list: Buffer[], totalLength?: number): Buffer; + concat(list: Buffer[], totalLength?: number): Buffer; /** * The same as buf1.compare(buf2). */ - compare(buf1: Buffer, buf2: Buffer): number; + compare(buf1: Buffer, buf2: Buffer): number; }; /************************************************ @@ -167,270 +167,270 @@ declare var Buffer: { * * ************************************************/ declare namespace NodeJS { - export interface ErrnoException extends Error { - errno?: number; - code?: string; - path?: string; - syscall?: string; - stack?: string; - } - - export interface EventEmitter { - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - listenerCount(type: string): number; - } - - export interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): string|Buffer; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; - wrap(oldStream: ReadableStream): ReadableStream; - } - - export interface WritableStream extends EventEmitter { - writable: boolean; - write(buffer: Buffer|string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - export interface ReadWriteStream extends ReadableStream, WritableStream {} - - export interface Events extends EventEmitter { } - - export interface Domain extends Events { - run(fn: Function): void; - add(emitter: Events): void; - remove(emitter: Events): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; - - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - } - - export interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - } - - export interface Process extends EventEmitter { - stdout: WritableStream; - stderr: WritableStream; - stdin: ReadableStream; - argv: string[]; - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - env: any; - exit(code?: number): void; - getgid(): number; - setgid(id: number): void; - setgid(id: string): void; - getuid(): number; - setuid(id: number): void; - setuid(id: string): void; - version: string; - versions: { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - openssl: string; - }; - config: { - target_defaults: { - cflags: any[]; - default_configuration: string; - defines: string[]; - include_dirs: string[]; - libraries: string[]; - }; - variables: { - clang: number; - host_arch: string; - node_install_npm: boolean; - node_install_waf: boolean; - node_prefix: string; - node_shared_openssl: boolean; - node_shared_v8: boolean; - node_shared_zlib: boolean; - node_use_dtrace: boolean; - node_use_etw: boolean; - node_use_openssl: boolean; - target_arch: string; - v8_no_strict_aliasing: number; - v8_use_snapshot: boolean; - visibility: string; - }; - }; - kill(pid:number, signal?: string|number): void; - pid: number; - title: string; - arch: string; - platform: string; - memoryUsage(): MemoryUsage; - nextTick(callback: Function): void; - umask(mask?: number): number; - uptime(): number; - hrtime(time?:number[]): number[]; - domain: Domain; - - // Worker - send?(message: any, sendHandle?: any): void; - disconnect(): void; - connected: boolean; - } - - export interface Global { - Array: typeof Array; - ArrayBuffer: typeof ArrayBuffer; - Boolean: typeof Boolean; - Buffer: typeof Buffer; - DataView: typeof DataView; - Date: typeof Date; - Error: typeof Error; - EvalError: typeof EvalError; - Float32Array: typeof Float32Array; - Float64Array: typeof Float64Array; - Function: typeof Function; - GLOBAL: Global; - Infinity: typeof Infinity; - Int16Array: typeof Int16Array; - Int32Array: typeof Int32Array; - Int8Array: typeof Int8Array; - Intl: typeof Intl; - JSON: typeof JSON; - Map: MapConstructor; - Math: typeof Math; - NaN: typeof NaN; - Number: typeof Number; - Object: typeof Object; - Promise: Function; - RangeError: typeof RangeError; - ReferenceError: typeof ReferenceError; - RegExp: typeof RegExp; - Set: SetConstructor; - String: typeof String; - Symbol: Function; - SyntaxError: typeof SyntaxError; - TypeError: typeof TypeError; - URIError: typeof URIError; - Uint16Array: typeof Uint16Array; - Uint32Array: typeof Uint32Array; - Uint8Array: typeof Uint8Array; - Uint8ClampedArray: Function; - WeakMap: WeakMapConstructor; - WeakSet: WeakSetConstructor; - clearImmediate: (immediateId: any) => void; - clearInterval: (intervalId: NodeJS.Timer) => void; - clearTimeout: (timeoutId: NodeJS.Timer) => void; - console: typeof console; - decodeURI: typeof decodeURI; - decodeURIComponent: typeof decodeURIComponent; - encodeURI: typeof encodeURI; - encodeURIComponent: typeof encodeURIComponent; - escape: (str: string) => string; - eval: typeof eval; - global: Global; - isFinite: typeof isFinite; - isNaN: typeof isNaN; - parseFloat: typeof parseFloat; - parseInt: typeof parseInt; - process: Process; - root: Global; - setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; - } - - export interface Timer { - ref() : void; - unref() : void; - } + export interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + export interface EventEmitter { + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; + } + + export interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + } + + export interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Buffer | string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface ReadWriteStream extends ReadableStream, WritableStream { } + + export interface Events extends EventEmitter { } + + export interface Domain extends Events { + run(fn: Function): void; + add(emitter: Events): void; + remove(emitter: Events): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + } + + export interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + } + + export interface Process extends EventEmitter { + stdout: WritableStream; + stderr: WritableStream; + stdin: ReadableStream; + argv: string[]; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + env: any; + exit(code?: number): void; + getgid(): number; + setgid(id: number): void; + setgid(id: string): void; + getuid(): number; + setuid(id: number): void; + setuid(id: string): void; + version: string; + versions: { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + openssl: string; + }; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string | number): void; + pid: number; + title: string; + arch: string; + platform: string; + memoryUsage(): MemoryUsage; + nextTick(callback: Function): void; + umask(mask?: number): number; + uptime(): number; + hrtime(time?: number[]): number[]; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; + } + + export interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: any) => void; + clearInterval: (intervalId: NodeJS.Timer) => void; + clearTimeout: (timeoutId: NodeJS.Timer) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + export interface Timer { + ref(): void; + unref(): void; + } } /** * @deprecated */ interface NodeBuffer { - [index: number]: number; - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): any; - length: number; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): Buffer; - indexOf(value: string | number | Buffer, byteOffset?: number): number; + [index: number]: number; + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): any; + length: number; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): Buffer; + indexOf(value: string | number | Buffer, byteOffset?: number): number; } /************************************************ @@ -439,189 +439,189 @@ interface NodeBuffer { * * ************************************************/ declare module "buffer" { - export var INSPECT_MAX_BYTES: number; - var BuffType: typeof Buffer; - var SlowBuffType: typeof SlowBuffer; - export { BuffType as Buffer, SlowBuffType as SlowBuffer }; + export var INSPECT_MAX_BYTES: number; + var BuffType: typeof Buffer; + var SlowBuffType: typeof SlowBuffer; + export { BuffType as Buffer, SlowBuffType as SlowBuffer }; } declare module "querystring" { - export interface StringifyOptions { - encodeURIComponent?: Function; - } - - export interface ParseOptions { - maxKeys?: number; - decodeURIComponent?: Function; - } - - export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; - export function escape(str: string): string; - export function unescape(str: string): string; + export interface StringifyOptions { + encodeURIComponent?: Function; + } + + export interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: Function; + } + + export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; + export function escape(str: string): string; + export function unescape(str: string): string; } declare module "events" { - export class EventEmitter implements NodeJS.EventEmitter { - static EventEmitter: EventEmitter; - static listenerCount(emitter: EventEmitter, event: string): number; // deprecated - static defaultMaxListeners: number; - - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - listenerCount(type: string): number; - } + export class EventEmitter implements NodeJS.EventEmitter { + static EventEmitter: EventEmitter; + static listenerCount(emitter: EventEmitter, event: string): number; // deprecated + static defaultMaxListeners: number; + + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; + } } declare module "http" { - import * as events from "events"; - import * as net from "net"; - import * as stream from "stream"; - - export interface RequestOptions { - protocol?: string; - host?: string; - hostname?: string; - family?: number; - port?: number; - localAddress?: string; - socketPath?: string; - method?: string; - path?: string; - headers?: { [key: string]: any }; - auth?: string; - agent?: Agent|boolean; - } - - export interface Server extends events.EventEmitter, net.Server { - setTimeout(msecs: number, callback: Function): void; - maxHeadersCount: number; - timeout: number; - } + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; + + export interface RequestOptions { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number; + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: { [key: string]: any }; + auth?: string; + agent?: Agent | boolean; + } + + export interface Server extends events.EventEmitter, net.Server { + setTimeout(msecs: number, callback: Function): void; + maxHeadersCount: number; + timeout: number; + } /** * @deprecated Use IncomingMessage */ - export interface ServerRequest extends IncomingMessage { - connection: net.Socket; - } - export interface ServerResponse extends events.EventEmitter, stream.Writable { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; - statusCode: number; - statusMessage: string; - headersSent: boolean; - setHeader(name: string, value: string | string[]): void; - sendDate: boolean; - getHeader(name: string): string; - removeHeader(name: string): void; - write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - export interface ClientRequest extends events.EventEmitter, stream.Writable { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - write(chunk: any, encoding?: string): void; - abort(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - - setHeader(name: string, value: string | string[]): void; - getHeader(name: string): string; - removeHeader(name: string): void; - addTrailers(headers: any): void; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - export interface IncomingMessage extends events.EventEmitter, stream.Readable { - httpVersion: string; - headers: any; - rawHeaders: string[]; - trailers: any; - rawTrailers: any; - setTimeout(msecs: number, callback: Function): NodeJS.Timer; + export interface ServerRequest extends IncomingMessage { + connection: net.Socket; + } + export interface ServerResponse extends events.EventEmitter, stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + writeContinue(): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; + writeHead(statusCode: number, headers?: any): void; + statusCode: number; + statusMessage: string; + headersSent: boolean; + setHeader(name: string, value: string | string[]): void; + sendDate: boolean; + getHeader(name: string): string; + removeHeader(name: string): void; + write(chunk: any, encoding?: string): any; + addTrailers(headers: any): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface ClientRequest extends events.EventEmitter, stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + write(chunk: any, encoding?: string): void; + abort(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + + setHeader(name: string, value: string | string[]): void; + getHeader(name: string): string; + removeHeader(name: string): void; + addTrailers(headers: any): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface IncomingMessage extends events.EventEmitter, stream.Readable { + httpVersion: string; + headers: any; + rawHeaders: string[]; + trailers: any; + rawTrailers: any; + setTimeout(msecs: number, callback: Function): NodeJS.Timer; /** * Only valid for request obtained from http.Server. */ - method?: string; + method?: string; /** * Only valid for request obtained from http.Server. */ - url?: string; + url?: string; /** * Only valid for response obtained from http.ClientRequest. */ - statusCode?: number; + statusCode?: number; /** * Only valid for response obtained from http.ClientRequest. */ - statusMessage?: string; - socket: net.Socket; - } + statusMessage?: string; + socket: net.Socket; + } /** * @deprecated Use IncomingMessage */ - export interface ClientResponse extends IncomingMessage { } + export interface ClientResponse extends IncomingMessage { } - export interface AgentOptions { + export interface AgentOptions { /** * Keep sockets around in a pool to be used by other requests in the future. Default = false */ - keepAlive?: boolean; + keepAlive?: boolean; /** * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. * Only relevant if keepAlive is set to true. */ - keepAliveMsecs?: number; + keepAliveMsecs?: number; /** * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity */ - maxSockets?: number; + maxSockets?: number; /** * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. */ - maxFreeSockets?: number; - } + maxFreeSockets?: number; + } - export class Agent { - maxSockets: number; - sockets: any; - requests: any; + export class Agent { + maxSockets: number; + sockets: any; + requests: any; - constructor(opts?: AgentOptions); + constructor(opts?: AgentOptions); /** * Destroy any sockets that are currently in use by the agent. @@ -629,682 +629,682 @@ declare module "http" { * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, * sockets may hang open for quite a long time before the server terminates them. */ - destroy(): void; - } - - export var METHODS: string[]; - - export var STATUS_CODES: { - [errorCode: number]: string; - [errorCode: string]: string; - }; - export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server; - export function createClient(port?: number, host?: string): any; - export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; - export var globalAgent: Agent; + destroy(): void; + } + + export var METHODS: string[]; + + export var STATUS_CODES: { + [errorCode: number]: string; + [errorCode: string]: string; + }; + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; + export function createClient(port?: number, host?: string): any; + export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; + export var globalAgent: Agent; } declare module "cluster" { - import * as child from "child_process"; - import * as events from "events"; - - export interface ClusterSettings { - exec?: string; - args?: string[]; - silent?: boolean; - } - - export interface Address { - address: string; - port: number; - addressType: string; - } - - export class Worker extends events.EventEmitter { - id: string; - process: child.ChildProcess; - suicide: boolean; - send(message: any, sendHandle?: any): void; - kill(signal?: string): void; - destroy(signal?: string): void; - disconnect(): void; - } - - export var settings: ClusterSettings; - export var isMaster: boolean; - export var isWorker: boolean; - export function setupMaster(settings?: ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; - export var worker: Worker; - export var workers: Worker[]; - - // Event emitter - export function addListener(event: string, listener: Function): void; - export function on(event: "disconnect", listener: (worker: Worker) => void): void; - export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void; - export function on(event: "fork", listener: (worker: Worker) => void): void; - export function on(event: "listening", listener: (worker: Worker, address: any) => void): void; - export function on(event: "message", listener: (worker: Worker, message: any) => void): void; - export function on(event: "online", listener: (worker: Worker) => void): void; - export function on(event: "setup", listener: (settings: any) => void): void; - export function on(event: string, listener: Function): any; - export function once(event: string, listener: Function): void; - export function removeListener(event: string, listener: Function): void; - export function removeAllListeners(event?: string): void; - export function setMaxListeners(n: number): void; - export function listeners(event: string): Function[]; - export function emit(event: string, ...args: any[]): boolean; + import * as child from "child_process"; + import * as events from "events"; + + export interface ClusterSettings { + exec?: string; + args?: string[]; + silent?: boolean; + } + + export interface Address { + address: string; + port: number; + addressType: string; + } + + export class Worker extends events.EventEmitter { + id: string; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any): void; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + } + + export var settings: ClusterSettings; + export var isMaster: boolean; + export var isWorker: boolean; + export function setupMaster(settings?: ClusterSettings): void; + export function fork(env?: any): Worker; + export function disconnect(callback?: Function): void; + export var worker: Worker; + export var workers: Worker[]; + + // Event emitter + export function addListener(event: string, listener: Function): void; + export function on(event: "disconnect", listener: (worker: Worker) => void): void; + export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void; + export function on(event: "fork", listener: (worker: Worker) => void): void; + export function on(event: "listening", listener: (worker: Worker, address: any) => void): void; + export function on(event: "message", listener: (worker: Worker, message: any) => void): void; + export function on(event: "online", listener: (worker: Worker) => void): void; + export function on(event: "setup", listener: (settings: any) => void): void; + export function on(event: string, listener: Function): any; + export function once(event: string, listener: Function): void; + export function removeListener(event: string, listener: Function): void; + export function removeAllListeners(event?: string): void; + export function setMaxListeners(n: number): void; + export function listeners(event: string): Function[]; + export function emit(event: string, ...args: any[]): boolean; } declare module "zlib" { - import * as stream from "stream"; - export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } - - export interface Gzip extends stream.Transform { } - export interface Gunzip extends stream.Transform { } - export interface Deflate extends stream.Transform { } - export interface Inflate extends stream.Transform { } - export interface DeflateRaw extends stream.Transform { } - export interface InflateRaw extends stream.Transform { } - export interface Unzip extends stream.Transform { } - - export function createGzip(options?: ZlibOptions): Gzip; - export function createGunzip(options?: ZlibOptions): Gunzip; - export function createDeflate(options?: ZlibOptions): Deflate; - export function createInflate(options?: ZlibOptions): Inflate; - export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; - export function createInflateRaw(options?: ZlibOptions): InflateRaw; - export function createUnzip(options?: ZlibOptions): Unzip; - - export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function deflateSync(buf: Buffer, options?: ZlibOptions): any; - export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any; - export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function gzipSync(buf: Buffer, options?: ZlibOptions): any; - export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function gunzipSync(buf: Buffer, options?: ZlibOptions): any; - export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function inflateSync(buf: Buffer, options?: ZlibOptions): any; - export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any; - export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function unzipSync(buf: Buffer, options?: ZlibOptions): any; - - // Constants - export var Z_NO_FLUSH: number; - export var Z_PARTIAL_FLUSH: number; - export var Z_SYNC_FLUSH: number; - export var Z_FULL_FLUSH: number; - export var Z_FINISH: number; - export var Z_BLOCK: number; - export var Z_TREES: number; - export var Z_OK: number; - export var Z_STREAM_END: number; - export var Z_NEED_DICT: number; - export var Z_ERRNO: number; - export var Z_STREAM_ERROR: number; - export var Z_DATA_ERROR: number; - export var Z_MEM_ERROR: number; - export var Z_BUF_ERROR: number; - export var Z_VERSION_ERROR: number; - export var Z_NO_COMPRESSION: number; - export var Z_BEST_SPEED: number; - export var Z_BEST_COMPRESSION: number; - export var Z_DEFAULT_COMPRESSION: number; - export var Z_FILTERED: number; - export var Z_HUFFMAN_ONLY: number; - export var Z_RLE: number; - export var Z_FIXED: number; - export var Z_DEFAULT_STRATEGY: number; - export var Z_BINARY: number; - export var Z_TEXT: number; - export var Z_ASCII: number; - export var Z_UNKNOWN: number; - export var Z_DEFLATED: number; - export var Z_NULL: number; + import * as stream from "stream"; + export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } + + export interface Gzip extends stream.Transform { } + export interface Gunzip extends stream.Transform { } + export interface Deflate extends stream.Transform { } + export interface Inflate extends stream.Transform { } + export interface DeflateRaw extends stream.Transform { } + export interface InflateRaw extends stream.Transform { } + export interface Unzip extends stream.Transform { } + + export function createGzip(options?: ZlibOptions): Gzip; + export function createGunzip(options?: ZlibOptions): Gunzip; + export function createDeflate(options?: ZlibOptions): Deflate; + export function createInflate(options?: ZlibOptions): Inflate; + export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + export function createInflateRaw(options?: ZlibOptions): InflateRaw; + export function createUnzip(options?: ZlibOptions): Unzip; + + export function deflate(buf: Buffer, callback: (error: Error, result: any) => void): void; + export function deflateSync(buf: Buffer, options?: ZlibOptions): any; + export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) => void): void; + export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any; + export function gzip(buf: Buffer, callback: (error: Error, result: any) => void): void; + export function gzipSync(buf: Buffer, options?: ZlibOptions): any; + export function gunzip(buf: Buffer, callback: (error: Error, result: any) => void): void; + export function gunzipSync(buf: Buffer, options?: ZlibOptions): any; + export function inflate(buf: Buffer, callback: (error: Error, result: any) => void): void; + export function inflateSync(buf: Buffer, options?: ZlibOptions): any; + export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) => void): void; + export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any; + export function unzip(buf: Buffer, callback: (error: Error, result: any) => void): void; + export function unzipSync(buf: Buffer, options?: ZlibOptions): any; + + // Constants + export var Z_NO_FLUSH: number; + export var Z_PARTIAL_FLUSH: number; + export var Z_SYNC_FLUSH: number; + export var Z_FULL_FLUSH: number; + export var Z_FINISH: number; + export var Z_BLOCK: number; + export var Z_TREES: number; + export var Z_OK: number; + export var Z_STREAM_END: number; + export var Z_NEED_DICT: number; + export var Z_ERRNO: number; + export var Z_STREAM_ERROR: number; + export var Z_DATA_ERROR: number; + export var Z_MEM_ERROR: number; + export var Z_BUF_ERROR: number; + export var Z_VERSION_ERROR: number; + export var Z_NO_COMPRESSION: number; + export var Z_BEST_SPEED: number; + export var Z_BEST_COMPRESSION: number; + export var Z_DEFAULT_COMPRESSION: number; + export var Z_FILTERED: number; + export var Z_HUFFMAN_ONLY: number; + export var Z_RLE: number; + export var Z_FIXED: number; + export var Z_DEFAULT_STRATEGY: number; + export var Z_BINARY: number; + export var Z_TEXT: number; + export var Z_ASCII: number; + export var Z_UNKNOWN: number; + export var Z_DEFLATED: number; + export var Z_NULL: number; } declare module "os" { - export interface CpuInfo { - model: string; - speed: number; - times: { - user: number; - nice: number; - sys: number; - idle: number; - irq: number; - }; - } - - export interface NetworkInterfaceInfo { - address: string; - netmask: string; - family: string; - mac: string; - internal: boolean; - } - - export function tmpdir(): string; - export function homedir(): string; - export function endianness(): string; - export function hostname(): string; - export function type(): string; - export function platform(): string; - export function arch(): string; - export function release(): string; - export function uptime(): number; - export function loadavg(): number[]; - export function totalmem(): number; - export function freemem(): number; - export function cpus(): CpuInfo[]; - export function networkInterfaces(): {[index: string]: NetworkInterfaceInfo[]}; - export var EOL: string; + export interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + + export interface NetworkInterfaceInfo { + address: string; + netmask: string; + family: string; + mac: string; + internal: boolean; + } + + export function tmpdir(): string; + export function homedir(): string; + export function endianness(): string; + export function hostname(): string; + export function type(): string; + export function platform(): string; + export function arch(): string; + export function release(): string; + export function uptime(): number; + export function loadavg(): number[]; + export function totalmem(): number; + export function freemem(): number; + export function cpus(): CpuInfo[]; + export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; + export var EOL: string; } declare module "https" { - import * as tls from "tls"; - import * as events from "events"; - import * as http from "http"; - - export interface ServerOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - crl?: any; - ciphers?: string; - honorCipherOrder?: boolean; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; - SNICallback?: (servername: string) => any; - } - - export interface RequestOptions extends http.RequestOptions{ - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; - rejectUnauthorized?: boolean; - secureProtocol?: string; - } - - export interface Agent { - maxSockets: number; - sockets: any; - requests: any; - } - export var Agent: { - new (options?: RequestOptions): Agent; - }; - export interface Server extends tls.Server { } - export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; - export var globalAgent: Agent; + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; + + export interface ServerOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + crl?: any; + ciphers?: string; + honorCipherOrder?: boolean; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; + SNICallback?: (servername: string) => any; + } + + export interface RequestOptions extends http.RequestOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + secureProtocol?: string; + } + + export interface Agent { + maxSockets: number; + sockets: any; + requests: any; + } + export var Agent: { + new (options?: RequestOptions): Agent; + }; + export interface Server extends tls.Server { } + export function createServer(options: ServerOptions, requestListener?: Function): Server; + export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export var globalAgent: Agent; } declare module "punycode" { - export function decode(string: string): string; - export function encode(string: string): string; - export function toUnicode(domain: string): string; - export function toASCII(domain: string): string; - export var ucs2: ucs2; - interface ucs2 { - decode(string: string): number[]; - encode(codePoints: number[]): string; - } - export var version: any; + export function decode(string: string): string; + export function encode(string: string): string; + export function toUnicode(domain: string): string; + export function toASCII(domain: string): string; + export var ucs2: ucs2; + interface ucs2 { + decode(string: string): number[]; + encode(codePoints: number[]): string; + } + export var version: any; } declare module "repl" { - import * as stream from "stream"; - import * as events from "events"; - - export interface ReplOptions { - prompt?: string; - input?: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - terminal?: boolean; - eval?: Function; - useColors?: boolean; - useGlobal?: boolean; - ignoreUndefined?: boolean; - writer?: Function; - } - export function start(options: ReplOptions): events.EventEmitter; + import * as stream from "stream"; + import * as events from "events"; + + export interface ReplOptions { + prompt?: string; + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + terminal?: boolean; + eval?: Function; + useColors?: boolean; + useGlobal?: boolean; + ignoreUndefined?: boolean; + writer?: Function; + } + export function start(options: ReplOptions): events.EventEmitter; } declare module "readline" { - import * as events from "events"; - import * as stream from "stream"; - - export interface Key { - sequence?: string; - name?: string; - ctrl?: boolean; - meta?: boolean; - shift?: boolean; - } - - export interface ReadLine extends events.EventEmitter { - setPrompt(prompt: string): void; - prompt(preserveCursor?: boolean): void; - question(query: string, callback: (answer: string) => void): void; - pause(): ReadLine; - resume(): ReadLine; - close(): void; - write(data: string|Buffer, key?: Key): void; - } - - export interface Completer { - (line: string): CompleterResult; - (line: string, callback: (err: any, result: CompleterResult) => void): any; - } - - export interface CompleterResult { - completions: string[]; - line: string; - } - - export interface ReadLineOptions { - input: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - completer?: Completer; - terminal?: boolean; - historySize?: number; - } - - export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): ReadLine; - export function createInterface(options: ReadLineOptions): ReadLine; - - export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; - export function moveCursor(stream: NodeJS.WritableStream, dx: number|string, dy: number|string): void; - export function clearLine(stream: NodeJS.WritableStream, dir: number): void; - export function clearScreenDown(stream: NodeJS.WritableStream): void; + import * as events from "events"; + import * as stream from "stream"; + + export interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } + + export interface ReadLine extends events.EventEmitter { + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: (answer: string) => void): void; + pause(): ReadLine; + resume(): ReadLine; + close(): void; + write(data: string | Buffer, key?: Key): void; + } + + export interface Completer { + (line: string): CompleterResult; + (line: string, callback: (err: any, result: CompleterResult) => void): any; + } + + export interface CompleterResult { + completions: string[]; + line: string; + } + + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + completer?: Completer; + terminal?: boolean; + historySize?: number; + } + + export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): ReadLine; + export function createInterface(options: ReadLineOptions): ReadLine; + + export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; + export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; + export function clearLine(stream: NodeJS.WritableStream, dir: number): void; + export function clearScreenDown(stream: NodeJS.WritableStream): void; } declare module "vm" { - export interface Context { } - export interface Script { - runInThisContext(): void; - runInNewContext(sandbox?: Context): void; - } - export function runInThisContext(code: string, filename?: string): void; - export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; - export function runInContext(code: string, context: Context, filename?: string): void; - export function createContext(initSandbox?: Context): Context; - export function createScript(code: string, filename?: string): Script; + export interface Context { } + export interface Script { + runInThisContext(): void; + runInNewContext(sandbox?: Context): void; + } + export function runInThisContext(code: string, filename?: string): void; + export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; + export function runInContext(code: string, context: Context, filename?: string): void; + export function createContext(initSandbox?: Context): Context; + export function createScript(code: string, filename?: string): Script; } declare module "child_process" { - import * as events from "events"; - import * as stream from "stream"; - - export interface ChildProcess extends events.EventEmitter { - stdin: stream.Writable; - stdout: stream.Readable; - stderr: stream.Readable; - stdio: [stream.Writable, stream.Readable, stream.Readable]; - pid: number; - connected: boolean; - kill(signal?: string): void; - send(message: any, sendHandle?: any): void; - disconnect(): void; - unref(): void; - } - - export interface SpawnOptions { - cwd?: string; - env?: any; - stdio?: any; - detached?: boolean; - uid?: number; - gid?: number; - shell?: boolean | string; - } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; - - export interface ExecOptions { - cwd?: string; - env?: any; - shell?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - } - export interface ExecOptionsWithStringEncoding extends ExecOptions { - encoding: BufferEncoding; - } - export interface ExecOptionsWithBufferEncoding extends ExecOptions { - encoding: string; // specify `null`. - } - export function exec(command: string, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - - export interface ExecFileOptions { - cwd?: string; - env?: any; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - } - export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { - encoding: BufferEncoding; - } - export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { - encoding: string; // specify `null`. - } - export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - // usage. child_process.execFile("file.sh", {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - // usage. child_process.execFile("file.sh", ["foo"], {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - - export interface ForkOptions { - cwd?: string; - env?: any; - execPath?: string; - execArgv?: string[]; - silent?: boolean; - uid?: number; - gid?: number; - } - export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; - - export interface SpawnSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - shell?: boolean | string; - } - export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { - encoding: BufferEncoding; - } - export interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { - encoding: string; // specify `null`. - } - export interface SpawnSyncReturns { - pid: number; - output: string[]; - stdout: T; - stderr: T; - status: number; - signal: string; - error: Error; - } - export function spawnSync(command: string): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; - - export interface ExecSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - shell?: string; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - } - export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { - encoding: BufferEncoding; - } - export interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { - encoding: string; // specify `null`. - } - export function execSync(command: string): Buffer; - export function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; - export function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; - export function execSync(command: string, options?: ExecSyncOptions): Buffer; - - export interface ExecFileSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - } - export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { - encoding: BufferEncoding; - } - export interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { - encoding: string; // specify `null`. - } - export function execFileSync(command: string): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; - export function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithStringEncoding): string; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; + import * as events from "events"; + import * as stream from "stream"; + + export interface ChildProcess extends events.EventEmitter { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + stdio: [stream.Writable, stream.Readable, stream.Readable]; + pid: number; + connected: boolean; + kill(signal?: string): void; + send(message: any, sendHandle?: any): void; + disconnect(): void; + unref(): void; + } + + export interface SpawnOptions { + cwd?: string; + env?: any; + stdio?: any; + detached?: boolean; + uid?: number; + gid?: number; + shell?: boolean | string; + } + export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + + export interface ExecOptions { + cwd?: string; + env?: any; + shell?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + } + export interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + export interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: string; // specify `null`. + } + export function exec(command: string, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + + export interface ExecFileOptions { + cwd?: string; + env?: any; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + } + export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: string; // specify `null`. + } + export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // usage. child_process.execFile("file.sh", {encoding: null as string}, (err, stdout, stderr) => {}); + export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // usage. child_process.execFile("file.sh", ["foo"], {encoding: null as string}, (err, stdout, stderr) => {}); + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + + export interface ForkOptions { + cwd?: string; + env?: any; + execPath?: string; + execArgv?: string[]; + silent?: boolean; + uid?: number; + gid?: number; + } + export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; + + export interface SpawnSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + shell?: boolean | string; + } + export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + export interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding: string; // specify `null`. + } + export interface SpawnSyncReturns { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number; + signal: string; + error: Error; + } + export function spawnSync(command: string): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; + + export interface ExecSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + shell?: string; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + } + export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + export interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding: string; // specify `null`. + } + export function execSync(command: string): Buffer; + export function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + export function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + export function execSync(command: string, options?: ExecSyncOptions): Buffer; + + export interface ExecFileSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + } + export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + export interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: string; // specify `null`. + } + export function execFileSync(command: string): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + export function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithStringEncoding): string; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; } declare module "url" { - export interface Url { - href?: string; - protocol?: string; - auth?: string; - hostname?: string; - port?: string; - host?: string; - pathname?: string; - search?: string; - query?: any; // string | Object - slashes?: boolean; - hash?: string; - path?: string; - } - - export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; - export function format(url: Url): string; - export function resolve(from: string, to: string): string; + export interface Url { + href?: string; + protocol?: string; + auth?: string; + hostname?: string; + port?: string; + host?: string; + pathname?: string; + search?: string; + query?: any; // string | Object + slashes?: boolean; + hash?: string; + path?: string; + } + + export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; + export function format(url: Url): string; + export function resolve(from: string, to: string): string; } declare module "dns" { - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; + export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; } declare module "net" { - import * as stream from "stream"; - - export interface Socket extends stream.Duplex { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - connect(port: number, host?: string, connectionListener?: Function): void; - connect(path: string, connectionListener?: Function): void; - bufferSize: number; - setEncoding(encoding?: string): void; - write(data: any, encoding?: string, callback?: Function): void; - destroy(): void; - pause(): void; - resume(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setKeepAlive(enable?: boolean, initialDelay?: number): void; - address(): { port: number; family: string; address: string; }; - unref(): void; - ref(): void; - - remoteAddress: string; - remoteFamily: string; - remotePort: number; - localAddress: string; - localPort: number; - bytesRead: number; - bytesWritten: number; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - - export var Socket: { - new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; - }; - - export interface ListenOptions { - port?: number; - host?: string; - backlog?: number; - path?: string; - exclusive?: boolean; - } - - export interface Server extends Socket { - listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): Server; - listen(port: number, hostname?: string, listeningListener?: Function): Server; - listen(port: number, backlog?: number, listeningListener?: Function): Server; - listen(port: number, listeningListener?: Function): Server; - listen(path: string, backlog?: number, listeningListener?: Function): Server; - listen(path: string, listeningListener?: Function): Server; - listen(handle: any, backlog?: number, listeningListener?: Function): Server; - listen(handle: any, listeningListener?: Function): Server; - listen(options: ListenOptions, listeningListener?: Function): Server; - close(callback?: Function): Server; - address(): { port: number; family: string; address: string; }; - getConnections(cb: (error: Error, count: number) => void): void; - ref(): Server; - unref(): Server; - maxConnections: number; - connections: number; - } - export function createServer(connectionListener?: (socket: Socket) =>void ): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server; - export function connect(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; - export function connect(port: number, host?: string, connectionListener?: Function): Socket; - export function connect(path: string, connectionListener?: Function): Socket; - export function createConnection(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; - export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; - export function createConnection(path: string, connectionListener?: Function): Socket; - export function isIP(input: string): number; - export function isIPv4(input: string): boolean; - export function isIPv6(input: string): boolean; + import * as stream from "stream"; + + export interface Socket extends stream.Duplex { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + connect(port: number, host?: string, connectionListener?: Function): void; + connect(path: string, connectionListener?: Function): void; + bufferSize: number; + setEncoding(encoding?: string): void; + write(data: any, encoding?: string, callback?: Function): void; + destroy(): void; + pause(): void; + resume(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setKeepAlive(enable?: boolean, initialDelay?: number): void; + address(): { port: number; family: string; address: string; }; + unref(): void; + ref(): void; + + remoteAddress: string; + remoteFamily: string; + remotePort: number; + localAddress: string; + localPort: number; + bytesRead: number; + bytesWritten: number; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + + export var Socket: { + new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; + }; + + export interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + } + + export interface Server extends Socket { + listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): Server; + listen(port: number, hostname?: string, listeningListener?: Function): Server; + listen(port: number, backlog?: number, listeningListener?: Function): Server; + listen(port: number, listeningListener?: Function): Server; + listen(path: string, backlog?: number, listeningListener?: Function): Server; + listen(path: string, listeningListener?: Function): Server; + listen(handle: any, backlog?: number, listeningListener?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + listen(options: ListenOptions, listeningListener?: Function): Server; + close(callback?: Function): Server; + address(): { port: number; family: string; address: string; }; + getConnections(cb: (error: Error, count: number) => void): void; + ref(): Server; + unref(): Server; + maxConnections: number; + connections: number; + } + export function createServer(connectionListener?: (socket: Socket) => void): Server; + export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; + export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function connect(port: number, host?: string, connectionListener?: Function): Socket; + export function connect(path: string, connectionListener?: Function): Socket; + export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + export function createConnection(path: string, connectionListener?: Function): Socket; + export function isIP(input: string): number; + export function isIPv4(input: string): boolean; + export function isIPv6(input: string): boolean; } declare module "dgram" { - import * as events from "events"; - - interface RemoteInfo { - address: string; - port: number; - size: number; - } - - interface AddressInfo { - address: string; - family: string; - port: number; - } - - export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - - interface Socket extends events.EventEmitter { - send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - bind(port: number, address?: string, callback?: () => void): void; - close(): void; - address(): AddressInfo; - setBroadcast(flag: boolean): void; - setMulticastTTL(ttl: number): void; - setMulticastLoopback(flag: boolean): void; - addMembership(multicastAddress: string, multicastInterface?: string): void; - dropMembership(multicastAddress: string, multicastInterface?: string): void; - } + import * as events from "events"; + + interface RemoteInfo { + address: string; + port: number; + size: number; + } + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + interface Socket extends events.EventEmitter { + send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port: number, address?: string, callback?: () => void): void; + close(): void; + address(): AddressInfo; + setBroadcast(flag: boolean): void; + setMulticastTTL(ttl: number): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + } } declare module "fs" { - import * as stream from "stream"; - import * as events from "events"; - - interface Stats { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: number; - ino: number; - mode: number; - nlink: number; - uid: number; - gid: number; - rdev: number; - size: number; - blksize: number; - blocks: number; - atime: Date; - mtime: Date; - ctime: Date; - birthtime: Date; - } - - interface FSWatcher extends events.EventEmitter { - close(): void; - } - - export interface ReadStream extends stream.Readable { - close(): void; - } - export interface WriteStream extends stream.Writable { - close(): void; - bytesWritten: number; - } + import * as stream from "stream"; + import * as events from "events"; + + interface Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + } + + export interface ReadStream extends stream.Readable { + close(): void; + } + export interface WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + } /** * Asynchronous rename. @@ -1312,85 +1312,85 @@ declare module "fs" { * @param newPath * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** * Synchronous rename * @param oldPath * @param newPath */ - export function renameSync(oldPath: string, newPath: string): void; - export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncateSync(path: string, len?: number): void; - export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function ftruncateSync(fd: number, len?: number): void; - export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chownSync(path: string, uid: number, gid: number): void; - export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchownSync(fd: number, uid: number, gid: number): void; - export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchownSync(path: string, uid: number, gid: number): void; - export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmodSync(path: string, mode: number): void; - export function chmodSync(path: string, mode: string): void; - export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchmodSync(fd: number, mode: number): void; - export function fchmodSync(fd: number, mode: string): void; - export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmodSync(path: string, mode: number): void; - export function lchmodSync(path: string, mode: string): void; - export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function statSync(path: string): Stats; - export function lstatSync(path: string): Stats; - export function fstatSync(fd: number): Stats; - export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function linkSync(srcpath: string, dstpath: string): void; - export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; - export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; - export function readlinkSync(path: string): string; - export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; - export function realpathSync(path: string, cache?: { [path: string]: string }): string; + export function renameSync(oldPath: string, newPath: string): void; + export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncateSync(path: string, len?: number): void; + export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncateSync(fd: number, len?: number): void; + export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chownSync(path: string, uid: number, gid: number): void; + export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchownSync(fd: number, uid: number, gid: number): void; + export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchownSync(path: string, uid: number, gid: number): void; + export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmodSync(path: string, mode: number): void; + export function chmodSync(path: string, mode: string): void; + export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmodSync(fd: number, mode: number): void; + export function fchmodSync(fd: number, mode: string): void; + export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmodSync(path: string, mode: number): void; + export function lchmodSync(path: string, mode: string): void; + export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function statSync(path: string): Stats; + export function lstatSync(path: string): Stats; + export function fstatSync(fd: number): Stats; + export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function linkSync(srcpath: string, dstpath: string): void; + export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; + export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; + export function readlinkSync(path: string): string; + export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpathSync(path: string, cache?: { [path: string]: string }): string; /* * Asynchronous unlink - deletes the file specified in {path} * * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /* * Synchronous unlink - deletes the file specified in {path} * * @param path */ - export function unlinkSync(path: string): void; + export function unlinkSync(path: string): void; /* * Asynchronous rmdir - removes the directory specified in {path} * * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /* * Synchronous rmdir - removes the directory specified in {path} * * @param path */ - export function rmdirSync(path: string): void; + export function rmdirSync(path: string): void; /* * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /* * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * @@ -1398,7 +1398,7 @@ declare module "fs" { * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; /* * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * @@ -1406,7 +1406,7 @@ declare module "fs" { * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /* * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * @@ -1414,7 +1414,7 @@ declare module "fs" { * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function mkdirSync(path: string, mode?: number): void; + export function mkdirSync(path: string, mode?: number): void; /* * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * @@ -1422,37 +1422,37 @@ declare module "fs" { * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function mkdirSync(path: string, mode?: string): void; - export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; - export function readdirSync(path: string): string[]; - export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function closeSync(fd: number): void; - export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function openSync(path: string, flags: string, mode?: number): number; - export function openSync(path: string, flags: string, mode?: string): number; - export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimesSync(path: string, atime: number, mtime: number): void; - export function utimesSync(path: string, atime: Date, mtime: Date): void; - export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function futimesSync(fd: number, atime: number, mtime: number): void; - export function futimesSync(fd: number, atime: Date, mtime: Date): void; - export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fsyncSync(fd: number): void; - export function fdatasync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fdatasyncSync(fd: number): void; - export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; - export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; - export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; - export function writeSync(fd: number, data: any, position?: number, enconding?: string): number; - export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; - export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + export function mkdirSync(path: string, mode?: string): void; + export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; + export function readdirSync(path: string): string[]; + export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function closeSync(fd: number): void; + export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function openSync(path: string, flags: string, mode?: number): number; + export function openSync(path: string, flags: string, mode?: string): number; + export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimesSync(path: string, atime: number, mtime: number): void; + export function utimesSync(path: string, atime: Date, mtime: Date): void; + export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimesSync(fd: number, atime: number, mtime: number): void; + export function futimesSync(fd: number, atime: Date, mtime: Date): void; + export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fsyncSync(fd: number): void; + export function fdatasync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fdatasyncSync(fd: number): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; + export function writeSync(fd: number, data: any, position?: number, enconding?: string): number; + export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; + export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; /* * Asynchronous readFile - Asynchronously reads the entire contents of a file. * @@ -1460,7 +1460,7 @@ declare module "fs" { * @param encoding * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ - export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; /* * Asynchronous readFile - Asynchronously reads the entire contents of a file. * @@ -1468,7 +1468,7 @@ declare module "fs" { * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ - export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; /* * Asynchronous readFile - Asynchronously reads the entire contents of a file. * @@ -1476,78 +1476,78 @@ declare module "fs" { * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ - export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; /* * Asynchronous readFile - Asynchronously reads the entire contents of a file. * * @param fileName * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. */ - export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; /* * Synchronous readFile - Synchronously reads the entire contents of a file. * * @param fileName * @param encoding */ - export function readFileSync(filename: string, encoding: string): string; + export function readFileSync(filename: string, encoding: string): string; /* * Synchronous readFile - Synchronously reads the entire contents of a file. * * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. */ - export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; + export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; /* * Synchronous readFile - Synchronously reads the entire contents of a file. * * @param fileName * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. */ - export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; - export function writeFile(filename: string|number, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFile(filename: string|number, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFile(filename: string|number, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; - export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; - export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; - export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; - export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; - export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; - export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; - export function exists(path: string, callback?: (exists: boolean) => void): void; - export function existsSync(path: string): boolean; - /** Constant for fs.access(). File is visible to the calling process. */ - export var F_OK: number; - /** Constant for fs.access(). File can be read by the calling process. */ - export var R_OK: number; - /** Constant for fs.access(). File can be written by the calling process. */ - export var W_OK: number; - /** Constant for fs.access(). File can be executed by the calling process. */ - export var X_OK: number; - /** Tests a user's permissions for the file specified by path. */ - export function access(path: string, callback: (err: NodeJS.ErrnoException) => void): void; - export function access(path: string, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; - /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ - export function accessSync(path: string, mode ?: number): void; - export function createReadStream(path: string, options?: { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - }): ReadStream; - export function createWriteStream(path: string, options?: { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - }): WriteStream; + export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; + export function writeFile(filename: string | number, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string | number, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string | number, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; + export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; + export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; + export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; + export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; + export function exists(path: string, callback?: (exists: boolean) => void): void; + export function existsSync(path: string): boolean; + /** Constant for fs.access(). File is visible to the calling process. */ + export var F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + export var R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + export var W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + export var X_OK: number; + /** Tests a user's permissions for the file specified by path. */ + export function access(path: string, callback: (err: NodeJS.ErrnoException) => void): void; + export function access(path: string, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; + /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ + export function accessSync(path: string, mode?: number): void; + export function createReadStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + }): ReadStream; + export function createWriteStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + }): WriteStream; } declare module "path" { @@ -1555,28 +1555,28 @@ declare module "path" { /** * A parsed path object generated by path.parse() or consumed by path.format(). */ - export interface ParsedPath { + export interface ParsedPath { /** * The root of the path such as '/' or 'c:\' */ - root: string; + root: string; /** * The full directory path such as '/home/user/dir' or 'c:\path\dir' */ - dir: string; + dir: string; /** * The file name including extension (if any) such as 'index.html' */ - base: string; + base: string; /** * The file extension (if any) such as '.html' */ - ext: string; + ext: string; /** * The file name without extension (if any) such as 'index' */ - name: string; - } + name: string; + } /** * Normalize a string path, reducing '..' and '.' parts. @@ -1584,21 +1584,21 @@ declare module "path" { * * @param p string path to normalize. */ - export function normalize(p: string): string; + export function normalize(p: string): string; /** * Join all arguments together and normalize the resulting path. * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. * * @param paths string paths to join. */ - export function join(...paths: any[]): string; + export function join(...paths: any[]): string; /** * Join all arguments together and normalize the resulting path. * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. * * @param paths string paths to join. */ - export function join(...paths: string[]): string; + export function join(...paths: string[]): string; /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * @@ -1608,13 +1608,13 @@ declare module "path" { * * @param pathSegments string paths to join. Non-string arguments are ignored. */ - export function resolve(...pathSegments: any[]): string; + export function resolve(...pathSegments: any[]): string; /** * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. * * @param path path to test. */ - export function isAbsolute(path: string): boolean; + export function isAbsolute(path: string): boolean; /** * Solve the relative path from {from} to {to}. * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. @@ -1622,13 +1622,13 @@ declare module "path" { * @param from * @param to */ - export function relative(from: string, to: string): string; + export function relative(from: string, to: string): string; /** * Return the directory name of a path. Similar to the Unix dirname command. * * @param p the path to evaluate. */ - export function dirname(p: string): string; + export function dirname(p: string): string; /** * Return the last portion of a path. Similar to the Unix basename command. * Often used to extract the file name from a fully qualified path. @@ -1636,677 +1636,679 @@ declare module "path" { * @param p the path to evaluate. * @param ext optionally, an extension to remove from the result. */ - export function basename(p: string, ext?: string): string; + export function basename(p: string, ext?: string): string; /** * Return the extension of the path, from the last '.' to end of string in the last portion of the path. * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string * * @param p the path to evaluate. */ - export function extname(p: string): string; + export function extname(p: string): string; /** * The platform-specific file separator. '\\' or '/'. */ - export var sep: string; + export var sep: string; /** * The platform-specific file delimiter. ';' or ':'. */ - export var delimiter: string; + export var delimiter: string; /** * Returns an object from a path string - the opposite of format(). * * @param pathString path to evaluate. */ - export function parse(pathString: string): ParsedPath; + export function parse(pathString: string): ParsedPath; /** * Returns a path string from an object - the opposite of parse(). * * @param pathString path to evaluate. */ - export function format(pathObject: ParsedPath): string; - - export module posix { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; - } - - export module win32 { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; - } + export function format(pathObject: ParsedPath): string; + + export module posix { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } + + export module win32 { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } } declare module "string_decoder" { - export interface NodeStringDecoder { - write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; - } - export var StringDecoder: { - new (encoding: string): NodeStringDecoder; - }; + export interface NodeStringDecoder { + write(buffer: Buffer): string; + detectIncompleteChar(buffer: Buffer): number; + } + export var StringDecoder: { + new (encoding: string): NodeStringDecoder; + }; } declare module "tls" { - import * as crypto from "crypto"; - import * as net from "net"; - import * as stream from "stream"; - - var CLIENT_RENEG_LIMIT: number; - var CLIENT_RENEG_WINDOW: number; - - export interface TlsOptions { - host?: string; - port?: number; - pfx?: any; //string or buffer - key?: any; //string or buffer - passphrase?: string; - cert?: any; - ca?: any; //string or buffer - crl?: any; //string or string array - ciphers?: string; - honorCipherOrder?: any; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; //array or Buffer; - SNICallback?: (servername: string) => any; - } - - export interface ConnectionOptions { - host?: string; - port?: number; - socket?: net.Socket; - pfx?: any; //string | Buffer - key?: any; //string | Buffer - passphrase?: string; - cert?: any; //string | Buffer - ca?: any; //Array of string | Buffer - rejectUnauthorized?: boolean; - NPNProtocols?: any; //Array of string | Buffer - servername?: string; - } - - export interface Server extends net.Server { - close(): Server; - address(): { port: number; family: string; address: string; }; - addContext(hostName: string, credentials: { - key: string; - cert: string; - ca: string; - }): void; - maxConnections: number; - connections: number; - } - - export interface ClearTextStream extends stream.Duplex { - authorized: boolean; - authorizationError: Error; - getPeerCertificate(): any; - getCipher: { - name: string; - version: string; - }; - address: { - port: number; - family: string; - address: string; - }; - remoteAddress: string; - remotePort: number; - } - - export interface SecurePair { - encrypted: any; - cleartext: any; - } - - export interface SecureContextOptions { - pfx?: any; //string | buffer - key?: any; //string | buffer - passphrase?: string; - cert?: any; // string | buffer - ca?: any; // string | buffer - crl?: any; // string | string[] - ciphers?: string; - honorCipherOrder?: boolean; - } - - export interface SecureContext { - context: any; - } - - export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; - export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; - export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; - export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; - export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; - export function createSecureContext(details: SecureContextOptions): SecureContext; + import * as crypto from "crypto"; + import * as net from "net"; + import * as stream from "stream"; + + var CLIENT_RENEG_LIMIT: number; + var CLIENT_RENEG_WINDOW: number; + + export interface TlsOptions { + host?: string; + port?: number; + pfx?: any; //string or buffer + key?: any; //string or buffer + passphrase?: string; + cert?: any; + ca?: any; //string or buffer + crl?: any; //string or string array + ciphers?: string; + honorCipherOrder?: any; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; //array or Buffer; + SNICallback?: (servername: string) => any; + } + + export interface ConnectionOptions { + host?: string; + port?: number; + socket?: net.Socket; + pfx?: any; //string | Buffer + key?: any; //string | Buffer + passphrase?: string; + cert?: any; //string | Buffer + ca?: any; //Array of string | Buffer + rejectUnauthorized?: boolean; + NPNProtocols?: any; //Array of string | Buffer + servername?: string; + } + + export interface Server extends net.Server { + close(): Server; + address(): { port: number; family: string; address: string; }; + addContext(hostName: string, credentials: { + key: string; + cert: string; + ca: string; + }): void; + maxConnections: number; + connections: number; + } + + export interface ClearTextStream extends stream.Duplex { + authorized: boolean; + authorizationError: Error; + getPeerCertificate(): any; + getCipher: { + name: string; + version: string; + }; + address: { + port: number; + family: string; + address: string; + }; + remoteAddress: string; + remotePort: number; + } + + export interface SecurePair { + encrypted: any; + cleartext: any; + } + + export interface SecureContextOptions { + pfx?: any; //string | buffer + key?: any; //string | buffer + passphrase?: string; + cert?: any; // string | buffer + ca?: any; // string | buffer + crl?: any; // string | string[] + ciphers?: string; + honorCipherOrder?: boolean; + } + + export interface SecureContext { + context: any; + } + + export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) => void): Server; + export function connect(options: TlsOptions, secureConnectionListener?: () => void): ClearTextStream; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; + export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + export function createSecureContext(details: SecureContextOptions): SecureContext; } declare module "crypto" { - export interface CredentialDetails { - pfx: string; - key: string; - passphrase: string; - cert: string; - ca: any; //string | string array - crl: any; //string | string array - ciphers: string; - } - export interface Credentials { context?: any; } - export function createCredentials(details: CredentialDetails): Credentials; - export function createHash(algorithm: string): Hash; - export function createHmac(algorithm: string, key: string): Hmac; - export function createHmac(algorithm: string, key: Buffer): Hmac; - export interface Hash { - update(data: any, input_encoding?: string): Hash; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): any; - digest(): Buffer; - } - export interface Hmac extends NodeJS.ReadWriteStream { - update(data: any, input_encoding?: string): Hmac; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): any; - digest(): Buffer; - } - export function createCipher(algorithm: string, password: any): Cipher; - export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; - export interface Cipher extends NodeJS.ReadWriteStream { - update(data: Buffer): Buffer; - update(data: string, input_encoding: "utf8"|"ascii"|"binary"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "binary"|"base64"|"hex"): string; - update(data: string, input_encoding: "utf8"|"ascii"|"binary", output_encoding: "binary"|"base64"|"hex"): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding: boolean): void; - getAuthTag(): Buffer; - } - export function createDecipher(algorithm: string, password: any): Decipher; - export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; - export interface Decipher extends NodeJS.ReadWriteStream { - update(data: Buffer): Buffer; - update(data: string, input_encoding: "binary"|"base64"|"hex"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "utf8"|"ascii"|"binary"): string; - update(data: string, input_encoding: "binary"|"base64"|"hex", output_encoding: "utf8"|"ascii"|"binary"): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding: boolean): void; - setAuthTag(tag: Buffer): void; - } - export function createSign(algorithm: string): Signer; - export interface Signer extends NodeJS.WritableStream { - update(data: any): void; - sign(private_key: string, output_format: string): string; - } - export function createVerify(algorith: string): Verify; - export interface Verify extends NodeJS.WritableStream { - update(data: any): void; - verify(object: string, signature: string, signature_format?: string): boolean; - } - export function createDiffieHellman(prime_length: number): DiffieHellman; - export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; - export interface DiffieHellman { - generateKeys(encoding?: string): string; - computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; - getPrime(encoding?: string): string; - getGenerator(encoding: string): string; - getPublicKey(encoding?: string): string; - getPrivateKey(encoding?: string): string; - setPublicKey(public_key: string, encoding?: string): void; - setPrivateKey(public_key: string, encoding?: string): void; - } - export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number) : Buffer; - export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string) : Buffer; - export function randomBytes(size: number): Buffer; - export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; - export function pseudoRandomBytes(size: number): Buffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; - export interface RsaPublicKey { - key: string; - padding?: any; - } - export interface RsaPrivateKey { - key: string; - passphrase?: string, - padding?: any; - } - export function publicEncrypt(public_key: string|RsaPublicKey, buffer: Buffer): Buffer - export function privateDecrypt(private_key: string|RsaPrivateKey, buffer: Buffer): Buffer + export interface CredentialDetails { + pfx: string; + key: string; + passphrase: string; + cert: string; + ca: any; //string | string array + crl: any; //string | string array + ciphers: string; + } + export interface Credentials { context?: any; } + export function createCredentials(details: CredentialDetails): Credentials; + export function createHash(algorithm: string): Hash; + export function createHmac(algorithm: string, key: string): Hmac; + export function createHmac(algorithm: string, key: Buffer): Hmac; + export interface Hash { + update(data: any, input_encoding?: string): Hash; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; + digest(): Buffer; + } + export interface Hmac extends NodeJS.ReadWriteStream { + update(data: any, input_encoding?: string): Hmac; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; + digest(): Buffer; + } + export function createCipher(algorithm: string, password: any): Cipher; + export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; + export interface Cipher extends NodeJS.ReadWriteStream { + update(data: Buffer): Buffer; + update(data: string, input_encoding: "utf8" | "ascii" | "binary"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "binary" | "base64" | "hex"): string; + update(data: string, input_encoding: "utf8" | "ascii" | "binary", output_encoding: "binary" | "base64" | "hex"): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding: boolean): void; + getAuthTag(): Buffer; + } + export function createDecipher(algorithm: string, password: any): Decipher; + export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; + export interface Decipher extends NodeJS.ReadWriteStream { + update(data: Buffer): Buffer; + update(data: string, input_encoding: "binary" | "base64" | "hex"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "utf8" | "ascii" | "binary"): string; + update(data: string, input_encoding: "binary" | "base64" | "hex", output_encoding: "utf8" | "ascii" | "binary"): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding: boolean): void; + setAuthTag(tag: Buffer): void; + } + export function createSign(algorithm: string): Signer; + export interface Signer extends NodeJS.WritableStream { + update(data: any): void; + sign(private_key: string, output_format: string): string; + } + export function createVerify(algorith: string): Verify; + export interface Verify extends NodeJS.WritableStream { + update(data: any): void; + verify(object: string, signature: string, signature_format?: string): boolean; + } + export function createDiffieHellman(prime_length: number): DiffieHellman; + export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; + export interface DiffieHellman { + generateKeys(encoding?: string): string; + computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; + getPrime(encoding?: string): string; + getGenerator(encoding: string): string; + getPublicKey(encoding?: string): string; + getPrivateKey(encoding?: string): string; + setPublicKey(public_key: string, encoding?: string): void; + setPrivateKey(public_key: string, encoding?: string): void; + } + export function getDiffieHellman(group_name: string): DiffieHellman; + export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number): Buffer; + export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; + export function randomBytes(size: number): Buffer; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; + export function pseudoRandomBytes(size: number): Buffer; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; + export interface RsaPublicKey { + key: string; + padding?: any; + } + export interface RsaPrivateKey { + key: string; + passphrase?: string, + padding?: any; + } + export function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer + export function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer } declare module "stream" { - import * as events from "events"; - - export class Stream extends events.EventEmitter { - pipe(destination: T, options?: { end?: boolean; }): T; - } - - export interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - } - - export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { - readable: boolean; - constructor(opts?: ReadableOptions); - _read(size: number): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - destroy(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - } - - export interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - objectMode?: boolean; - } - - export class Writable extends events.EventEmitter implements NodeJS.WritableStream { - writable: boolean; - constructor(opts?: WritableOptions); - _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - } - - // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements NodeJS.ReadWriteStream { - writable: boolean; - constructor(opts?: DuplexOptions); - _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export interface TransformOptions extends ReadableOptions, WritableOptions {} - - // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { - readable: boolean; - writable: boolean; - constructor(opts?: TransformOptions); - _transform(chunk: any, encoding: string, callback: Function): void; - _flush(callback: Function): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export class PassThrough extends Transform {} + import * as events from "events"; + + export class Stream extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + } + + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + destroy(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + } + + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + } + + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + } + + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements NodeJS.ReadWriteStream { + writable: boolean; + constructor(opts?: DuplexOptions); + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export interface TransformOptions extends ReadableOptions, WritableOptions { } + + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { + readable: boolean; + writable: boolean; + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: string, callback: Function): void; + _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export class PassThrough extends Transform { } } declare module "util" { - export interface InspectOptions { - showHidden?: boolean; - depth?: number; - colors?: boolean; - customInspect?: boolean; - } - - export function format(format: any, ...param: any[]): string; - export function debug(string: string): void; - export function error(...param: any[]): void; - export function puts(...param: any[]): void; - export function print(...param: any[]): void; - export function log(string: string): void; - export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; - export function inspect(object: any, options: InspectOptions): string; - export function isArray(object: any): boolean; - export function isRegExp(object: any): boolean; - export function isDate(object: any): boolean; - export function isError(object: any): boolean; - export function inherits(constructor: any, superConstructor: any): void; - export function debuglog(key:string): (msg:string,...param: any[])=>void; + export interface InspectOptions { + showHidden?: boolean; + depth?: number; + colors?: boolean; + customInspect?: boolean; + } + + export function format(format: any, ...param: any[]): string; + export function debug(string: string): void; + export function error(...param: any[]): void; + export function puts(...param: any[]): void; + export function print(...param: any[]): void; + export function log(string: string): void; + export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + export function isArray(object: any): boolean; + export function isRegExp(object: any): boolean; + export function isDate(object: any): boolean; + export function isError(object: any): boolean; + export function inherits(constructor: any, superConstructor: any): void; + export function debuglog(key: string): (msg: string, ...param: any[]) => void; } declare module "assert" { - function internal (value: any, message?: string): void; - namespace internal { - export class AssertionError implements Error { - name: string; - message: string; - actual: any; - expected: any; - operator: string; - generatedMessage: boolean; - - constructor(options?: {message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function}); - } - - export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; - export function ok(value: any, message?: string): void; - export function equal(actual: any, expected: any, message?: string): void; - export function notEqual(actual: any, expected: any, message?: string): void; - export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; - export function strictEqual(actual: any, expected: any, message?: string): void; - export function notStrictEqual(actual: any, expected: any, message?: string): void; - export function deepStrictEqual(actual: any, expected: any, message?: string): void; - export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; - export var throws: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - - export var doesNotThrow: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - - export function ifError(value: any): void; - } - - export = internal; + function internal(value: any, message?: string): void; + namespace internal { + export class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function + }); + } + + export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; + export function ok(value: any, message?: string): void; + export function equal(actual: any, expected: any, message?: string): void; + export function notEqual(actual: any, expected: any, message?: string): void; + export function deepEqual(actual: any, expected: any, message?: string): void; + export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function strictEqual(actual: any, expected: any, message?: string): void; + export function notStrictEqual(actual: any, expected: any, message?: string): void; + export function deepStrictEqual(actual: any, expected: any, message?: string): void; + export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; + export var throws: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export var doesNotThrow: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export function ifError(value: any): void; + } + + export = internal; } declare module "tty" { - import * as net from "net"; - - export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { - isRaw: boolean; - setRawMode(mode: boolean): void; - isTTY: boolean; - } - export interface WriteStream extends net.Socket { - columns: number; - rows: number; - isTTY: boolean; - } + import * as net from "net"; + + export function isatty(fd: number): boolean; + export interface ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + isTTY: boolean; + } + export interface WriteStream extends net.Socket { + columns: number; + rows: number; + isTTY: boolean; + } } declare module "domain" { - import * as events from "events"; - - export class Domain extends events.EventEmitter implements NodeJS.Domain { - run(fn: Function): void; - add(emitter: events.EventEmitter): void; - remove(emitter: events.EventEmitter): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; - } - - export function create(): Domain; + import * as events from "events"; + + export class Domain extends events.EventEmitter implements NodeJS.Domain { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + } + + export function create(): Domain; } declare module "constants" { - export var E2BIG: number; - export var EACCES: number; - export var EADDRINUSE: number; - export var EADDRNOTAVAIL: number; - export var EAFNOSUPPORT: number; - export var EAGAIN: number; - export var EALREADY: number; - export var EBADF: number; - export var EBADMSG: number; - export var EBUSY: number; - export var ECANCELED: number; - export var ECHILD: number; - export var ECONNABORTED: number; - export var ECONNREFUSED: number; - export var ECONNRESET: number; - export var EDEADLK: number; - export var EDESTADDRREQ: number; - export var EDOM: number; - export var EEXIST: number; - export var EFAULT: number; - export var EFBIG: number; - export var EHOSTUNREACH: number; - export var EIDRM: number; - export var EILSEQ: number; - export var EINPROGRESS: number; - export var EINTR: number; - export var EINVAL: number; - export var EIO: number; - export var EISCONN: number; - export var EISDIR: number; - export var ELOOP: number; - export var EMFILE: number; - export var EMLINK: number; - export var EMSGSIZE: number; - export var ENAMETOOLONG: number; - export var ENETDOWN: number; - export var ENETRESET: number; - export var ENETUNREACH: number; - export var ENFILE: number; - export var ENOBUFS: number; - export var ENODATA: number; - export var ENODEV: number; - export var ENOENT: number; - export var ENOEXEC: number; - export var ENOLCK: number; - export var ENOLINK: number; - export var ENOMEM: number; - export var ENOMSG: number; - export var ENOPROTOOPT: number; - export var ENOSPC: number; - export var ENOSR: number; - export var ENOSTR: number; - export var ENOSYS: number; - export var ENOTCONN: number; - export var ENOTDIR: number; - export var ENOTEMPTY: number; - export var ENOTSOCK: number; - export var ENOTSUP: number; - export var ENOTTY: number; - export var ENXIO: number; - export var EOPNOTSUPP: number; - export var EOVERFLOW: number; - export var EPERM: number; - export var EPIPE: number; - export var EPROTO: number; - export var EPROTONOSUPPORT: number; - export var EPROTOTYPE: number; - export var ERANGE: number; - export var EROFS: number; - export var ESPIPE: number; - export var ESRCH: number; - export var ETIME: number; - export var ETIMEDOUT: number; - export var ETXTBSY: number; - export var EWOULDBLOCK: number; - export var EXDEV: number; - export var WSAEINTR: number; - export var WSAEBADF: number; - export var WSAEACCES: number; - export var WSAEFAULT: number; - export var WSAEINVAL: number; - export var WSAEMFILE: number; - export var WSAEWOULDBLOCK: number; - export var WSAEINPROGRESS: number; - export var WSAEALREADY: number; - export var WSAENOTSOCK: number; - export var WSAEDESTADDRREQ: number; - export var WSAEMSGSIZE: number; - export var WSAEPROTOTYPE: number; - export var WSAENOPROTOOPT: number; - export var WSAEPROTONOSUPPORT: number; - export var WSAESOCKTNOSUPPORT: number; - export var WSAEOPNOTSUPP: number; - export var WSAEPFNOSUPPORT: number; - export var WSAEAFNOSUPPORT: number; - export var WSAEADDRINUSE: number; - export var WSAEADDRNOTAVAIL: number; - export var WSAENETDOWN: number; - export var WSAENETUNREACH: number; - export var WSAENETRESET: number; - export var WSAECONNABORTED: number; - export var WSAECONNRESET: number; - export var WSAENOBUFS: number; - export var WSAEISCONN: number; - export var WSAENOTCONN: number; - export var WSAESHUTDOWN: number; - export var WSAETOOMANYREFS: number; - export var WSAETIMEDOUT: number; - export var WSAECONNREFUSED: number; - export var WSAELOOP: number; - export var WSAENAMETOOLONG: number; - export var WSAEHOSTDOWN: number; - export var WSAEHOSTUNREACH: number; - export var WSAENOTEMPTY: number; - export var WSAEPROCLIM: number; - export var WSAEUSERS: number; - export var WSAEDQUOT: number; - export var WSAESTALE: number; - export var WSAEREMOTE: number; - export var WSASYSNOTREADY: number; - export var WSAVERNOTSUPPORTED: number; - export var WSANOTINITIALISED: number; - export var WSAEDISCON: number; - export var WSAENOMORE: number; - export var WSAECANCELLED: number; - export var WSAEINVALIDPROCTABLE: number; - export var WSAEINVALIDPROVIDER: number; - export var WSAEPROVIDERFAILEDINIT: number; - export var WSASYSCALLFAILURE: number; - export var WSASERVICE_NOT_FOUND: number; - export var WSATYPE_NOT_FOUND: number; - export var WSA_E_NO_MORE: number; - export var WSA_E_CANCELLED: number; - export var WSAEREFUSED: number; - export var SIGHUP: number; - export var SIGINT: number; - export var SIGILL: number; - export var SIGABRT: number; - export var SIGFPE: number; - export var SIGKILL: number; - export var SIGSEGV: number; - export var SIGTERM: number; - export var SIGBREAK: number; - export var SIGWINCH: number; - export var SSL_OP_ALL: number; - export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; - export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; - export var SSL_OP_CISCO_ANYCONNECT: number; - export var SSL_OP_COOKIE_EXCHANGE: number; - export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; - export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - export var SSL_OP_EPHEMERAL_RSA: number; - export var SSL_OP_LEGACY_SERVER_CONNECT: number; - export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; - export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; - export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; - export var SSL_OP_NETSCAPE_CA_DN_BUG: number; - export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; - export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NO_COMPRESSION: number; - export var SSL_OP_NO_QUERY_MTU: number; - export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; - export var SSL_OP_NO_SSLv2: number; - export var SSL_OP_NO_SSLv3: number; - export var SSL_OP_NO_TICKET: number; - export var SSL_OP_NO_TLSv1: number; - export var SSL_OP_NO_TLSv1_1: number; - export var SSL_OP_NO_TLSv1_2: number; - export var SSL_OP_PKCS1_CHECK_1: number; - export var SSL_OP_PKCS1_CHECK_2: number; - export var SSL_OP_SINGLE_DH_USE: number; - export var SSL_OP_SINGLE_ECDH_USE: number; - export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; - export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; - export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; - export var SSL_OP_TLS_D5_BUG: number; - export var SSL_OP_TLS_ROLLBACK_BUG: number; - export var ENGINE_METHOD_DSA: number; - export var ENGINE_METHOD_DH: number; - export var ENGINE_METHOD_RAND: number; - export var ENGINE_METHOD_ECDH: number; - export var ENGINE_METHOD_ECDSA: number; - export var ENGINE_METHOD_CIPHERS: number; - export var ENGINE_METHOD_DIGESTS: number; - export var ENGINE_METHOD_STORE: number; - export var ENGINE_METHOD_PKEY_METHS: number; - export var ENGINE_METHOD_PKEY_ASN1_METHS: number; - export var ENGINE_METHOD_ALL: number; - export var ENGINE_METHOD_NONE: number; - export var DH_CHECK_P_NOT_SAFE_PRIME: number; - export var DH_CHECK_P_NOT_PRIME: number; - export var DH_UNABLE_TO_CHECK_GENERATOR: number; - export var DH_NOT_SUITABLE_GENERATOR: number; - export var NPN_ENABLED: number; - export var RSA_PKCS1_PADDING: number; - export var RSA_SSLV23_PADDING: number; - export var RSA_NO_PADDING: number; - export var RSA_PKCS1_OAEP_PADDING: number; - export var RSA_X931_PADDING: number; - export var RSA_PKCS1_PSS_PADDING: number; - export var POINT_CONVERSION_COMPRESSED: number; - export var POINT_CONVERSION_UNCOMPRESSED: number; - export var POINT_CONVERSION_HYBRID: number; - export var O_RDONLY: number; - export var O_WRONLY: number; - export var O_RDWR: number; - export var S_IFMT: number; - export var S_IFREG: number; - export var S_IFDIR: number; - export var S_IFCHR: number; - export var S_IFLNK: number; - export var O_CREAT: number; - export var O_EXCL: number; - export var O_TRUNC: number; - export var O_APPEND: number; - export var F_OK: number; - export var R_OK: number; - export var W_OK: number; - export var X_OK: number; - export var UV_UDP_REUSEADDR: number; + export var E2BIG: number; + export var EACCES: number; + export var EADDRINUSE: number; + export var EADDRNOTAVAIL: number; + export var EAFNOSUPPORT: number; + export var EAGAIN: number; + export var EALREADY: number; + export var EBADF: number; + export var EBADMSG: number; + export var EBUSY: number; + export var ECANCELED: number; + export var ECHILD: number; + export var ECONNABORTED: number; + export var ECONNREFUSED: number; + export var ECONNRESET: number; + export var EDEADLK: number; + export var EDESTADDRREQ: number; + export var EDOM: number; + export var EEXIST: number; + export var EFAULT: number; + export var EFBIG: number; + export var EHOSTUNREACH: number; + export var EIDRM: number; + export var EILSEQ: number; + export var EINPROGRESS: number; + export var EINTR: number; + export var EINVAL: number; + export var EIO: number; + export var EISCONN: number; + export var EISDIR: number; + export var ELOOP: number; + export var EMFILE: number; + export var EMLINK: number; + export var EMSGSIZE: number; + export var ENAMETOOLONG: number; + export var ENETDOWN: number; + export var ENETRESET: number; + export var ENETUNREACH: number; + export var ENFILE: number; + export var ENOBUFS: number; + export var ENODATA: number; + export var ENODEV: number; + export var ENOENT: number; + export var ENOEXEC: number; + export var ENOLCK: number; + export var ENOLINK: number; + export var ENOMEM: number; + export var ENOMSG: number; + export var ENOPROTOOPT: number; + export var ENOSPC: number; + export var ENOSR: number; + export var ENOSTR: number; + export var ENOSYS: number; + export var ENOTCONN: number; + export var ENOTDIR: number; + export var ENOTEMPTY: number; + export var ENOTSOCK: number; + export var ENOTSUP: number; + export var ENOTTY: number; + export var ENXIO: number; + export var EOPNOTSUPP: number; + export var EOVERFLOW: number; + export var EPERM: number; + export var EPIPE: number; + export var EPROTO: number; + export var EPROTONOSUPPORT: number; + export var EPROTOTYPE: number; + export var ERANGE: number; + export var EROFS: number; + export var ESPIPE: number; + export var ESRCH: number; + export var ETIME: number; + export var ETIMEDOUT: number; + export var ETXTBSY: number; + export var EWOULDBLOCK: number; + export var EXDEV: number; + export var WSAEINTR: number; + export var WSAEBADF: number; + export var WSAEACCES: number; + export var WSAEFAULT: number; + export var WSAEINVAL: number; + export var WSAEMFILE: number; + export var WSAEWOULDBLOCK: number; + export var WSAEINPROGRESS: number; + export var WSAEALREADY: number; + export var WSAENOTSOCK: number; + export var WSAEDESTADDRREQ: number; + export var WSAEMSGSIZE: number; + export var WSAEPROTOTYPE: number; + export var WSAENOPROTOOPT: number; + export var WSAEPROTONOSUPPORT: number; + export var WSAESOCKTNOSUPPORT: number; + export var WSAEOPNOTSUPP: number; + export var WSAEPFNOSUPPORT: number; + export var WSAEAFNOSUPPORT: number; + export var WSAEADDRINUSE: number; + export var WSAEADDRNOTAVAIL: number; + export var WSAENETDOWN: number; + export var WSAENETUNREACH: number; + export var WSAENETRESET: number; + export var WSAECONNABORTED: number; + export var WSAECONNRESET: number; + export var WSAENOBUFS: number; + export var WSAEISCONN: number; + export var WSAENOTCONN: number; + export var WSAESHUTDOWN: number; + export var WSAETOOMANYREFS: number; + export var WSAETIMEDOUT: number; + export var WSAECONNREFUSED: number; + export var WSAELOOP: number; + export var WSAENAMETOOLONG: number; + export var WSAEHOSTDOWN: number; + export var WSAEHOSTUNREACH: number; + export var WSAENOTEMPTY: number; + export var WSAEPROCLIM: number; + export var WSAEUSERS: number; + export var WSAEDQUOT: number; + export var WSAESTALE: number; + export var WSAEREMOTE: number; + export var WSASYSNOTREADY: number; + export var WSAVERNOTSUPPORTED: number; + export var WSANOTINITIALISED: number; + export var WSAEDISCON: number; + export var WSAENOMORE: number; + export var WSAECANCELLED: number; + export var WSAEINVALIDPROCTABLE: number; + export var WSAEINVALIDPROVIDER: number; + export var WSAEPROVIDERFAILEDINIT: number; + export var WSASYSCALLFAILURE: number; + export var WSASERVICE_NOT_FOUND: number; + export var WSATYPE_NOT_FOUND: number; + export var WSA_E_NO_MORE: number; + export var WSA_E_CANCELLED: number; + export var WSAEREFUSED: number; + export var SIGHUP: number; + export var SIGINT: number; + export var SIGILL: number; + export var SIGABRT: number; + export var SIGFPE: number; + export var SIGKILL: number; + export var SIGSEGV: number; + export var SIGTERM: number; + export var SIGBREAK: number; + export var SIGWINCH: number; + export var SSL_OP_ALL: number; + export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; + export var SSL_OP_CISCO_ANYCONNECT: number; + export var SSL_OP_COOKIE_EXCHANGE: number; + export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + export var SSL_OP_EPHEMERAL_RSA: number; + export var SSL_OP_LEGACY_SERVER_CONNECT: number; + export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; + export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + export var SSL_OP_NETSCAPE_CA_DN_BUG: number; + export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NO_COMPRESSION: number; + export var SSL_OP_NO_QUERY_MTU: number; + export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + export var SSL_OP_NO_SSLv2: number; + export var SSL_OP_NO_SSLv3: number; + export var SSL_OP_NO_TICKET: number; + export var SSL_OP_NO_TLSv1: number; + export var SSL_OP_NO_TLSv1_1: number; + export var SSL_OP_NO_TLSv1_2: number; + export var SSL_OP_PKCS1_CHECK_1: number; + export var SSL_OP_PKCS1_CHECK_2: number; + export var SSL_OP_SINGLE_DH_USE: number; + export var SSL_OP_SINGLE_ECDH_USE: number; + export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; + export var SSL_OP_TLS_D5_BUG: number; + export var SSL_OP_TLS_ROLLBACK_BUG: number; + export var ENGINE_METHOD_DSA: number; + export var ENGINE_METHOD_DH: number; + export var ENGINE_METHOD_RAND: number; + export var ENGINE_METHOD_ECDH: number; + export var ENGINE_METHOD_ECDSA: number; + export var ENGINE_METHOD_CIPHERS: number; + export var ENGINE_METHOD_DIGESTS: number; + export var ENGINE_METHOD_STORE: number; + export var ENGINE_METHOD_PKEY_METHS: number; + export var ENGINE_METHOD_PKEY_ASN1_METHS: number; + export var ENGINE_METHOD_ALL: number; + export var ENGINE_METHOD_NONE: number; + export var DH_CHECK_P_NOT_SAFE_PRIME: number; + export var DH_CHECK_P_NOT_PRIME: number; + export var DH_UNABLE_TO_CHECK_GENERATOR: number; + export var DH_NOT_SUITABLE_GENERATOR: number; + export var NPN_ENABLED: number; + export var RSA_PKCS1_PADDING: number; + export var RSA_SSLV23_PADDING: number; + export var RSA_NO_PADDING: number; + export var RSA_PKCS1_OAEP_PADDING: number; + export var RSA_X931_PADDING: number; + export var RSA_PKCS1_PSS_PADDING: number; + export var POINT_CONVERSION_COMPRESSED: number; + export var POINT_CONVERSION_UNCOMPRESSED: number; + export var POINT_CONVERSION_HYBRID: number; + export var O_RDONLY: number; + export var O_WRONLY: number; + export var O_RDWR: number; + export var S_IFMT: number; + export var S_IFREG: number; + export var S_IFDIR: number; + export var S_IFCHR: number; + export var S_IFLNK: number; + export var O_CREAT: number; + export var O_EXCL: number; + export var O_TRUNC: number; + export var O_APPEND: number; + export var F_OK: number; + export var R_OK: number; + export var W_OK: number; + export var X_OK: number; + export var UV_UDP_REUSEADDR: number; } \ No newline at end of file diff --git a/src/typings/semver.d.ts b/src/typings/semver.d.ts index cb8efa4f50062..129a83e21fa44 100644 --- a/src/typings/semver.d.ts +++ b/src/typings/semver.d.ts @@ -7,119 +7,119 @@ declare module SemVerModule { /** * Return the parsed version, or null if it's not valid. */ - function valid(v: string, loose?: boolean): string; + function valid(v: string, loose?: boolean): string; /** * Return the version incremented by the release type (major, minor, patch, or prerelease), or null if it's not valid. */ - function inc(v: string, release: string, loose?: boolean): string; + function inc(v: string, release: string, loose?: boolean): string; - // Comparison + // Comparison /** * v1 > v2 */ - function gt(v1: string, v2: string, loose?: boolean): boolean; + function gt(v1: string, v2: string, loose?: boolean): boolean; /** * v1 >= v2 */ - function gte(v1: string, v2: string, loose?: boolean): boolean; + function gte(v1: string, v2: string, loose?: boolean): boolean; /** * v1 < v2 */ - function lt(v1: string, v2: string, loose?: boolean): boolean; + function lt(v1: string, v2: string, loose?: boolean): boolean; /** * v1 <= v2 */ - function lte(v1: string, v2: string, loose?: boolean): boolean; + function lte(v1: string, v2: string, loose?: boolean): boolean; /** * v1 == v2 This is true if they're logically equivalent, even if they're not the exact same string. You already know how to compare strings. */ - function eq(v1: string, v2: string, loose?: boolean): boolean; + function eq(v1: string, v2: string, loose?: boolean): boolean; /** * v1 != v2 The opposite of eq. */ - function neq(v1: string, v2: string, loose?: boolean): boolean; + function neq(v1: string, v2: string, loose?: boolean): boolean; /** * Pass in a comparison string, and it'll call the corresponding semver comparison function. "===" and "!==" do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. */ - function cmp(v1: string, comparator: any, v2: string, loose?: boolean): boolean; + function cmp(v1: string, comparator: any, v2: string, loose?: boolean): boolean; /** * Return 0 if v1 == v2, or 1 if v1 is greater, or -1 if v2 is greater. Sorts in ascending order if passed to Array.sort(). */ - function compare(v1: string, v2: string, loose?: boolean): number; + function compare(v1: string, v2: string, loose?: boolean): number; /** * The reverse of compare. Sorts an array of versions in descending order when passed to Array.sort(). */ - function rcompare(v1: string, v2: string, loose?: boolean): number; + function rcompare(v1: string, v2: string, loose?: boolean): number; - // Ranges + // Ranges /** * Return the valid range or null if it's not valid */ - function validRange(range: string, loose?: boolean): string; + function validRange(range: string, loose?: boolean): string; /** * Return true if the version satisfies the range. */ - function satisfies(version: string, range: string, loose?: boolean): boolean; + function satisfies(version: string, range: string, loose?: boolean): boolean; /** * Return the highest version in the list that satisfies the range, or null if none of them do. */ - function maxSatisfying(versions: string[], range: string, loose?: boolean): string; + function maxSatisfying(versions: string[], range: string, loose?: boolean): string; /** * Return true if version is greater than all the versions possible in the range. */ - function gtr(version: string, range: string, loose?: boolean): boolean; + function gtr(version: string, range: string, loose?: boolean): boolean; /** * Return true if version is less than all the versions possible in the range. */ - function ltr(version: string, range: string, loose?: boolean): boolean; + function ltr(version: string, range: string, loose?: boolean): boolean; /** * Return true if the version is outside the bounds of the range in either the high or low direction. The hilo argument must be either the string '>' or '<'. (This is the function called by gtr and ltr.) */ - function outside(version: string, range: string, hilo: string, loose?: boolean): boolean; + function outside(version: string, range: string, hilo: string, loose?: boolean): boolean; - class SemVerBase { - raw: string; - loose: boolean; - format(): string; - inspect(): string; - toString(): string; - } + class SemVerBase { + raw: string; + loose: boolean; + format(): string; + inspect(): string; + toString(): string; + } - class SemVer extends SemVerBase { - constructor(version: string, loose?: boolean); + class SemVer extends SemVerBase { + constructor(version: string, loose?: boolean); - major: number; - minor: number; - patch: number; - version: string; - build: string[]; - prerelease: string[]; + major: number; + minor: number; + patch: number; + version: string; + build: string[]; + prerelease: string[]; - compare(other:SemVer): number; - compareMain(other:SemVer): number; - comparePre(other:SemVer): number; - inc(release: string): SemVer; - } + compare(other: SemVer): number; + compareMain(other: SemVer): number; + comparePre(other: SemVer): number; + inc(release: string): SemVer; + } - class Comparator extends SemVerBase { - constructor(comp: string, loose?: boolean); + class Comparator extends SemVerBase { + constructor(comp: string, loose?: boolean); - semver: SemVer; - operator: string; - value: boolean; - parse(comp: string): void; - test(version:SemVer): boolean; - } + semver: SemVer; + operator: string; + value: boolean; + parse(comp: string): void; + test(version: SemVer): boolean; + } - class Range extends SemVerBase { - constructor(range: string, loose?: boolean); + class Range extends SemVerBase { + constructor(range: string, loose?: boolean); - set: Comparator[][]; - parseRange(range: string): Comparator[]; - test(version: SemVer): boolean; - } + set: Comparator[][]; + parseRange(range: string): Comparator[]; + test(version: SemVer): boolean; + } } declare module "semver" { - export = SemVerModule; + export = SemVerModule; } diff --git a/src/typings/winreg.d.ts b/src/typings/winreg.d.ts index 773b450af2d2f..10efb9d72a0d4 100644 --- a/src/typings/winreg.d.ts +++ b/src/typings/winreg.d.ts @@ -5,21 +5,21 @@ declare module winreg { export interface IRegValue { - host: string; - hive: any; - key: string; - name: string; - type: string; - value: any; - } + host: string; + hive: any; + key: string; + name: string; + type: string; + value: any; + } export interface IWinRegConfig { - hive: any; - key: string; + hive: any; + key: string; } export interface IRegValuesCallback { - (error: Error, items: IRegValue[]): void; + (error: Error, items: IRegValue[]): void; } export interface IWinReg { @@ -31,17 +31,17 @@ declare module winreg { /** * list the subkeys of this key */ - keys(callback: (error:Error, keys: string[])=> void): void; + keys(callback: (error: Error, keys: string[]) => void): void; /** * gets a value by it's name */ - get(name: string, callback: (error: Error, item: IRegValue)=> void): void; + get(name: string, callback: (error: Error, item: IRegValue) => void): void; /** * sets a value */ - set(name:string, type: string, value: string, callback: (error:string) => void): void; + set(name: string, type: string, value: string, callback: (error: string) => void): void; /** * remove the value with the given key @@ -51,12 +51,12 @@ declare module winreg { /** * create this key */ - create(callback: (error:Error) => void): void; + create(callback: (error: Error) => void): void; /** * remove this key */ - erase(callback: (error:Error)=> void): void; + erase(callback: (error: Error) => void): void; /** * a new Winreg instance initialized with the parent ke @@ -70,7 +70,7 @@ declare module winreg { } export interface IWinRegFactory { - new(config: IWinRegConfig): IWinReg; + new (config: IWinRegConfig): IWinReg; // hives HKLM: string; @@ -81,16 +81,16 @@ declare module winreg { // types REG_SZ: string; - REG_MULTI_SZ: string; - REG_EXPAND_SZ: string; - REG_DWORD: string; - REG_QWORD: string; - REG_BINARY: string; - REG_NONE: string; + REG_MULTI_SZ: string; + REG_EXPAND_SZ: string; + REG_DWORD: string; + REG_QWORD: string; + REG_BINARY: string; + REG_NONE: string; } } declare module 'winreg' { - var winreg: winreg.IWinRegFactory; - export = winreg; + var winreg: winreg.IWinRegFactory; + export = winreg; } \ No newline at end of file diff --git a/src/typings/xterm.d.ts b/src/typings/xterm.d.ts index 7279edf0d3a81..4c7f7744ce1cf 100644 --- a/src/typings/xterm.d.ts +++ b/src/typings/xterm.d.ts @@ -13,5 +13,5 @@ declare module 'xterm' { resize(columns: number, rows: number): void; } - export = init; + export = init; } \ No newline at end of file diff --git a/src/typings/yauzl.d.ts b/src/typings/yauzl.d.ts index e9f24e5e2ca3d..3bc78861ae938 100644 --- a/src/typings/yauzl.d.ts +++ b/src/typings/yauzl.d.ts @@ -31,7 +31,7 @@ declare module 'yauzl' { } export class ZipFile extends EventEmitter { - openReadStream(entry: Entry, callback: (err?: Error, stream?: Readable)=>void); + openReadStream(entry: Entry, callback: (err?: Error, stream?: Readable) => void); close(); isOpen: boolean; entryCount: number; @@ -42,6 +42,6 @@ declare module 'yauzl' { autoClose: boolean; } - export function open(path: string, callback: (err?: Error, zipfile?: ZipFile)=>void): void; - export function open(path: string, options: IOptions, callback: (err?: Error, zipfile?: ZipFile)=>void): void; + export function open(path: string, callback: (err?: Error, zipfile?: ZipFile) => void): void; + export function open(path: string, options: IOptions, callback: (err?: Error, zipfile?: ZipFile) => void): void; } \ No newline at end of file diff --git a/src/vs/base/browser/browser.ts b/src/vs/base/browser/browser.ts index 468cd72461667..1a85e88af6192 100644 --- a/src/vs/base/browser/browser.ts +++ b/src/vs/base/browser/browser.ts @@ -6,8 +6,8 @@ import types = require('vs/base/common/types'); import * as Platform from 'vs/base/common/platform'; -import Event, {Emitter} from 'vs/base/common/event'; -import {IDisposable} from 'vs/base/common/lifecycle'; +import Event, { Emitter } from 'vs/base/common/event'; +import { IDisposable } from 'vs/base/common/lifecycle'; class ZoomManager { @@ -18,13 +18,13 @@ class ZoomManager { private _pixelRatioComputed: boolean = false; private _onDidChangeZoomLevel: Emitter = new Emitter(); - public onDidChangeZoomLevel:Event = this._onDidChangeZoomLevel.event; + public onDidChangeZoomLevel: Event = this._onDidChangeZoomLevel.event; public getZoomLevel(): number { return this._zoomLevel; } - public setZoomLevel(zoomLevel:number): void { + public setZoomLevel(zoomLevel: number): void { if (this._zoomLevel === zoomLevel) { return; } @@ -45,11 +45,11 @@ class ZoomManager { private _computePixelRatio(): number { let ctx = document.createElement('canvas').getContext('2d'); let dpr = window.devicePixelRatio || 1; - let bsr = (ctx).webkitBackingStorePixelRatio || - (ctx).mozBackingStorePixelRatio || - (ctx).msBackingStorePixelRatio || - (ctx).oBackingStorePixelRatio || - (ctx).backingStorePixelRatio || 1; + let bsr = (ctx).webkitBackingStorePixelRatio || + (ctx).mozBackingStorePixelRatio || + (ctx).msBackingStorePixelRatio || + (ctx).oBackingStorePixelRatio || + (ctx).backingStorePixelRatio || 1; return dpr / bsr; } } @@ -60,10 +60,10 @@ export function getZoomLevel(): number { export function getPixelRatio(): number { return ZoomManager.INSTANCE.getPixelRatio(); } -export function setZoomLevel(zoomLevel:number): void { +export function setZoomLevel(zoomLevel: number): void { ZoomManager.INSTANCE.setZoomLevel(zoomLevel); } -export function onDidChangeZoomLevel(callback:(zoomLevel:number)=>void): IDisposable { +export function onDidChangeZoomLevel(callback: (zoomLevel: number) => void): IDisposable { return ZoomManager.INSTANCE.onDidChangeZoomLevel(callback); } diff --git a/src/vs/base/browser/builder.ts b/src/vs/base/browser/builder.ts index 231deb5e55376..fd1f4e809dd5a 100644 --- a/src/vs/base/browser/builder.ts +++ b/src/vs/base/browser/builder.ts @@ -5,9 +5,9 @@ 'use strict'; import 'vs/css!./builder'; -import {TPromise} from 'vs/base/common/winjs.base'; +import { TPromise } from 'vs/base/common/winjs.base'; import types = require('vs/base/common/types'); -import {IDisposable, dispose} from 'vs/base/common/lifecycle'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import strings = require('vs/base/common/strings'); import assert = require('vs/base/common/assert'); import DOM = require('vs/base/browser/dom'); @@ -183,7 +183,7 @@ export class Builder implements IDisposable { } // Wrap Builders into MultiBuilder - let builders:Builder[] = [this]; + let builders: Builder[] = [this]; if (obj instanceof MultiBuilder) { for (let i = 0; i < (obj).length; i++) { builders.push((obj).item(i)); @@ -680,7 +680,7 @@ export class Builder implements IDisposable { public preventDefault(type: string, cancelBubble: boolean, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder; public preventDefault(typesArray: string[], cancelBubble: boolean, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder; public preventDefault(arg1: any, cancelBubble: boolean, listenerToUnbindContainer?: IDisposable[], useCapture?: boolean): Builder { - let fn = function(e: Event) { + let fn = function (e: Event) { e.preventDefault(); if (cancelBubble) { @@ -1891,7 +1891,7 @@ export class MultiBuilder extends Builder { // Mixin Builder functions to operate on all builders let $outer = this; let propertyFn = (prop: string) => { - ($outer)[prop] = function(): any { + ($outer)[prop] = function (): any { let args = Array.prototype.slice.call(arguments); let returnValues: any[]; @@ -2102,7 +2102,7 @@ export let Binding = { let SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((.([\w\-]+))*)/; -export let $: QuickBuilder = function(arg?: any): Builder { +export let $: QuickBuilder = function (arg?: any): Builder { // Off-DOM use if (types.isUndefined(arg)) { diff --git a/src/vs/base/browser/dnd.ts b/src/vs/base/browser/dnd.ts index 7f8365773a5e3..a0d3778527a97 100644 --- a/src/vs/base/browser/dnd.ts +++ b/src/vs/base/browser/dnd.ts @@ -5,7 +5,7 @@ 'use strict'; -import {$} from 'vs/base/browser/builder'; +import { $ } from 'vs/base/browser/builder'; import URI from 'vs/base/common/uri'; /** diff --git a/src/vs/base/browser/dom.ts b/src/vs/base/browser/dom.ts index 39645aeccee3e..d680de1f0012d 100644 --- a/src/vs/base/browser/dom.ts +++ b/src/vs/base/browser/dom.ts @@ -4,16 +4,16 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {TPromise} from 'vs/base/common/winjs.base'; -import {TimeoutTimer} from 'vs/base/common/async'; -import {onUnexpectedError} from 'vs/base/common/errors'; -import {EventEmitter} from 'vs/base/common/eventEmitter'; -import {Disposable, IDisposable} from 'vs/base/common/lifecycle'; -import {isObject} from 'vs/base/common/types'; -import {isChrome, isWebKit} from 'vs/base/browser/browser'; -import {IKeyboardEvent, StandardKeyboardEvent} from 'vs/base/browser/keyboardEvent'; -import {IMouseEvent, StandardMouseEvent} from 'vs/base/browser/mouseEvent'; -import {CharCode} from 'vs/base/common/charCode'; +import { TPromise } from 'vs/base/common/winjs.base'; +import { TimeoutTimer } from 'vs/base/common/async'; +import { onUnexpectedError } from 'vs/base/common/errors'; +import { EventEmitter } from 'vs/base/common/eventEmitter'; +import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; +import { isObject } from 'vs/base/common/types'; +import { isChrome, isWebKit } from 'vs/base/browser/browser'; +import { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; +import { IMouseEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent'; +import { CharCode } from 'vs/base/common/charCode'; export function clearNode(node: HTMLElement) { while (node.firstChild) { diff --git a/src/vs/base/browser/event.ts b/src/vs/base/browser/event.ts index a0c69a3ca2531..3cec88098ba9c 100644 --- a/src/vs/base/browser/event.ts +++ b/src/vs/base/browser/event.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import _Event, { Emitter, mapEvent } from 'vs/base/common/event'; +import _Event, { Emitter, mapEvent } from 'vs/base/common/event'; export type EventHandler = HTMLElement | HTMLDocument | Window; diff --git a/src/vs/base/browser/globalMouseMoveMonitor.ts b/src/vs/base/browser/globalMouseMoveMonitor.ts index 7b14ee90183ff..3e2e2fc289eaa 100644 --- a/src/vs/base/browser/globalMouseMoveMonitor.ts +++ b/src/vs/base/browser/globalMouseMoveMonitor.ts @@ -4,30 +4,30 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {Disposable, IDisposable, dispose} from 'vs/base/common/lifecycle'; +import { Disposable, IDisposable, dispose } from 'vs/base/common/lifecycle'; import * as dom from 'vs/base/browser/dom'; -import {IframeUtils} from 'vs/base/browser/iframe'; -import {StandardMouseEvent} from 'vs/base/browser/mouseEvent'; +import { IframeUtils } from 'vs/base/browser/iframe'; +import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; export interface IStandardMouseMoveEventData { - leftButton:boolean; - posx:number; - posy:number; + leftButton: boolean; + posx: number; + posy: number; } export interface IEventMerger { - (lastEvent:R, currentEvent:MouseEvent):R; + (lastEvent: R, currentEvent: MouseEvent): R; } export interface IMouseMoveCallback { - (mouseMoveData:R):void; + (mouseMoveData: R): void; } export interface IOnStopCallback { - ():void; + (): void; } -export function standardMouseMoveMerger(lastEvent:IStandardMouseMoveEventData, currentEvent:MouseEvent):IStandardMouseMoveEventData { +export function standardMouseMoveMerger(lastEvent: IStandardMouseMoveEventData, currentEvent: MouseEvent): IStandardMouseMoveEventData { let ev = new StandardMouseEvent(currentEvent); ev.preventDefault(); return { @@ -39,10 +39,10 @@ export function standardMouseMoveMerger(lastEvent:IStandardMouseMoveEventData, c export class GlobalMouseMoveMonitor extends Disposable { - private hooks:IDisposable[]; - private mouseMoveEventMerger:IEventMerger; - private mouseMoveCallback:IMouseMoveCallback; - private onStopCallback:IOnStopCallback; + private hooks: IDisposable[]; + private mouseMoveEventMerger: IEventMerger; + private mouseMoveCallback: IMouseMoveCallback; + private onStopCallback: IOnStopCallback; constructor() { super(); @@ -57,7 +57,7 @@ export class GlobalMouseMoveMonitor extends Disposable { super.dispose(); } - public stopMonitoring(invokeStopCallback:boolean): void { + public stopMonitoring(invokeStopCallback: boolean): void { if (!this.isMonitoring()) { // Not monitoring return; @@ -80,10 +80,10 @@ export class GlobalMouseMoveMonitor extends Disposable { } public startMonitoring( - mouseMoveEventMerger:IEventMerger, - mouseMoveCallback:IMouseMoveCallback, - onStopCallback:IOnStopCallback - ): void { + mouseMoveEventMerger: IEventMerger, + mouseMoveCallback: IMouseMoveCallback, + onStopCallback: IOnStopCallback + ): void { if (this.isMonitoring()) { // I am already hooked return; @@ -95,31 +95,31 @@ export class GlobalMouseMoveMonitor extends Disposable { let windowChain = IframeUtils.getSameOriginWindowChain(); for (let i = 0; i < windowChain.length; i++) { this.hooks.push(dom.addDisposableThrottledListener(windowChain[i].window.document, 'mousemove', - (data:R) => this.mouseMoveCallback(data), - (lastEvent:R, currentEvent:MouseEvent) => this.mouseMoveEventMerger(lastEvent, currentEvent) + (data: R) => this.mouseMoveCallback(data), + (lastEvent: R, currentEvent: MouseEvent) => this.mouseMoveEventMerger(lastEvent, currentEvent) )); - this.hooks.push(dom.addDisposableListener(windowChain[i].window.document, 'mouseup', (e:MouseEvent) => this.stopMonitoring(true))); + this.hooks.push(dom.addDisposableListener(windowChain[i].window.document, 'mouseup', (e: MouseEvent) => this.stopMonitoring(true))); } if (IframeUtils.hasDifferentOriginAncestor()) { let lastSameOriginAncestor = windowChain[windowChain.length - 1]; // We might miss a mouse up if it happens outside the iframe // This one is for Chrome - this.hooks.push(dom.addDisposableListener(lastSameOriginAncestor.window.document, 'mouseout', (browserEvent:MouseEvent) => { + this.hooks.push(dom.addDisposableListener(lastSameOriginAncestor.window.document, 'mouseout', (browserEvent: MouseEvent) => { let e = new StandardMouseEvent(browserEvent); if (e.target.tagName.toLowerCase() === 'html') { this.stopMonitoring(true); } })); // This one is for FF - this.hooks.push(dom.addDisposableListener(lastSameOriginAncestor.window.document, 'mouseover', (browserEvent:MouseEvent) => { + this.hooks.push(dom.addDisposableListener(lastSameOriginAncestor.window.document, 'mouseover', (browserEvent: MouseEvent) => { let e = new StandardMouseEvent(browserEvent); if (e.target.tagName.toLowerCase() === 'html') { this.stopMonitoring(true); } })); // This one is for IE - this.hooks.push(dom.addDisposableListener(lastSameOriginAncestor.window.document.body, 'mouseleave', (browserEvent:MouseEvent) => { + this.hooks.push(dom.addDisposableListener(lastSameOriginAncestor.window.document.body, 'mouseleave', (browserEvent: MouseEvent) => { this.stopMonitoring(true); })); } diff --git a/src/vs/base/browser/htmlContentRenderer.ts b/src/vs/base/browser/htmlContentRenderer.ts index 3429e7c13435d..c01045fe8ae86 100644 --- a/src/vs/base/browser/htmlContentRenderer.ts +++ b/src/vs/base/browser/htmlContentRenderer.ts @@ -6,12 +6,12 @@ 'use strict'; import DOM = require('vs/base/browser/dom'); -import {defaultGenerator} from 'vs/base/common/idGenerator'; -import {escape} from 'vs/base/common/strings'; -import {TPromise} from 'vs/base/common/winjs.base'; -import {IHTMLContentElement, MarkedString} from 'vs/base/common/htmlContent'; -import {marked} from 'vs/base/common/marked/marked'; -import {IMouseEvent} from 'vs/base/browser/mouseEvent'; +import { defaultGenerator } from 'vs/base/common/idGenerator'; +import { escape } from 'vs/base/common/strings'; +import { TPromise } from 'vs/base/common/winjs.base'; +import { IHTMLContentElement, MarkedString } from 'vs/base/common/htmlContent'; +import { marked } from 'vs/base/common/marked/marked'; +import { IMouseEvent } from 'vs/base/browser/mouseEvent'; export type RenderableContent = string | IHTMLContentElement | IHTMLContentElement[]; diff --git a/src/vs/base/browser/keyboardEvent.ts b/src/vs/base/browser/keyboardEvent.ts index c4dad411e5c23..88a8b336552bd 100644 --- a/src/vs/base/browser/keyboardEvent.ts +++ b/src/vs/base/browser/keyboardEvent.ts @@ -5,12 +5,12 @@ 'use strict'; -import {KeyCode, KeyCodeUtils, KeyMod} from 'vs/base/common/keyCodes'; +import { KeyCode, KeyCodeUtils, KeyMod } from 'vs/base/common/keyCodes'; import * as platform from 'vs/base/common/platform'; import * as browser from 'vs/base/browser/browser'; -let KEY_CODE_MAP: {[keyCode:number]:KeyCode} = {}; -(function() { +let KEY_CODE_MAP: { [keyCode: number]: KeyCode } = {}; +(function () { KEY_CODE_MAP[3] = KeyCode.PauseBreak; // VK_CANCEL 0x03 Control-break processing KEY_CODE_MAP[8] = KeyCode.Backspace; KEY_CODE_MAP[9] = KeyCode.Tab; @@ -148,11 +148,11 @@ let KEY_CODE_MAP: {[keyCode:number]:KeyCode} = {}; } })(); -export function lookupKeyCode(e:KeyboardEvent): KeyCode { +export function lookupKeyCode(e: KeyboardEvent): KeyCode { return KEY_CODE_MAP[e.keyCode] || KeyCode.Unknown; } -let extractKeyCode = function extractKeyCode(e:KeyboardEvent): KeyCode { +let extractKeyCode = function extractKeyCode(e: KeyboardEvent): KeyCode { if (e.charCode) { // "keypress" events mostly let char = String.fromCharCode(e.charCode).toUpperCase(); @@ -161,13 +161,13 @@ let extractKeyCode = function extractKeyCode(e:KeyboardEvent): KeyCode { return lookupKeyCode(e); }; -export function setExtractKeyCode(newExtractKeyCode:(e:KeyboardEvent)=>KeyCode): void { +export function setExtractKeyCode(newExtractKeyCode: (e: KeyboardEvent) => KeyCode): void { extractKeyCode = newExtractKeyCode; } export interface IKeyboardEvent { - browserEvent:KeyboardEvent; - target:HTMLElement; + browserEvent: KeyboardEvent; + target: HTMLElement; ctrlKey: boolean; shiftKey: boolean; @@ -176,7 +176,7 @@ export interface IKeyboardEvent { keyCode: KeyCode; asKeybinding(): number; - equals(keybinding:number): boolean; + equals(keybinding: number): boolean; preventDefault(): void; stopPropagation(): void; @@ -200,7 +200,7 @@ export class StandardKeyboardEvent implements IKeyboardEvent { private _asKeybinding: number; - constructor(source:KeyboardEvent) { + constructor(source: KeyboardEvent) { let e = source; this.browserEvent = e; @@ -238,7 +238,7 @@ export class StandardKeyboardEvent implements IKeyboardEvent { return this._asKeybinding; } - public equals(other:number): boolean { + public equals(other: number): boolean { return (this._asKeybinding === other); } diff --git a/src/vs/base/browser/mouseEvent.ts b/src/vs/base/browser/mouseEvent.ts index 867e36d2e21aa..12c5a02b348af 100644 --- a/src/vs/base/browser/mouseEvent.ts +++ b/src/vs/base/browser/mouseEvent.ts @@ -6,22 +6,22 @@ import * as platform from 'vs/base/common/platform'; import * as browser from 'vs/base/browser/browser'; -import {IframeUtils} from 'vs/base/browser/iframe'; +import { IframeUtils } from 'vs/base/browser/iframe'; export interface IMouseEvent { - browserEvent:MouseEvent; - leftButton:boolean; - middleButton:boolean; - rightButton:boolean; - target:HTMLElement; - detail:number; - posx:number; - posy:number; - ctrlKey:boolean; - shiftKey:boolean; - altKey:boolean; - metaKey:boolean; - timestamp:number; + browserEvent: MouseEvent; + leftButton: boolean; + middleButton: boolean; + rightButton: boolean; + target: HTMLElement; + detail: number; + posx: number; + posy: number; + ctrlKey: boolean; + shiftKey: boolean; + altKey: boolean; + metaKey: boolean; + timestamp: number; preventDefault(): void; stopPropagation(): void; @@ -29,22 +29,22 @@ export interface IMouseEvent { export class StandardMouseEvent implements IMouseEvent { - public browserEvent:MouseEvent; - - public leftButton:boolean; - public middleButton:boolean; - public rightButton:boolean; - public target:HTMLElement; - public detail:number; - public posx:number; - public posy:number; - public ctrlKey:boolean; - public shiftKey:boolean; - public altKey:boolean; - public metaKey:boolean; - public timestamp:number; - - constructor(e:MouseEvent) { + public browserEvent: MouseEvent; + + public leftButton: boolean; + public middleButton: boolean; + public rightButton: boolean; + public target: HTMLElement; + public detail: number; + public posx: number; + public posy: number; + public ctrlKey: boolean; + public shiftKey: boolean; + public altKey: boolean; + public metaKey: boolean; + public timestamp: number; + + constructor(e: MouseEvent) { this.timestamp = Date.now(); this.browserEvent = e; this.leftButton = e.button === 0; @@ -91,23 +91,23 @@ export class StandardMouseEvent implements IMouseEvent { } export interface IDataTransfer { - dropEffect:string; - effectAllowed:string; - types:any[]; - files:any[]; + dropEffect: string; + effectAllowed: string; + types: any[]; + files: any[]; - setData(type:string, data:string):void; - setDragImage(image:any, x:number, y:number):void; + setData(type: string, data: string): void; + setDragImage(image: any, x: number, y: number): void; - getData(type:string):string; - clearData(types?:string[]):void; + getData(type: string): string; + clearData(types?: string[]): void; } export class DragMouseEvent extends StandardMouseEvent { - public dataTransfer:IDataTransfer; + public dataTransfer: IDataTransfer; - constructor(e:MouseEvent) { + constructor(e: MouseEvent) { super(e); this.dataTransfer = (e).dataTransfer; } @@ -116,32 +116,32 @@ export class DragMouseEvent extends StandardMouseEvent { export class DropMouseEvent extends DragMouseEvent { - constructor(e:MouseEvent) { + constructor(e: MouseEvent) { super(e); } } interface IWebKitMouseWheelEvent { - wheelDeltaY:number; - wheelDeltaX:number; + wheelDeltaY: number; + wheelDeltaX: number; } interface IGeckoMouseWheelEvent { - HORIZONTAL_AXIS:number; - VERTICAL_AXIS:number; - axis:number; - detail:number; + HORIZONTAL_AXIS: number; + VERTICAL_AXIS: number; + axis: number; + detail: number; } export class StandardMouseWheelEvent { - public browserEvent:MouseWheelEvent; - public deltaY:number; - public deltaX:number; - public target:Node; + public browserEvent: MouseWheelEvent; + public deltaY: number; + public deltaX: number; + public target: Node; - constructor(e:MouseWheelEvent, deltaX:number = 0, deltaY:number = 0) { + constructor(e: MouseWheelEvent, deltaX: number = 0, deltaY: number = 0) { this.browserEvent = e || null; this.target = e ? (e.target || (e).targetNode || e.srcElement) : null; diff --git a/src/vs/base/browser/styleMutator.ts b/src/vs/base/browser/styleMutator.ts index 647d13fe6b71b..333819d46dfc2 100644 --- a/src/vs/base/browser/styleMutator.ts +++ b/src/vs/base/browser/styleMutator.ts @@ -177,7 +177,7 @@ export abstract class FastDomNode { this._domNode.style.visibility = this._visibility; } - public setTransform(transform:string): void { + public setTransform(transform: string): void { if (this._transform === transform) { return; } @@ -185,9 +185,9 @@ export abstract class FastDomNode { this._setTransform(this._domNode, this._transform); } - protected abstract _setTransform(domNode:HTMLElement, transform:string): void; + protected abstract _setTransform(domNode: HTMLElement, transform: string): void; - public setLineNumber(lineNumber:string): void { + public setLineNumber(lineNumber: string): void { if (this._lineNumber === lineNumber) { return; } @@ -197,19 +197,19 @@ export abstract class FastDomNode { } class WebKitFastDomNode extends FastDomNode { - protected _setTransform(domNode:HTMLElement, transform:string): void { + protected _setTransform(domNode: HTMLElement, transform: string): void { (domNode.style).webkitTransform = transform; } } class StandardFastDomNode extends FastDomNode { - protected _setTransform(domNode:HTMLElement, transform:string): void { + protected _setTransform(domNode: HTMLElement, transform: string): void { domNode.style.transform = transform; } } let useWebKitFastDomNode = false; -(function() { +(function () { let testDomNode = document.createElement('div'); if (typeof (testDomNode.style).webkitTransform !== 'undefined') { useWebKitFastDomNode = true; @@ -312,7 +312,7 @@ function setTransform(domNode: HTMLElement, desiredValue: string): boolean { } return false; } -(function() { +(function () { let testDomNode = document.createElement('div'); if (typeof (testDomNode.style).webkitTransform !== 'undefined') { StyleMutator.setTransform = setWebkitTransform; diff --git a/src/vs/base/browser/touch.ts b/src/vs/base/browser/touch.ts index a183cd6e37b31..7d79a4c19d01b 100644 --- a/src/vs/base/browser/touch.ts +++ b/src/vs/base/browser/touch.ts @@ -5,7 +5,7 @@ 'use strict'; import arrays = require('vs/base/common/arrays'); -import {IDisposable, dispose} from 'vs/base/common/lifecycle'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import DomUtils = require('vs/base/browser/dom'); export namespace EventType { diff --git a/src/vs/base/browser/ui/actionbar/actionbar.ts b/src/vs/base/browser/ui/actionbar/actionbar.ts index 806341ed3f6c4..83b863c2a4990 100644 --- a/src/vs/base/browser/ui/actionbar/actionbar.ts +++ b/src/vs/base/browser/ui/actionbar/actionbar.ts @@ -8,18 +8,18 @@ import 'vs/css!./actionbar'; import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); -import {Promise} from 'vs/base/common/winjs.base'; -import {Builder, $} from 'vs/base/browser/builder'; -import {SelectBox} from 'vs/base/browser/ui/selectBox/selectBox'; +import { Promise } from 'vs/base/common/winjs.base'; +import { Builder, $ } from 'vs/base/browser/builder'; +import { SelectBox } from 'vs/base/browser/ui/selectBox/selectBox'; import platform = require('vs/base/common/platform'); -import {IAction, IActionRunner, Action, IActionChangeEvent, ActionRunner} from 'vs/base/common/actions'; +import { IAction, IActionRunner, Action, IActionChangeEvent, ActionRunner } from 'vs/base/common/actions'; import DOM = require('vs/base/browser/dom'); -import {EventType as CommonEventType} from 'vs/base/common/events'; +import { EventType as CommonEventType } from 'vs/base/common/events'; import types = require('vs/base/common/types'); -import {IEventEmitter, EventEmitter} from 'vs/base/common/eventEmitter'; -import {Gesture, EventType} from 'vs/base/browser/touch'; -import {StandardKeyboardEvent} from 'vs/base/browser/keyboardEvent'; -import {KeyCode, KeyMod} from 'vs/base/common/keyCodes'; +import { IEventEmitter, EventEmitter } from 'vs/base/common/eventEmitter'; +import { Gesture, EventType } from 'vs/base/browser/touch'; +import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; +import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; export interface IActionItem extends IEventEmitter { actionRunner: IActionRunner; diff --git a/src/vs/base/browser/ui/aria/aria.ts b/src/vs/base/browser/ui/aria/aria.ts index 8ba74e0498277..dd5776ab9f894 100644 --- a/src/vs/base/browser/ui/aria/aria.ts +++ b/src/vs/base/browser/ui/aria/aria.ts @@ -7,8 +7,8 @@ import 'vs/css!./aria'; import nls = require('vs/nls'); -import {isMacintosh} from 'vs/base/common/platform'; -import {Builder, $} from 'vs/base/browser/builder'; +import { isMacintosh } from 'vs/base/common/platform'; +import { Builder, $ } from 'vs/base/browser/builder'; let ariaContainer: Builder; let alertContainer: Builder; diff --git a/src/vs/base/browser/ui/button/button.ts b/src/vs/base/browser/ui/button/button.ts index b4838947b27a4..cec07d6a46ef8 100644 --- a/src/vs/base/browser/ui/button/button.ts +++ b/src/vs/base/browser/ui/button/button.ts @@ -6,11 +6,11 @@ 'use strict'; import 'vs/css!./button'; -import {EventEmitter} from 'vs/base/common/eventEmitter'; +import { EventEmitter } from 'vs/base/common/eventEmitter'; import DOM = require('vs/base/browser/dom'); -import {Builder, $} from 'vs/base/browser/builder'; -import {StandardKeyboardEvent} from 'vs/base/browser/keyboardEvent'; -import {KeyCode} from 'vs/base/common/keyCodes'; +import { Builder, $ } from 'vs/base/browser/builder'; +import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; +import { KeyCode } from 'vs/base/common/keyCodes'; export class Button extends EventEmitter { diff --git a/src/vs/base/browser/ui/checkbox/checkbox.ts b/src/vs/base/browser/ui/checkbox/checkbox.ts index 10845dc9a0122..c497a4d7b640e 100644 --- a/src/vs/base/browser/ui/checkbox/checkbox.ts +++ b/src/vs/base/browser/ui/checkbox/checkbox.ts @@ -8,9 +8,9 @@ import 'vs/css!./checkbox'; import DOM = require('vs/base/browser/dom'); -import {KeyCode} from 'vs/base/common/keyCodes'; -import {Widget} from 'vs/base/browser/ui/widget'; -import {IKeyboardEvent} from 'vs/base/browser/keyboardEvent'; +import { KeyCode } from 'vs/base/common/keyCodes'; +import { Widget } from 'vs/base/browser/ui/widget'; +import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; export interface ICheckboxOpts { actionClassName: string; diff --git a/src/vs/base/browser/ui/contextview/contextview.ts b/src/vs/base/browser/ui/contextview/contextview.ts index ac90de2ed18ef..dfb187b2ae57d 100644 --- a/src/vs/base/browser/ui/contextview/contextview.ts +++ b/src/vs/base/browser/ui/contextview/contextview.ts @@ -7,10 +7,10 @@ 'use strict'; import 'vs/css!./contextview'; -import {Builder, $} from 'vs/base/browser/builder'; +import { Builder, $ } from 'vs/base/browser/builder'; import DOM = require('vs/base/browser/dom'); -import {IDisposable, dispose} from 'vs/base/common/lifecycle'; -import {EventEmitter} from 'vs/base/common/eventEmitter'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { EventEmitter } from 'vs/base/common/eventEmitter'; export interface IAnchor { x: number; @@ -58,7 +58,7 @@ export interface IView extends IPosition, ISize { } function layout(view: ISize, around: IView, viewport: IView, anchorPosition: AnchorPosition, anchorAlignment: AnchorAlignment): IPosition { - let chooseBiased = (a:number, aIsGood:boolean, b:number, bIsGood:boolean) => { + let chooseBiased = (a: number, aIsGood: boolean, b: number, bIsGood: boolean) => { if (aIsGood) { return a; } @@ -68,7 +68,7 @@ function layout(view: ISize, around: IView, viewport: IView, anchorPosition: Anc return a; }; - let chooseOne = (a:number, aIsGood:boolean, b:number, bIsGood:boolean, aIsPreferred:boolean) => { + let chooseOne = (a: number, aIsGood: boolean, b: number, bIsGood: boolean, aIsPreferred: boolean) => { if (aIsPreferred) { return chooseBiased(a, aIsGood, b, bIsGood); } else { diff --git a/src/vs/base/browser/ui/countBadge/countBadge.ts b/src/vs/base/browser/ui/countBadge/countBadge.ts index 6090d3dd1fcda..1f6825c5a90b3 100644 --- a/src/vs/base/browser/ui/countBadge/countBadge.ts +++ b/src/vs/base/browser/ui/countBadge/countBadge.ts @@ -6,7 +6,7 @@ 'use strict'; import 'vs/css!./countBadge'; -import {Builder, $} from 'vs/base/browser/builder'; +import { Builder, $ } from 'vs/base/browser/builder'; import strings = require('vs/base/common/strings'); export class CountBadge { diff --git a/src/vs/base/browser/ui/dropdown/dropdown.ts b/src/vs/base/browser/ui/dropdown/dropdown.ts index 622304d5677c2..1178d9dfa8ef7 100644 --- a/src/vs/base/browser/ui/dropdown/dropdown.ts +++ b/src/vs/base/browser/ui/dropdown/dropdown.ts @@ -6,16 +6,16 @@ 'use strict'; import 'vs/css!./dropdown'; -import {Builder, $} from 'vs/base/browser/builder'; -import {TPromise} from 'vs/base/common/winjs.base'; -import {Gesture, EventType} from 'vs/base/browser/touch'; -import {ActionRunner, IAction} from 'vs/base/common/actions'; -import {ActionItem, IActionItem} from 'vs/base/browser/ui/actionbar/actionbar'; -import {EventEmitter} from 'vs/base/common/eventEmitter'; -import {IDisposable, dispose} from 'vs/base/common/lifecycle'; -import {IContextViewProvider} from 'vs/base/browser/ui/contextview/contextview'; -import {IMenuOptions} from 'vs/base/browser/ui/menu/menu'; -import {Keybinding} from 'vs/base/common/keybinding'; +import { Builder, $ } from 'vs/base/browser/builder'; +import { TPromise } from 'vs/base/common/winjs.base'; +import { Gesture, EventType } from 'vs/base/browser/touch'; +import { ActionRunner, IAction } from 'vs/base/common/actions'; +import { ActionItem, IActionItem } from 'vs/base/browser/ui/actionbar/actionbar'; +import { EventEmitter } from 'vs/base/common/eventEmitter'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview'; +import { IMenuOptions } from 'vs/base/browser/ui/menu/menu'; +import { Keybinding } from 'vs/base/common/keybinding'; export interface ILabelRenderer { (container: HTMLElement): IDisposable; @@ -262,7 +262,7 @@ export class DropdownMenu extends BaseDropdown { getActions: () => TPromise.as(this.actions), getActionsContext: () => this.menuOptions ? this.menuOptions.context : null, getActionItem: (action) => this.menuOptions && this.menuOptions.actionItemProvider ? this.menuOptions.actionItemProvider(action) : null, - getKeyBinding: (action: IAction) => this.menuOptions && this.menuOptions.getKeyBinding ? this.menuOptions.getKeyBinding(action): null, + getKeyBinding: (action: IAction) => this.menuOptions && this.menuOptions.getKeyBinding ? this.menuOptions.getKeyBinding(action) : null, getMenuClassName: () => this.menuClassName, onHide: () => this.$el.removeClass('active') }); diff --git a/src/vs/base/browser/ui/dropdown/linksDropdown.ts b/src/vs/base/browser/ui/dropdown/linksDropdown.ts index 636c01ac4f601..3b447ec5665da 100644 --- a/src/vs/base/browser/ui/dropdown/linksDropdown.ts +++ b/src/vs/base/browser/ui/dropdown/linksDropdown.ts @@ -4,11 +4,11 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {TPromise} from 'vs/base/common/winjs.base'; -import {isMacintosh} from 'vs/base/common/platform'; -import {isFunction} from 'vs/base/common/types'; -import {Action} from 'vs/base/common/actions'; -import {DropdownMenu, IDropdownMenuOptions} from 'vs/base/browser/ui/dropdown/dropdown'; +import { TPromise } from 'vs/base/common/winjs.base'; +import { isMacintosh } from 'vs/base/common/platform'; +import { isFunction } from 'vs/base/common/types'; +import { Action } from 'vs/base/common/actions'; +import { DropdownMenu, IDropdownMenuOptions } from 'vs/base/browser/ui/dropdown/dropdown'; export interface ILinksDropdownMenuOptions extends IDropdownMenuOptions { tooltip: string; diff --git a/src/vs/base/browser/ui/findinput/findInput.ts b/src/vs/base/browser/ui/findinput/findInput.ts index eccf8eb86df0c..b68beac036610 100644 --- a/src/vs/base/browser/ui/findinput/findInput.ts +++ b/src/vs/base/browser/ui/findinput/findInput.ts @@ -8,19 +8,19 @@ import 'vs/css!./findInput'; import * as nls from 'vs/nls'; import * as dom from 'vs/base/browser/dom'; -import {IMessage as InputBoxMessage, IInputValidator, InputBox} from 'vs/base/browser/ui/inputbox/inputBox'; -import {Checkbox} from 'vs/base/browser/ui/checkbox/checkbox'; -import {IContextViewProvider} from 'vs/base/browser/ui/contextview/contextview'; -import {Widget} from 'vs/base/browser/ui/widget'; -import Event, {Emitter} from 'vs/base/common/event'; -import {IKeyboardEvent} from 'vs/base/browser/keyboardEvent'; -import {KeyCode} from 'vs/base/common/keyCodes'; +import { IMessage as InputBoxMessage, IInputValidator, InputBox } from 'vs/base/browser/ui/inputbox/inputBox'; +import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox'; +import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview'; +import { Widget } from 'vs/base/browser/ui/widget'; +import Event, { Emitter } from 'vs/base/common/event'; +import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; +import { KeyCode } from 'vs/base/common/keyCodes'; export interface IFindInputOptions { - placeholder?:string; - width?:number; - validation?:IInputValidator; - label:string; + placeholder?: string; + width?: number; + validation?: IInputValidator; + label: string; appendCaseSensitiveLabel?: string; appendWholeWordsLabel?: string; @@ -34,19 +34,19 @@ const NLS_DEFAULT_LABEL = nls.localize('defaultLabel', "input"); export class FindInput extends Widget { - static OPTION_CHANGE:string = 'optionChange'; + static OPTION_CHANGE: string = 'optionChange'; private contextViewProvider: IContextViewProvider; - private width:number; - private placeholder:string; - private validation:IInputValidator; - private label:string; - - private regex:Checkbox; - private wholeWords:Checkbox; - private caseSensitive:Checkbox; + private width: number; + private placeholder: string; + private validation: IInputValidator; + private label: string; + + private regex: Checkbox; + private wholeWords: Checkbox; + private caseSensitive: Checkbox; public domNode: HTMLElement; - public inputBox:InputBox; + public inputBox: InputBox; private _onDidOptionChange = this._register(new Emitter()); public onDidOptionChange: Event = this._onDidOptionChange.event; @@ -63,7 +63,7 @@ export class FindInput extends Widget { private _onCaseSensitiveKeyDown = this._register(new Emitter()); public onCaseSensitiveKeyDown: Event = this._onCaseSensitiveKeyDown.event; - constructor(parent:HTMLElement, contextViewProvider: IContextViewProvider, options?:IFindInputOptions) { + constructor(parent: HTMLElement, contextViewProvider: IContextViewProvider, options?: IFindInputOptions) { super(); this.contextViewProvider = contextViewProvider; this.width = options.width || 100; @@ -79,7 +79,7 @@ export class FindInput extends Widget { this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || ''); - if(Boolean(parent)) { + if (Boolean(parent)) { parent.appendChild(this.domNode); } @@ -104,7 +104,7 @@ export class FindInput extends Widget { this.caseSensitive.disable(); } - public setEnabled(enabled:boolean): void { + public setEnabled(enabled: boolean): void { if (enabled) { this.enable(); } else { @@ -118,7 +118,7 @@ export class FindInput extends Widget { this.focus(); } - public setWidth(newWidth:number): void { + public setWidth(newWidth: number): void { this.width = newWidth; this.domNode.style.width = this.width + 'px'; this.contextViewProvider.layout(); @@ -129,7 +129,7 @@ export class FindInput extends Widget { return this.inputBox.value; } - public setValue(value:string): void { + public setValue(value: string): void { if (this.inputBox.value !== value) { this.inputBox.value = value; } @@ -143,29 +143,29 @@ export class FindInput extends Widget { this.inputBox.focus(); } - public getCaseSensitive():boolean { + public getCaseSensitive(): boolean { return this.caseSensitive.checked; } - public setCaseSensitive(value:boolean): void { + public setCaseSensitive(value: boolean): void { this.caseSensitive.checked = value; this.setInputWidth(); } - public getWholeWords():boolean { + public getWholeWords(): boolean { return this.wholeWords.checked; } - public setWholeWords(value:boolean): void { + public setWholeWords(value: boolean): void { this.wholeWords.checked = value; this.setInputWidth(); } - public getRegex():boolean { + public getRegex(): boolean { return this.regex.checked; } - public setRegex(value:boolean): void { + public setRegex(value: boolean): void { this.regex.checked = value; this.setInputWidth(); } @@ -179,7 +179,7 @@ export class FindInput extends Widget { this.inputBox.width = w; } - private buildDomNode(appendCaseSensitiveLabel:string, appendWholeWordsLabel: string, appendRegexLabel: string): void { + private buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string): void { this.domNode = document.createElement('div'); this.domNode.style.width = this.width + 'px'; dom.addClass(this.domNode, 'monaco-findInput'); diff --git a/src/vs/base/browser/ui/highlightedlabel/highlightedLabel.ts b/src/vs/base/browser/ui/highlightedlabel/highlightedLabel.ts index 7c75f496b31cb..9f622f16fdb27 100644 --- a/src/vs/base/browser/ui/highlightedlabel/highlightedLabel.ts +++ b/src/vs/base/browser/ui/highlightedlabel/highlightedLabel.ts @@ -4,11 +4,11 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {escape} from 'vs/base/common/strings'; -import {IDisposable} from 'vs/base/common/lifecycle'; +import { escape } from 'vs/base/common/strings'; +import { IDisposable } from 'vs/base/common/lifecycle'; import * as dom from 'vs/base/browser/dom'; import * as objects from 'vs/base/common/objects'; -import {expand as expandOcticons} from 'vs/base/browser/ui/octiconLabel/octiconLabel'; +import { expand as expandOcticons } from 'vs/base/browser/ui/octiconLabel/octiconLabel'; export interface IHighlight { start: number; diff --git a/src/vs/base/browser/ui/iconLabel/iconLabel.ts b/src/vs/base/browser/ui/iconLabel/iconLabel.ts index 817872b8195ae..014e8239fcddd 100644 --- a/src/vs/base/browser/ui/iconLabel/iconLabel.ts +++ b/src/vs/base/browser/ui/iconLabel/iconLabel.ts @@ -7,12 +7,12 @@ import 'vs/css!./iconlabel'; import dom = require('vs/base/browser/dom'); -import {HighlightedLabel} from 'vs/base/browser/ui/highlightedlabel/highlightedLabel'; -import {IMatch} from 'vs/base/common/filters'; +import { HighlightedLabel } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel'; +import { IMatch } from 'vs/base/common/filters'; import uri from 'vs/base/common/uri'; import paths = require('vs/base/common/paths'); import types = require('vs/base/common/types'); -import {IWorkspaceProvider, getPathLabel} from 'vs/base/common/labels'; +import { IWorkspaceProvider, getPathLabel } from 'vs/base/common/labels'; export interface IIconLabelCreationOptions { supportHighlights?: boolean; diff --git a/src/vs/base/browser/ui/inputbox/inputBox.ts b/src/vs/base/browser/ui/inputbox/inputBox.ts index 1a3dc750fb21c..53fa3398693a2 100644 --- a/src/vs/base/browser/ui/inputbox/inputBox.ts +++ b/src/vs/base/browser/ui/inputbox/inputBox.ts @@ -9,14 +9,14 @@ import 'vs/css!./inputBox'; import nls = require('vs/nls'); import * as Bal from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; -import {IHTMLContentElement} from 'vs/base/common/htmlContent'; -import {renderHtml} from 'vs/base/browser/htmlContentRenderer'; +import { IHTMLContentElement } from 'vs/base/common/htmlContent'; +import { renderHtml } from 'vs/base/browser/htmlContentRenderer'; import aria = require('vs/base/browser/ui/aria/aria'); -import {IAction} from 'vs/base/common/actions'; -import {ActionBar} from 'vs/base/browser/ui/actionbar/actionbar'; -import {IContextViewProvider, AnchorAlignment} from 'vs/base/browser/ui/contextview/contextview'; -import Event, {Emitter} from 'vs/base/common/event'; -import {Widget} from 'vs/base/browser/ui/widget'; +import { IAction } from 'vs/base/common/actions'; +import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; +import { IContextViewProvider, AnchorAlignment } from 'vs/base/browser/ui/contextview/contextview'; +import Event, { Emitter } from 'vs/base/common/event'; +import { Widget } from 'vs/base/browser/ui/widget'; const $ = dom.$; diff --git a/src/vs/base/browser/ui/leftRightWidget/leftRightWidget.ts b/src/vs/base/browser/ui/leftRightWidget/leftRightWidget.ts index e35a7c76fce4e..85e960a9ce34c 100644 --- a/src/vs/base/browser/ui/leftRightWidget/leftRightWidget.ts +++ b/src/vs/base/browser/ui/leftRightWidget/leftRightWidget.ts @@ -6,8 +6,8 @@ 'use strict'; import 'vs/css!./leftRightWidget'; -import {Builder, $} from 'vs/base/browser/builder'; -import {IDisposable} from 'vs/base/common/lifecycle'; +import { Builder, $ } from 'vs/base/browser/builder'; +import { IDisposable } from 'vs/base/common/lifecycle'; export interface IRenderer { (container: HTMLElement): IDisposable; diff --git a/src/vs/base/browser/ui/list/listPaging.ts b/src/vs/base/browser/ui/list/listPaging.ts index 54a9e2eed5234..c5ceceb4cf42e 100644 --- a/src/vs/base/browser/ui/list/listPaging.ts +++ b/src/vs/base/browser/ui/list/listPaging.ts @@ -27,11 +27,11 @@ class PagedRenderer implements IRenderer, private modelProvider: () => IPagedModel - ) {} + ) { } renderTemplate(container: HTMLElement): ITemplateData { const data = this.renderer.renderTemplate(container); - return { data, disposable: { dispose: () => {} } }; + return { data, disposable: { dispose: () => { } } }; } renderElement(index: number, _: number, data: ITemplateData): void { diff --git a/src/vs/base/browser/ui/list/listView.ts b/src/vs/base/browser/ui/list/listView.ts index 59f6123e5b0d6..b43836046aa94 100644 --- a/src/vs/base/browser/ui/list/listView.ts +++ b/src/vs/base/browser/ui/list/listView.ts @@ -123,7 +123,7 @@ export class ListView implements IDisposable { each(renderRange, i => this.insertItemInDOM(this.items[i], i)); const scrollHeight = this.getContentHeight(); - this.rowsContainer.style.height = `${ scrollHeight }px`; + this.rowsContainer.style.height = `${scrollHeight}px`; this.scrollableElement.updateState({ scrollHeight }); return deleted.map(i => i.element); @@ -175,7 +175,7 @@ export class ListView implements IDisposable { rangesToInsert.forEach(range => each(range, i => this.insertItemInDOM(this.items[i], i))); rangesToRemove.forEach(range => each(range, i => this.removeItemFromDOM(this.items[i]))); - this.rowsContainer.style.transform = `translate3d(0px, -${ renderTop }px, 0px)`; + this.rowsContainer.style.transform = `translate3d(0px, -${renderTop}px, 0px)`; this.lastRenderTop = renderTop; this.lastRenderHeight = renderHeight; } @@ -192,8 +192,8 @@ export class ListView implements IDisposable { } const renderer = this.renderers[item.templateId]; - item.row.domNode.style.top = `${ this.elementTop(index) }px`; - item.row.domNode.style.height = `${ item.size }px`; + item.row.domNode.style.top = `${this.elementTop(index)}px`; + item.row.domNode.style.height = `${item.size}px`; item.row.domNode.setAttribute('data-index', `${index}`); renderer.renderElement(item.element, index, item.row.templateData); } @@ -225,7 +225,7 @@ export class ListView implements IDisposable { // Events - addListener(type: string, handler: (event:any)=>void, useCapture?: boolean): IDisposable { + addListener(type: string, handler: (event: any) => void, useCapture?: boolean): IDisposable { const userHandler = handler; let domNode = this.domNode; @@ -239,7 +239,7 @@ export class ListView implements IDisposable { return DOM.addDisposableListener(domNode, type, handler, useCapture); } - private fireScopedEvent(handler: (event: any)=>void, index) { + private fireScopedEvent(handler: (event: any) => void, index) { if (index < 0) { return; } diff --git a/src/vs/base/browser/ui/list/listWidget.ts b/src/vs/base/browser/ui/list/listWidget.ts index 4e288f8b198c9..36581beb6330a 100644 --- a/src/vs/base/browser/ui/list/listWidget.ts +++ b/src/vs/base/browser/ui/list/listWidget.ts @@ -28,8 +28,8 @@ class TraitRenderer implements IRenderer> { constructor( private controller: Trait, - private renderer: IRenderer - ) {} + private renderer: IRenderer + ) { } public get templateId(): string { return this.renderer.templateId; @@ -79,7 +79,7 @@ class Trait implements IDisposable { this._onChange.fire({ indexes }); } - renderElement(element: T, index: number, container:HTMLElement): void { + renderElement(element: T, index: number, container: HTMLElement): void { DOM.toggleClass(container, this._trait, this.contains(index)); } @@ -110,11 +110,11 @@ class Trait implements IDisposable { class FocusTrait extends Trait { - constructor(private getElementId:(number) => string) { + constructor(private getElementId: (number) => string) { super('focused'); } - renderElement(element: T, index: number, container:HTMLElement): void { + renderElement(element: T, index: number, container: HTMLElement): void { super.renderElement(element, index, container); container.setAttribute('role', 'option'); container.setAttribute('id', this.getElementId(index)); @@ -208,7 +208,7 @@ const DefaultOptions: IListOptions = {}; export class List implements IDisposable { private static InstanceCount = 0; - private idPrefix = `list_id_${ ++List.InstanceCount }`; + private idPrefix = `list_id_${++List.InstanceCount}`; private focus: Trait; private selection: Trait; @@ -352,7 +352,7 @@ export class List implements IDisposable { } focusPreviousPage(): void { - let firstPageIndex:number; + let firstPageIndex: number; const scrollTop = this.view.getScrollTop(); if (scrollTop === 0) { @@ -409,8 +409,8 @@ export class List implements IDisposable { } } - getElementId(index:number): string { - return `${ this.idPrefix }_${ index }`; + getElementId(index: number): string { + return `${this.idPrefix}_${index}`; } private toListEvent({ indexes }: ITraitChangeEvent) { diff --git a/src/vs/base/browser/ui/list/rangeMap.ts b/src/vs/base/browser/ui/list/rangeMap.ts index 5a3ff150bfa27..e100122c8db50 100644 --- a/src/vs/base/browser/ui/list/rangeMap.ts +++ b/src/vs/base/browser/ui/list/rangeMap.ts @@ -56,7 +56,7 @@ export function relativeComplement(one: IRange, other: IRange): IRange[] { return result; } -export function each(range: IRange, fn: (index : number) => void): void { +export function each(range: IRange, fn: (index: number) => void): void { for (let i = range.start; i < range.end; i++) { fn(i); } diff --git a/src/vs/base/browser/ui/list/rowCache.ts b/src/vs/base/browser/ui/list/rowCache.ts index dbf6b1ad934a4..77fd63cc9130c 100644 --- a/src/vs/base/browser/ui/list/rowCache.ts +++ b/src/vs/base/browser/ui/list/rowCache.ts @@ -28,7 +28,7 @@ function removeFromParent(element: HTMLElement): void { export class RowCache implements IDisposable { - private cache: { [templateId:string]: IRow[]; }; + private cache: { [templateId: string]: IRow[]; }; private scrollingRow: IRow; constructor(private renderers: { [templateId: string]: IRenderer; }) { diff --git a/src/vs/base/browser/ui/list/test/rangeMap.test.ts b/src/vs/base/browser/ui/list/test/rangeMap.test.ts index d8bf270ea4b3f..0ad8b350bef51 100644 --- a/src/vs/base/browser/ui/list/test/rangeMap.test.ts +++ b/src/vs/base/browser/ui/list/test/rangeMap.test.ts @@ -198,9 +198,9 @@ suite('RangeMap', () => { test('delete', () => { rangeMap.splice(0, 0, five, five, five, five, five, - five, five, five, five, five, - five, five, five, five, five, - five, five, five, five, five); + five, five, five, five, five, + five, five, five, five, five, + five, five, five, five, five); assert.equal(rangeMap.size, 100); assert.equal(rangeMap.count, 20); @@ -236,7 +236,7 @@ suite('RangeMap', () => { test('insert & delete #2', () => { rangeMap.splice(0, 0, one, one, one, one, one, - one, one, one, one, one); + one, one, one, one, one); rangeMap.splice(2, 6); assert.equal(rangeMap.count, 4); assert.equal(rangeMap.size, 4); @@ -244,9 +244,9 @@ suite('RangeMap', () => { test('insert & delete #3', () => { rangeMap.splice(0, 0, one, one, one, one, one, - one, one, one, one, one, - two, two, two, two, two, - two, two, two, two, two); + one, one, one, one, one, + two, two, two, two, two, + two, two, two, two, two); rangeMap.splice(8, 4); assert.equal(rangeMap.count, 16); assert.equal(rangeMap.size, 24); @@ -254,9 +254,9 @@ suite('RangeMap', () => { test('insert & delete #3', () => { rangeMap.splice(0, 0, one, one, one, one, one, - one, one, one, one, one, - two, two, two, two, two, - two, two, two, two, two); + one, one, one, one, one, + two, two, two, two, two, + two, two, two, two, two); rangeMap.splice(5, 0, three, three, three, three, three); assert.equal(rangeMap.count, 25); assert.equal(rangeMap.size, 45); diff --git a/src/vs/base/browser/ui/menu/menu.ts b/src/vs/base/browser/ui/menu/menu.ts index a975249004444..6c526ac7e6a65 100644 --- a/src/vs/base/browser/ui/menu/menu.ts +++ b/src/vs/base/browser/ui/menu/menu.ts @@ -6,12 +6,12 @@ 'use strict'; import 'vs/css!./menu'; -import {IDisposable} from 'vs/base/common/lifecycle'; -import {$} from 'vs/base/browser/builder'; -import {IActionRunner, IAction} from 'vs/base/common/actions'; -import {ActionBar, IActionItemProvider, ActionsOrientation} from 'vs/base/browser/ui/actionbar/actionbar'; -import {EventEmitter} from 'vs/base/common/eventEmitter'; -import {Keybinding} from 'vs/base/common/keybinding'; +import { IDisposable } from 'vs/base/common/lifecycle'; +import { $ } from 'vs/base/browser/builder'; +import { IActionRunner, IAction } from 'vs/base/common/actions'; +import { ActionBar, IActionItemProvider, ActionsOrientation } from 'vs/base/browser/ui/actionbar/actionbar'; +import { EventEmitter } from 'vs/base/common/eventEmitter'; +import { Keybinding } from 'vs/base/common/keybinding'; export interface IMenuOptions { context?: any; diff --git a/src/vs/base/browser/ui/octiconLabel/octiconLabel.mock.ts b/src/vs/base/browser/ui/octiconLabel/octiconLabel.mock.ts index 635fb08e67453..1f6285529992e 100644 --- a/src/vs/base/browser/ui/octiconLabel/octiconLabel.mock.ts +++ b/src/vs/base/browser/ui/octiconLabel/octiconLabel.mock.ts @@ -3,9 +3,9 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import octiconLabel = require('vs/base/browser/ui/octiconLabel/octiconLabel'); -import {escape} from 'vs/base/common/strings'; +import { escape } from 'vs/base/common/strings'; -function expand(text:string): string { +function expand(text: string): string { return text; } diff --git a/src/vs/base/browser/ui/octiconLabel/octiconLabel.ts b/src/vs/base/browser/ui/octiconLabel/octiconLabel.ts index 2b900803410ce..184a14e47b2d0 100644 --- a/src/vs/base/browser/ui/octiconLabel/octiconLabel.ts +++ b/src/vs/base/browser/ui/octiconLabel/octiconLabel.ts @@ -6,7 +6,7 @@ import 'vs/css!./octicons/octicons'; -import {escape} from 'vs/base/common/strings'; +import { escape } from 'vs/base/common/strings'; export function expand(text: string): string { return text.replace(/\$\(([^)]+)\)/g, (match, g1) => { diff --git a/src/vs/base/browser/ui/progressbar/progressbar.ts b/src/vs/base/browser/ui/progressbar/progressbar.ts index ca4a2e08c468a..b110122c37dd1 100644 --- a/src/vs/base/browser/ui/progressbar/progressbar.ts +++ b/src/vs/base/browser/ui/progressbar/progressbar.ts @@ -6,13 +6,13 @@ 'use strict'; import 'vs/css!./progressbar'; -import {TPromise, ValueCallback} from 'vs/base/common/winjs.base'; +import { TPromise, ValueCallback } from 'vs/base/common/winjs.base'; import assert = require('vs/base/common/assert'); import browser = require('vs/base/browser/browser'); -import {Builder, $} from 'vs/base/browser/builder'; +import { Builder, $ } from 'vs/base/browser/builder'; import DOM = require('vs/base/browser/dom'); import uuid = require('vs/base/common/uuid'); -import {IDisposable,dispose} from 'vs/base/common/lifecycle'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; const css_done = 'done'; const css_active = 'active'; diff --git a/src/vs/base/browser/ui/resourceviewer/resourceViewer.ts b/src/vs/base/browser/ui/resourceviewer/resourceViewer.ts index db86ee614cf03..b5077f5ba33b0 100644 --- a/src/vs/base/browser/ui/resourceviewer/resourceViewer.ts +++ b/src/vs/base/browser/ui/resourceviewer/resourceViewer.ts @@ -10,10 +10,10 @@ import nls = require('vs/nls'); import mimes = require('vs/base/common/mime'); import URI from 'vs/base/common/uri'; import paths = require('vs/base/common/paths'); -import {Builder, $} from 'vs/base/browser/builder'; +import { Builder, $ } from 'vs/base/browser/builder'; import DOM = require('vs/base/browser/dom'); -import {DomScrollableElement} from 'vs/base/browser/ui/scrollbar/scrollableElement'; -import {BoundedLinkedMap} from 'vs/base/common/map'; +import { DomScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement'; +import { BoundedLinkedMap } from 'vs/base/common/map'; // Known media mimes that we can handle const mapExtToMediaMimes = { diff --git a/src/vs/base/browser/ui/sash/sash.ts b/src/vs/base/browser/ui/sash/sash.ts index c4159fe009924..6a726abbff34a 100644 --- a/src/vs/base/browser/ui/sash/sash.ts +++ b/src/vs/base/browser/ui/sash/sash.ts @@ -6,15 +6,15 @@ 'use strict'; import 'vs/css!./sash'; -import {IDisposable, dispose} from 'vs/base/common/lifecycle'; -import {Builder, $} from 'vs/base/browser/builder'; -import {isIPad} from 'vs/base/browser/browser'; -import {isMacintosh} from 'vs/base/common/platform'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { Builder, $ } from 'vs/base/browser/builder'; +import { isIPad } from 'vs/base/browser/browser'; +import { isMacintosh } from 'vs/base/common/platform'; import types = require('vs/base/common/types'); import DOM = require('vs/base/browser/dom'); -import {Gesture, EventType, GestureEvent} from 'vs/base/browser/touch'; -import {EventEmitter} from 'vs/base/common/eventEmitter'; -import {StandardMouseEvent} from 'vs/base/browser/mouseEvent'; +import { Gesture, EventType, GestureEvent } from 'vs/base/browser/touch'; +import { EventEmitter } from 'vs/base/common/eventEmitter'; +import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; export interface ISashLayoutProvider { } diff --git a/src/vs/base/browser/ui/scrollbar/abstractScrollbar.ts b/src/vs/base/browser/ui/scrollbar/abstractScrollbar.ts index dd738211757e0..29c945dfb876c 100644 --- a/src/vs/base/browser/ui/scrollbar/abstractScrollbar.ts +++ b/src/vs/base/browser/ui/scrollbar/abstractScrollbar.ts @@ -6,14 +6,14 @@ import * as Platform from 'vs/base/common/platform'; import * as DomUtils from 'vs/base/browser/dom'; -import {IMouseEvent, StandardMouseEvent, StandardMouseWheelEvent} from 'vs/base/browser/mouseEvent'; -import {GlobalMouseMoveMonitor, IStandardMouseMoveEventData, standardMouseMoveMerger} from 'vs/base/browser/globalMouseMoveMonitor'; -import {Widget} from 'vs/base/browser/ui/widget'; -import {FastDomNode, createFastDomNode} from 'vs/base/browser/styleMutator'; -import {ScrollbarState} from 'vs/base/browser/ui/scrollbar/scrollbarState'; -import {ScrollbarArrow, ScrollbarArrowOptions} from 'vs/base/browser/ui/scrollbar/scrollbarArrow'; -import {ScrollbarVisibilityController} from 'vs/base/browser/ui/scrollbar/scrollbarVisibilityController'; -import {Scrollable, ScrollbarVisibility} from 'vs/base/common/scrollable'; +import { IMouseEvent, StandardMouseEvent, StandardMouseWheelEvent } from 'vs/base/browser/mouseEvent'; +import { GlobalMouseMoveMonitor, IStandardMouseMoveEventData, standardMouseMoveMerger } from 'vs/base/browser/globalMouseMoveMonitor'; +import { Widget } from 'vs/base/browser/ui/widget'; +import { FastDomNode, createFastDomNode } from 'vs/base/browser/styleMutator'; +import { ScrollbarState } from 'vs/base/browser/ui/scrollbar/scrollbarState'; +import { ScrollbarArrow, ScrollbarArrowOptions } from 'vs/base/browser/ui/scrollbar/scrollbarArrow'; +import { ScrollbarVisibilityController } from 'vs/base/browser/ui/scrollbar/scrollbarVisibilityController'; +import { Scrollable, ScrollbarVisibility } from 'vs/base/common/scrollable'; /** * The orthogonal distance to the slider at which dragging "resets". This implements "snapping" @@ -34,7 +34,7 @@ export interface ScrollbarHost { export interface AbstractScrollbarOptions { canUseTranslate3d: boolean; - lazyRender:boolean; + lazyRender: boolean; host: ScrollbarHost; scrollbarState: ScrollbarState; visibility: ScrollbarVisibility; @@ -57,7 +57,7 @@ export abstract class AbstractScrollbar extends Widget { protected _shouldRender: boolean; - constructor(opts:AbstractScrollbarOptions) { + constructor(opts: AbstractScrollbarOptions) { super(); this._canUseTranslate3d = opts.canUseTranslate3d; this._lazyRender = opts.lazyRender; @@ -80,7 +80,7 @@ export abstract class AbstractScrollbar extends Widget { /** * Creates the dom node for an arrow & adds it to the container */ - protected _createArrow(opts:ScrollbarArrowOptions): void { + protected _createArrow(opts: ScrollbarArrowOptions): void { let arrow = this._register(new ScrollbarArrow(opts)); this.domNode.domNode.appendChild(arrow.bgDomNode); this.domNode.domNode.appendChild(arrow.domNode); diff --git a/src/vs/base/browser/ui/scrollbar/horizontalScrollbar.ts b/src/vs/base/browser/ui/scrollbar/horizontalScrollbar.ts index 12a7e96bcbe02..ea214d1e905d7 100644 --- a/src/vs/base/browser/ui/scrollbar/horizontalScrollbar.ts +++ b/src/vs/base/browser/ui/scrollbar/horizontalScrollbar.ts @@ -4,13 +4,13 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {AbstractScrollbar, ScrollbarHost, IMouseMoveEventData} from 'vs/base/browser/ui/scrollbar/abstractScrollbar'; -import {IMouseEvent, StandardMouseWheelEvent} from 'vs/base/browser/mouseEvent'; -import {IDomNodePagePosition} from 'vs/base/browser/dom'; -import {ScrollableElementResolvedOptions} from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; -import {Scrollable, ScrollEvent, ScrollbarVisibility} from 'vs/base/common/scrollable'; -import {ScrollbarState} from 'vs/base/browser/ui/scrollbar/scrollbarState'; -import {ARROW_IMG_SIZE} from 'vs/base/browser/ui/scrollbar/scrollbarArrow'; +import { AbstractScrollbar, ScrollbarHost, IMouseMoveEventData } from 'vs/base/browser/ui/scrollbar/abstractScrollbar'; +import { IMouseEvent, StandardMouseWheelEvent } from 'vs/base/browser/mouseEvent'; +import { IDomNodePagePosition } from 'vs/base/browser/dom'; +import { ScrollableElementResolvedOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; +import { Scrollable, ScrollEvent, ScrollbarVisibility } from 'vs/base/common/scrollable'; +import { ScrollbarState } from 'vs/base/browser/ui/scrollbar/scrollbarState'; +import { ARROW_IMG_SIZE } from 'vs/base/browser/ui/scrollbar/scrollbarArrow'; export class HorizontalScrollbar extends AbstractScrollbar { @@ -77,7 +77,7 @@ export class HorizontalScrollbar extends AbstractScrollbar { this.domNode.setBottom(0); } - public onDidScroll(e:ScrollEvent): boolean { + public onDidScroll(e: ScrollEvent): boolean { this._shouldRender = this._onElementScrollSize(e.scrollWidth) || this._shouldRender; this._shouldRender = this._onElementScrollPosition(e.scrollLeft) || this._shouldRender; this._shouldRender = this._onElementSize(e.width) || this._shouldRender; diff --git a/src/vs/base/browser/ui/scrollbar/scrollableElement.ts b/src/vs/base/browser/ui/scrollbar/scrollableElement.ts index f42246f9cf562..e209c7abf651f 100644 --- a/src/vs/base/browser/ui/scrollbar/scrollableElement.ts +++ b/src/vs/base/browser/ui/scrollbar/scrollableElement.ts @@ -9,17 +9,17 @@ import 'vs/css!./media/scrollbars'; import * as Browser from 'vs/base/browser/browser'; import * as DomUtils from 'vs/base/browser/dom'; import * as Platform from 'vs/base/common/platform'; -import {StandardMouseWheelEvent, IMouseEvent} from 'vs/base/browser/mouseEvent'; -import {HorizontalScrollbar} from 'vs/base/browser/ui/scrollbar/horizontalScrollbar'; -import {VerticalScrollbar} from 'vs/base/browser/ui/scrollbar/verticalScrollbar'; -import {ScrollableElementCreationOptions, ScrollableElementChangeOptions, ScrollableElementResolvedOptions} from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; -import {IDisposable, dispose} from 'vs/base/common/lifecycle'; -import {Scrollable, ScrollEvent, INewScrollState, ScrollbarVisibility} from 'vs/base/common/scrollable'; -import {Widget} from 'vs/base/browser/ui/widget'; -import {TimeoutTimer} from 'vs/base/common/async'; -import {FastDomNode, createFastDomNode} from 'vs/base/browser/styleMutator'; -import {ScrollbarHost} from 'vs/base/browser/ui/scrollbar/abstractScrollbar'; -import Event, {Emitter} from 'vs/base/common/event'; +import { StandardMouseWheelEvent, IMouseEvent } from 'vs/base/browser/mouseEvent'; +import { HorizontalScrollbar } from 'vs/base/browser/ui/scrollbar/horizontalScrollbar'; +import { VerticalScrollbar } from 'vs/base/browser/ui/scrollbar/verticalScrollbar'; +import { ScrollableElementCreationOptions, ScrollableElementChangeOptions, ScrollableElementResolvedOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { Scrollable, ScrollEvent, INewScrollState, ScrollbarVisibility } from 'vs/base/common/scrollable'; +import { Widget } from 'vs/base/browser/ui/widget'; +import { TimeoutTimer } from 'vs/base/common/async'; +import { FastDomNode, createFastDomNode } from 'vs/base/browser/styleMutator'; +import { ScrollbarHost } from 'vs/base/browser/ui/scrollbar/abstractScrollbar'; +import Event, { Emitter } from 'vs/base/common/event'; const HIDE_TIMEOUT = 500; const SCROLL_WHEEL_SENSITIVITY = 50; @@ -67,7 +67,7 @@ export class ScrollableElement extends Widget { // this._scrollable = this._register(new DelegateScrollable(scrollable, () => this._onScroll())); - let scrollbarHost:ScrollbarHost = { + let scrollbarHost: ScrollbarHost = { onMouseWheel: (mouseWheelEvent: StandardMouseWheelEvent) => this._onMouseWheel(mouseWheelEvent), onDragStart: () => this._onDragStart(), onDragEnd: () => this._onDragEnd(), @@ -140,7 +140,7 @@ export class ScrollableElement extends Widget { this._verticalScrollbar.delegateMouseDown(browserEvent); } - public updateState(newState:INewScrollState): void { + public updateState(newState: INewScrollState): void { this._scrollable.updateState(newState); } @@ -291,7 +291,7 @@ export class ScrollableElement extends Widget { } } - private _onDidScroll(e:ScrollEvent): void { + private _onDidScroll(e: ScrollEvent): void { this._shouldRender = this._horizontalScrollbar.onDidScroll(e) || this._shouldRender; this._shouldRender = this._verticalScrollbar.onDidScroll(e) || this._shouldRender; diff --git a/src/vs/base/browser/ui/scrollbar/scrollableElementOptions.ts b/src/vs/base/browser/ui/scrollbar/scrollableElementOptions.ts index 1db0602cde260..1f1ca8242baf2 100644 --- a/src/vs/base/browser/ui/scrollbar/scrollableElementOptions.ts +++ b/src/vs/base/browser/ui/scrollbar/scrollableElementOptions.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {ScrollbarVisibility} from 'vs/base/common/scrollable'; +import { ScrollbarVisibility } from 'vs/base/common/scrollable'; export interface ScrollableElementCreationOptions { /** diff --git a/src/vs/base/browser/ui/scrollbar/scrollbarArrow.ts b/src/vs/base/browser/ui/scrollbar/scrollbarArrow.ts index 1e70624cf0f4c..9ab0513e79a66 100644 --- a/src/vs/base/browser/ui/scrollbar/scrollbarArrow.ts +++ b/src/vs/base/browser/ui/scrollbar/scrollbarArrow.ts @@ -4,10 +4,10 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {IMouseEvent} from 'vs/base/browser/mouseEvent'; -import {GlobalMouseMoveMonitor, IStandardMouseMoveEventData, standardMouseMoveMerger} from 'vs/base/browser/globalMouseMoveMonitor'; -import {Widget} from 'vs/base/browser/ui/widget'; -import {TimeoutTimer, IntervalTimer} from 'vs/base/common/async'; +import { IMouseEvent } from 'vs/base/browser/mouseEvent'; +import { GlobalMouseMoveMonitor, IStandardMouseMoveEventData, standardMouseMoveMerger } from 'vs/base/browser/globalMouseMoveMonitor'; +import { Widget } from 'vs/base/browser/ui/widget'; +import { TimeoutTimer, IntervalTimer } from 'vs/base/common/async'; /** * The arrow image size. @@ -36,7 +36,7 @@ export class ScrollbarArrow extends Widget { private _mousedownScheduleRepeatTimer: TimeoutTimer; private _mouseMoveMonitor: GlobalMouseMoveMonitor; - constructor(opts:ScrollbarArrowOptions) { + constructor(opts: ScrollbarArrowOptions) { super(); this._onActivate = opts.onActivate; diff --git a/src/vs/base/browser/ui/scrollbar/scrollbarVisibilityController.ts b/src/vs/base/browser/ui/scrollbar/scrollbarVisibilityController.ts index f2dde2eb08d14..5b29c4b1f2c2b 100644 --- a/src/vs/base/browser/ui/scrollbar/scrollbarVisibilityController.ts +++ b/src/vs/base/browser/ui/scrollbar/scrollbarVisibilityController.ts @@ -4,10 +4,10 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {Disposable} from 'vs/base/common/lifecycle'; -import {TimeoutTimer} from 'vs/base/common/async'; -import {FastDomNode} from 'vs/base/browser/styleMutator'; -import {ScrollbarVisibility} from 'vs/base/common/scrollable'; +import { Disposable } from 'vs/base/common/lifecycle'; +import { TimeoutTimer } from 'vs/base/common/async'; +import { FastDomNode } from 'vs/base/browser/styleMutator'; +import { ScrollbarVisibility } from 'vs/base/common/scrollable'; export class ScrollbarVisibilityController extends Disposable { private _visibility: ScrollbarVisibility; diff --git a/src/vs/base/browser/ui/scrollbar/verticalScrollbar.ts b/src/vs/base/browser/ui/scrollbar/verticalScrollbar.ts index 921d84b83f6e7..3fce9dbc8df2c 100644 --- a/src/vs/base/browser/ui/scrollbar/verticalScrollbar.ts +++ b/src/vs/base/browser/ui/scrollbar/verticalScrollbar.ts @@ -4,13 +4,13 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {AbstractScrollbar, ScrollbarHost, IMouseMoveEventData} from 'vs/base/browser/ui/scrollbar/abstractScrollbar'; -import {IMouseEvent, StandardMouseWheelEvent} from 'vs/base/browser/mouseEvent'; -import {IDomNodePagePosition} from 'vs/base/browser/dom'; -import {ScrollableElementResolvedOptions} from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; -import {Scrollable, ScrollEvent, ScrollbarVisibility} from 'vs/base/common/scrollable'; -import {ScrollbarState} from 'vs/base/browser/ui/scrollbar/scrollbarState'; -import {ARROW_IMG_SIZE} from 'vs/base/browser/ui/scrollbar/scrollbarArrow'; +import { AbstractScrollbar, ScrollbarHost, IMouseMoveEventData } from 'vs/base/browser/ui/scrollbar/abstractScrollbar'; +import { IMouseEvent, StandardMouseWheelEvent } from 'vs/base/browser/mouseEvent'; +import { IDomNodePagePosition } from 'vs/base/browser/dom'; +import { ScrollableElementResolvedOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; +import { Scrollable, ScrollEvent, ScrollbarVisibility } from 'vs/base/common/scrollable'; +import { ScrollbarState } from 'vs/base/browser/ui/scrollbar/scrollbarState'; +import { ARROW_IMG_SIZE } from 'vs/base/browser/ui/scrollbar/scrollbarArrow'; export class VerticalScrollbar extends AbstractScrollbar { @@ -78,7 +78,7 @@ export class VerticalScrollbar extends AbstractScrollbar { this.domNode.setTop(0); } - public onDidScroll(e:ScrollEvent): boolean { + public onDidScroll(e: ScrollEvent): boolean { this._shouldRender = this._onElementScrollSize(e.scrollHeight) || this._shouldRender; this._shouldRender = this._onElementScrollPosition(e.scrollTop) || this._shouldRender; this._shouldRender = this._onElementSize(e.height) || this._shouldRender; diff --git a/src/vs/base/browser/ui/selectBox/selectBox.ts b/src/vs/base/browser/ui/selectBox/selectBox.ts index bd08f4c169385..54d041f94ce3e 100644 --- a/src/vs/base/browser/ui/selectBox/selectBox.ts +++ b/src/vs/base/browser/ui/selectBox/selectBox.ts @@ -5,9 +5,9 @@ import 'vs/css!./selectBox'; -import {IDisposable, dispose} from 'vs/base/common/lifecycle'; -import Event, {Emitter} from 'vs/base/common/event'; -import {Widget} from 'vs/base/browser/ui/widget'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import Event, { Emitter } from 'vs/base/common/event'; +import { Widget } from 'vs/base/browser/ui/widget'; import * as dom from 'vs/base/browser/dom'; export class SelectBox extends Widget { diff --git a/src/vs/base/browser/ui/splitview/splitview.ts b/src/vs/base/browser/ui/splitview/splitview.ts index 13e72e8cdb922..7c777e973a461 100644 --- a/src/vs/base/browser/ui/splitview/splitview.ts +++ b/src/vs/base/browser/ui/splitview/splitview.ts @@ -13,9 +13,9 @@ import objects = require('vs/base/common/objects'); import dom = require('vs/base/browser/dom'); import numbers = require('vs/base/common/numbers'); import sash = require('vs/base/browser/ui/sash/sash'); -import {StandardKeyboardEvent} from 'vs/base/browser/keyboardEvent'; -import {KeyCode} from 'vs/base/common/keyCodes'; -import Event, {Emitter} from 'vs/base/common/event'; +import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; +import { KeyCode } from 'vs/base/common/keyCodes'; +import Event, { Emitter } from 'vs/base/common/event'; export enum Orientation { VERTICAL, @@ -379,9 +379,9 @@ export abstract class FixedCollapsibleView extends AbstractCollapsibleView { } class PlainView extends View { - render() {} - focus() {} - layout() {} + render() { } + focus() { } + layout() { } } class DeadView extends PlainView { @@ -413,8 +413,7 @@ function sum(arr: number[]): number { export class SplitView implements sash.IHorizontalSashLayoutProvider, - sash.IVerticalSashLayoutProvider -{ + sash.IVerticalSashLayoutProvider { private orientation: Orientation; private el: HTMLElement; private size: number; diff --git a/src/vs/base/browser/ui/timer/timer.ts b/src/vs/base/browser/ui/timer/timer.ts index afa4e08efa0c6..1b19e91e145c2 100644 --- a/src/vs/base/browser/ui/timer/timer.ts +++ b/src/vs/base/browser/ui/timer/timer.ts @@ -6,8 +6,8 @@ 'use strict'; import 'vs/css!./timer'; -import {TimeKeeper, ITimerEvent, getTimeKeeper} from 'vs/base/common/timer'; -import {IDisposable, dispose} from 'vs/base/common/lifecycle'; +import { TimeKeeper, ITimerEvent, getTimeKeeper } from 'vs/base/common/timer'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import DomUtils = require('vs/base/browser/dom'); export class TimeKeeperRenderer { diff --git a/src/vs/base/browser/ui/toolbar/toolbar.ts b/src/vs/base/browser/ui/toolbar/toolbar.ts index 830e61d970d44..4ebedbee59b96 100644 --- a/src/vs/base/browser/ui/toolbar/toolbar.ts +++ b/src/vs/base/browser/ui/toolbar/toolbar.ts @@ -7,14 +7,14 @@ import 'vs/css!./toolbar'; import nls = require('vs/nls'); -import {TPromise} from 'vs/base/common/winjs.base'; -import {IDisposable} from 'vs/base/common/lifecycle'; -import {Builder, $} from 'vs/base/browser/builder'; +import { TPromise } from 'vs/base/common/winjs.base'; +import { IDisposable } from 'vs/base/common/lifecycle'; +import { Builder, $ } from 'vs/base/browser/builder'; import types = require('vs/base/common/types'); -import {Action, IActionRunner, IAction} from 'vs/base/common/actions'; -import {ActionBar, ActionsOrientation, IActionItemProvider, BaseActionItem} from 'vs/base/browser/ui/actionbar/actionbar'; -import {IContextMenuProvider, DropdownMenu, IActionProvider, ILabelRenderer, IDropdownMenuOptions} from 'vs/base/browser/ui/dropdown/dropdown'; -import {Keybinding} from 'vs/base/common/keybinding'; +import { Action, IActionRunner, IAction } from 'vs/base/common/actions'; +import { ActionBar, ActionsOrientation, IActionItemProvider, BaseActionItem } from 'vs/base/browser/ui/actionbar/actionbar'; +import { IContextMenuProvider, DropdownMenu, IActionProvider, ILabelRenderer, IDropdownMenuOptions } from 'vs/base/browser/ui/dropdown/dropdown'; +import { Keybinding } from 'vs/base/common/keybinding'; export const CONTEXT = 'context.toolbar'; diff --git a/src/vs/base/browser/ui/widget.ts b/src/vs/base/browser/ui/widget.ts index d1feb225c3994..c01fda038cca2 100644 --- a/src/vs/base/browser/ui/widget.ts +++ b/src/vs/base/browser/ui/widget.ts @@ -5,50 +5,50 @@ 'use strict'; -import {Disposable} from 'vs/base/common/lifecycle'; -import {StandardMouseEvent, IMouseEvent} from 'vs/base/browser/mouseEvent'; -import {StandardKeyboardEvent, IKeyboardEvent} from 'vs/base/browser/keyboardEvent'; +import { Disposable } from 'vs/base/common/lifecycle'; +import { StandardMouseEvent, IMouseEvent } from 'vs/base/browser/mouseEvent'; +import { StandardKeyboardEvent, IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import * as DomUtils from 'vs/base/browser/dom'; export abstract class Widget extends Disposable { - protected onclick(domNode:HTMLElement, listener:(e:IMouseEvent)=>void): void { - this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.CLICK, (e:MouseEvent) => listener(new StandardMouseEvent(e)))); + protected onclick(domNode: HTMLElement, listener: (e: IMouseEvent) => void): void { + this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.CLICK, (e: MouseEvent) => listener(new StandardMouseEvent(e)))); } - protected onmousedown(domNode:HTMLElement, listener:(e:IMouseEvent)=>void): void { - this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.MOUSE_DOWN, (e:MouseEvent) => listener(new StandardMouseEvent(e)))); + protected onmousedown(domNode: HTMLElement, listener: (e: IMouseEvent) => void): void { + this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.MOUSE_DOWN, (e: MouseEvent) => listener(new StandardMouseEvent(e)))); } - protected onmouseover(domNode:HTMLElement, listener:(e:IMouseEvent)=>void): void { - this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.MOUSE_OVER, (e:MouseEvent) => listener(new StandardMouseEvent(e)))); + protected onmouseover(domNode: HTMLElement, listener: (e: IMouseEvent) => void): void { + this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.MOUSE_OVER, (e: MouseEvent) => listener(new StandardMouseEvent(e)))); } - protected onnonbubblingmouseout(domNode:HTMLElement, listener:(e:IMouseEvent)=>void): void { - this._register(DomUtils.addDisposableNonBubblingMouseOutListener(domNode, (e:MouseEvent) => listener(new StandardMouseEvent(e)))); + protected onnonbubblingmouseout(domNode: HTMLElement, listener: (e: IMouseEvent) => void): void { + this._register(DomUtils.addDisposableNonBubblingMouseOutListener(domNode, (e: MouseEvent) => listener(new StandardMouseEvent(e)))); } - protected onkeydown(domNode:HTMLElement, listener:(e:IKeyboardEvent)=>void): void { - this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.KEY_DOWN, (e:KeyboardEvent) => listener(new StandardKeyboardEvent(e)))); + protected onkeydown(domNode: HTMLElement, listener: (e: IKeyboardEvent) => void): void { + this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.KEY_DOWN, (e: KeyboardEvent) => listener(new StandardKeyboardEvent(e)))); } - protected onkeyup(domNode:HTMLElement, listener:(e:IKeyboardEvent)=>void): void { - this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.KEY_UP, (e:KeyboardEvent) => listener(new StandardKeyboardEvent(e)))); + protected onkeyup(domNode: HTMLElement, listener: (e: IKeyboardEvent) => void): void { + this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.KEY_UP, (e: KeyboardEvent) => listener(new StandardKeyboardEvent(e)))); } - protected oninput(domNode:HTMLElement, listener:(e:Event)=>void): void { + protected oninput(domNode: HTMLElement, listener: (e: Event) => void): void { this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.INPUT, listener)); } - protected onblur(domNode:HTMLElement, listener:(e:Event)=>void): void { + protected onblur(domNode: HTMLElement, listener: (e: Event) => void): void { this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.BLUR, listener)); } - protected onfocus(domNode:HTMLElement, listener:(e:Event)=>void): void { + protected onfocus(domNode: HTMLElement, listener: (e: Event) => void): void { this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.FOCUS, listener)); } - protected onchange(domNode:HTMLElement, listener:(e:Event)=>void): void { + protected onchange(domNode: HTMLElement, listener: (e: Event) => void): void { this._register(DomUtils.addDisposableListener(domNode, DomUtils.EventType.CHANGE, listener)); } } diff --git a/src/vs/base/common/actions.ts b/src/vs/base/common/actions.ts index 3c1a0238f38c5..a605a213eac71 100644 --- a/src/vs/base/common/actions.ts +++ b/src/vs/base/common/actions.ts @@ -4,11 +4,11 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {TPromise} from 'vs/base/common/winjs.base'; +import { TPromise } from 'vs/base/common/winjs.base'; import { IEventEmitter, EventEmitter } from 'vs/base/common/eventEmitter'; -import {IDisposable} from 'vs/base/common/lifecycle'; +import { IDisposable } from 'vs/base/common/lifecycle'; import * as Events from 'vs/base/common/events'; -import Event, {Emitter} from 'vs/base/common/event'; +import Event, { Emitter } from 'vs/base/common/event'; export interface IAction extends IDisposable { id: string; diff --git a/src/vs/base/common/arrays.ts b/src/vs/base/common/arrays.ts index c822c32c111e5..805d6241d1950 100644 --- a/src/vs/base/common/arrays.ts +++ b/src/vs/base/common/arrays.ts @@ -19,7 +19,7 @@ export function tail(array: T[], n: number = 0): T { */ export function forEach(array: T[], callback: (element: T, remove: Function) => void): void { for (var i = 0, len = array.length; i < len; i++) { - callback(array[i], function() { + callback(array[i], function () { array.splice(i, 1); i--; len--; }); @@ -261,8 +261,8 @@ export function fill(num: number, valueFn: () => T, arr: T[] = []): T[] { } export function index(array: T[], indexer: (t: T) => string): { [key: string]: T; }; -export function index(array: T[], indexer: (t: T) => string, merger?: (t: T, r: R) => R): { [key: string]: R; }; -export function index(array: T[], indexer: (t: T) => string, merger: (t: T, r: R) => R = t => t as any): { [key: string]: R; } { +export function index(array: T[], indexer: (t: T) => string, merger?: (t: T, r: R) => R): { [key: string]: R; }; +export function index(array: T[], indexer: (t: T) => string, merger: (t: T, r: R) => R = t => t as any): { [key: string]: R; } { return array.reduce((r, t) => { const key = indexer(t); r[key] = merger(t, r[key]); diff --git a/src/vs/base/common/async.ts b/src/vs/base/common/async.ts index 5c5b079b7ff4d..e6267cfe4c1a5 100644 --- a/src/vs/base/common/async.ts +++ b/src/vs/base/common/async.ts @@ -403,7 +403,7 @@ export function once(fn: T): T { let didCall = false; let result: any; - return function() { + return function () { if (didCall) { return result; } @@ -488,7 +488,7 @@ export class TimeoutTimer extends Disposable { } } - cancelAndSet(runner: () => void, timeout:number): void { + cancelAndSet(runner: () => void, timeout: number): void { this.cancel(); this._token = platform.setTimeout(() => { this._token = -1; @@ -529,7 +529,7 @@ export class IntervalTimer extends Disposable { } } - cancelAndSet(runner: () => void, interval:number): void { + cancelAndSet(runner: () => void, interval: number): void { this.cancel(); this._token = platform.setInterval(() => { runner(); diff --git a/src/vs/base/common/cache.ts b/src/vs/base/common/cache.ts index 9ed07ab56c2b3..65c468842ced5 100644 --- a/src/vs/base/common/cache.ts +++ b/src/vs/base/common/cache.ts @@ -10,7 +10,7 @@ import { TPromise } from 'vs/base/common/winjs.base'; export default class Cache { private promise: TPromise = null; - constructor(private task: ()=>TPromise) {} + constructor(private task: () => TPromise) { } get(): TPromise { if (this.promise) { diff --git a/src/vs/base/common/callbackList.ts b/src/vs/base/common/callbackList.ts index 4471fb6d632c3..02f7580ff2729 100644 --- a/src/vs/base/common/callbackList.ts +++ b/src/vs/base/common/callbackList.ts @@ -4,8 +4,8 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {IDisposable} from 'vs/base/common/lifecycle'; -import {onUnexpectedError} from 'vs/base/common/errors'; +import { IDisposable } from 'vs/base/common/lifecycle'; +import { onUnexpectedError } from 'vs/base/common/errors'; export default class CallbackList { diff --git a/src/vs/base/common/cancellation.ts b/src/vs/base/common/cancellation.ts index ba8f97a834c17..73a63574fc1eb 100644 --- a/src/vs/base/common/cancellation.ts +++ b/src/vs/base/common/cancellation.ts @@ -5,14 +5,14 @@ 'use strict'; -import Event, {Emitter} from 'vs/base/common/event'; +import Event, { Emitter } from 'vs/base/common/event'; export interface CancellationToken { isCancellationRequested: boolean; onCancellationRequested: Event; } -const shortcutEvent: Event = Object.freeze(function(callback, context?) { +const shortcutEvent: Event = Object.freeze(function (callback, context?) { let handle = setTimeout(callback.bind(context), 0); return { dispose() { clearTimeout(handle); } }; }); diff --git a/src/vs/base/common/collections.ts b/src/vs/base/common/collections.ts index dd961aa38962c..56369b827fe1c 100644 --- a/src/vs/base/common/collections.ts +++ b/src/vs/base/common/collections.ts @@ -115,7 +115,7 @@ export function forEach(from: INumberDictionary, callback: (entry: { key: export function forEach(from: any, callback: (entry: { key: any; value: T; }, remove: Function) => any): void { for (var key in from) { if (hasOwnProperty.call(from, key)) { - const result = callback({ key: key, value: from[key] }, function() { + const result = callback({ key: key, value: from[key] }, function () { delete from[key]; }); if (result === false) { diff --git a/src/vs/base/common/decorators.ts b/src/vs/base/common/decorators.ts index d11a4fb43c6b2..d20f57e96c30c 100644 --- a/src/vs/base/common/decorators.ts +++ b/src/vs/base/common/decorators.ts @@ -21,7 +21,7 @@ export function memoize(target: any, key: string, descriptor: any) { throw new Error('not supported'); } - const memoizeKey = `$memoize$${ key }`; + const memoizeKey = `$memoize$${key}`; descriptor[fnKey] = function (...args) { if (!this.hasOwnProperty(memoizeKey)) { diff --git a/src/vs/base/common/diagnostics.ts b/src/vs/base/common/diagnostics.ts index a83885e2755e0..dc866d18614ba 100644 --- a/src/vs/base/common/diagnostics.ts +++ b/src/vs/base/common/diagnostics.ts @@ -12,7 +12,7 @@ import * as Platform from 'vs/base/common/platform'; */ var globals = Platform.globals; -if(!globals.Monaco) { +if (!globals.Monaco) { globals.Monaco = {}; } globals.Monaco.Diagnostics = {}; @@ -21,8 +21,8 @@ var switches = globals.Monaco.Diagnostics; var map = {}; var data = []; -function fifo(array:any[], size:number) { - while(array.length > size) { +function fifo(array: any[], size: number) { + while (array.length > size) { array.shift(); } } @@ -45,23 +45,23 @@ export function register(what: string, fn: Function): (...args: any[]) => void { tracers.push(fn); map[what] = tracers; - var result = function(...args:any[]) { + var result = function (...args: any[]) { - var idx:number; + var idx: number; - if(switches[what] === true) { + if (switches[what] === true) { // replay back-in-time functions var allArgs = [arguments]; idx = data.indexOf(fn); - if(idx !== -1) { + if (idx !== -1) { allArgs.unshift.apply(allArgs, data[idx + 1] || []); data[idx + 1] = []; } - var doIt:()=>void = function() { + var doIt: () => void = function () { var thisArguments = allArgs.shift(); fn.apply(fn, thisArguments); - if(allArgs.length > 0) { + if (allArgs.length > 0) { Platform.setTimeout(doIt, 500); } }; diff --git a/src/vs/base/common/diff/diff.ts b/src/vs/base/common/diff/diff.ts index 7f98094c4bbde..a72323015b5e3 100644 --- a/src/vs/base/common/diff/diff.ts +++ b/src/vs/base/common/diff/diff.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {DiffChange} from 'vs/base/common/diff/diffChange'; +import { DiffChange } from 'vs/base/common/diff/diffChange'; function createStringSequence(a: string): ISequence { @@ -22,7 +22,7 @@ export function stringDiff(original: string, modified: string): IDiffChange[] { export interface ISequence { getLength(): number; - getElementHash(index:number): string; + getElementHash(index: number): string; } export interface IDiffChange { @@ -30,29 +30,29 @@ export interface IDiffChange { * The position of the first element in the original sequence which * this change affects. */ - originalStart:number; + originalStart: number; /** * The number of elements from the original sequence which were * affected. */ - originalLength:number; + originalLength: number; /** * The position of the first element in the modified sequence which * this change affects. */ - modifiedStart:number; + modifiedStart: number; /** * The number of elements from the modified sequence which were * affected (added). */ - modifiedLength:number; + modifiedLength: number; } export interface IContinueProcessingPredicate { - (furthestOriginalIndex:number, originalSequence:ISequence, matchLengthOfLongest:number): boolean; + (furthestOriginalIndex: number, originalSequence: ISequence, matchLengthOfLongest: number): boolean; } // @@ -61,7 +61,7 @@ export interface IContinueProcessingPredicate { export class Debug { - public static Assert(condition:boolean, message:string): void { + public static Assert(condition: boolean, message: string): void { if (!condition) { throw new Error(message); } @@ -84,7 +84,7 @@ export class MyArray { * length: * A 64-bit integer that represents the number of elements to copy. */ - public static Copy(sourceArray:any[], sourceIndex:number, destinationArray:any[], destinationIndex:number, length:number) { + public static Copy(sourceArray: any[], sourceIndex: number, destinationArray: any[], destinationIndex: number, length: number) { for (let i = 0; i < length; i++) { destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i]; } @@ -119,11 +119,11 @@ let MaxDifferencesHistory = 1447; */ class DiffChangeHelper { - private m_changes:DiffChange[]; - private m_originalStart:number; - private m_modifiedStart:number; - private m_originalCount:number; - private m_modifiedCount:number; + private m_changes: DiffChange[]; + private m_originalStart: number; + private m_modifiedStart: number; + private m_originalCount: number; + private m_modifiedCount: number; /** * Constructs a new DiffChangeHelper for the given DiffSequences. @@ -161,7 +161,7 @@ class DiffChangeHelper { * @param originalIndex The index of the original element to add. * @param modifiedIndex The index of the modified element that provides corresponding position in the modified sequence. */ - public AddOriginalElement(originalIndex:number, modifiedIndex:number) { + public AddOriginalElement(originalIndex: number, modifiedIndex: number) { // The 'true' start index is the smallest of the ones we've seen this.m_originalStart = Math.min(this.m_originalStart, originalIndex); this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex); @@ -176,7 +176,7 @@ class DiffChangeHelper { * @param originalIndex The index of the original element that provides corresponding position in the original sequence. * @param modifiedIndex The index of the modified element to add. */ - public AddModifiedElement(originalIndex:number, modifiedIndex:number): void { + public AddModifiedElement(originalIndex: number, modifiedIndex: number): void { // The 'true' start index is the smallest of the ones we've seen this.m_originalStart = Math.min(this.m_originalStart, originalIndex); this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex); @@ -219,19 +219,19 @@ const hasOwnProperty = Object.prototype.hasOwnProperty; */ export class LcsDiff { - private OriginalSequence:ISequence; - private ModifiedSequence:ISequence; - private ContinueProcessingPredicate:IContinueProcessingPredicate; + private OriginalSequence: ISequence; + private ModifiedSequence: ISequence; + private ContinueProcessingPredicate: IContinueProcessingPredicate; - private m_originalIds:number[]; - private m_modifiedIds:number[]; - private m_forwardHistory:number[][]; - private m_reverseHistory:number[][]; + private m_originalIds: number[]; + private m_modifiedIds: number[]; + private m_forwardHistory: number[][]; + private m_reverseHistory: number[][]; /** * Constructs the DiffFinder */ - constructor(originalSequence:ISequence, newSequence:ISequence, continueProcessingPredicate:IContinueProcessingPredicate = null) { + constructor(originalSequence: ISequence, newSequence: ISequence, continueProcessingPredicate: IContinueProcessingPredicate = null) { this.OriginalSequence = originalSequence; this.ModifiedSequence = newSequence; this.ContinueProcessingPredicate = continueProcessingPredicate; @@ -252,7 +252,7 @@ export class LcsDiff { // Create a new hash table for unique elements from the original // sequence. - let hashTable:{[key:string]:number;} = {}; + let hashTable: { [key: string]: number; } = {}; let currentUniqueId = 1; let i: number; @@ -282,7 +282,7 @@ export class LcsDiff { } } - private ElementsAreEqual(originalIndex:number, newIndex:number): boolean { + private ElementsAreEqual(originalIndex: number, newIndex: number): boolean { return this.m_originalIds[originalIndex] === this.m_modifiedIds[newIndex]; } @@ -295,8 +295,8 @@ export class LcsDiff { * sequences on the bounded range. * @returns An array of the differences between the two input sequences. */ - private _ComputeDiff(originalStart:number, originalEnd:number, modifiedStart:number, modifiedEnd:number): DiffChange[] { - let quitEarlyArr = [ false ]; + private _ComputeDiff(originalStart: number, originalEnd: number, modifiedStart: number, modifiedEnd: number): DiffChange[] { + let quitEarlyArr = [false]; return this.ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr); } @@ -305,7 +305,7 @@ export class LcsDiff { * recursively. * @returns An array of the differences between the two input sequences. */ - private ComputeDiffRecursive(originalStart:number, originalEnd:number, modifiedStart:number, modifiedEnd:number, quitEarlyArr:boolean[]): DiffChange[] { + private ComputeDiffRecursive(originalStart: number, originalEnd: number, modifiedStart: number, modifiedEnd: number, quitEarlyArr: boolean[]): DiffChange[] { quitEarlyArr[0] = false; // Find the start of the differences @@ -322,7 +322,7 @@ export class LcsDiff { // In the special case where we either have all insertions or all deletions or the sequences are identical if (originalStart > originalEnd || modifiedStart > modifiedEnd) { - let changes:DiffChange[]; + let changes: DiffChange[]; if (modifiedStart <= modifiedEnd) { Debug.Assert(originalStart === originalEnd + 1, 'originalStart should only be one more than originalEnd'); @@ -384,16 +384,16 @@ export class LcsDiff { // If we hit here, we quit early, and so can't return anything meaningful return [ - new DiffChange(originalStart, originalEnd -originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1) + new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1) ]; } - private WALKTRACE(diagonalForwardBase:number, diagonalForwardStart:number, diagonalForwardEnd:number, diagonalForwardOffset:number, - diagonalReverseBase:number, diagonalReverseStart:number, diagonalReverseEnd:number, diagonalReverseOffset:number, - forwardPoints:number[], reversePoints:number[], - originalIndex:number, originalEnd:number, midOriginalArr:number[], - modifiedIndex:number, modifiedEnd:number, midModifiedArr:number[], - deltaIsEven:boolean, quitEarlyArr:boolean[]): DiffChange[] { + private WALKTRACE(diagonalForwardBase: number, diagonalForwardStart: number, diagonalForwardEnd: number, diagonalForwardOffset: number, + diagonalReverseBase: number, diagonalReverseStart: number, diagonalReverseEnd: number, diagonalReverseOffset: number, + forwardPoints: number[], reversePoints: number[], + originalIndex: number, originalEnd: number, midOriginalArr: number[], + modifiedIndex: number, modifiedEnd: number, midModifiedArr: number[], + deltaIsEven: boolean, quitEarlyArr: boolean[]): DiffChange[] { let forwardChanges: DiffChange[] = null, reverseChanges: DiffChange[] = null; // First, walk backward through the forward diagonals history @@ -459,7 +459,7 @@ export class LcsDiff { reverseChanges = [ new DiffChange(originalStartPoint, originalEnd - originalStartPoint + 1, - modifiedStartPoint, modifiedEnd - modifiedStartPoint + 1) + modifiedStartPoint, modifiedEnd - modifiedStartPoint + 1) ]; } else { // Now walk backward through the reverse diagonals history @@ -529,11 +529,11 @@ export class LcsDiff { * @param midModified The middle point of the modified sequence range * @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; + private ComputeRecursionPoint(originalStart: number, originalEnd: number, modifiedStart: number, modifiedEnd: number, midOriginalArr: number[], midModifiedArr: number[], quitEarlyArr: boolean[]) { + let originalIndex: number, modifiedIndex: number; let diagonalForwardStart = 0, diagonalForwardEnd = 0; let diagonalReverseStart = 0, diagonalReverseEnd = 0; - let numDifferences:number; + let numDifferences: number; // To traverse the edit graph and produce the proper LCS, our actual // start position is just outside the given boundary @@ -555,8 +555,8 @@ export class LcsDiff { // The modifiedIndex can be computed mathematically from the originalIndex and the diagonal number. let maxDifferences = (originalEnd - originalStart) + (modifiedEnd - modifiedStart); let numDiagonals = maxDifferences + 1; - let forwardPoints:number[] = new Array(numDiagonals); - let reversePoints:number[] = new Array(numDiagonals); + let forwardPoints: number[] = new Array(numDiagonals); + let reversePoints: number[] = new Array(numDiagonals); // diagonalForwardBase: Index into forwardPoints of the diagonal which passes through (originalStart, modifiedStart) // diagonalReverseBase: Index into reversePoints of the diagonal which passes through (originalEnd, modifiedEnd) let diagonalForwardBase = (modifiedEnd - modifiedStart); @@ -591,7 +591,7 @@ export class LcsDiff { // away from the reference diagonal (which is diagonalForwardBase for forward, diagonalReverseBase for reverse). // --We extend on even diagonals (relative to the reference diagonal) only when numDifferences // is even and odd diagonals only when numDifferences is odd. - let diagonal:number, tempOriginalIndex:number; + let diagonal: number, tempOriginalIndex: number; for (numDifferences = 1; numDifferences <= (maxDifferences / 2) + 1; numDifferences++) { let furthestOriginalIndex = 0; let furthestModifiedIndex = 0; @@ -683,7 +683,7 @@ export class LcsDiff { return [ new DiffChange(originalStart, originalEnd - originalStart + 1, - modifiedStart, modifiedEnd - modifiedStart + 1) + modifiedStart, modifiedEnd - modifiedStart + 1) ]; } } @@ -743,7 +743,7 @@ export class LcsDiff { if (numDifferences <= MaxDifferencesHistory) { // We are allocating space for one extra int, which we fill with // the index of the diagonal base index - let temp:number[] = new Array(diagonalForwardEnd - diagonalForwardStart + 2); + let temp: number[] = new Array(diagonalForwardEnd - diagonalForwardStart + 2); temp[0] = diagonalForwardBase - diagonalForwardStart + 1; MyArray.Copy(forwardPoints, diagonalForwardStart, temp, 1, diagonalForwardEnd - diagonalForwardStart + 1); this.m_forwardHistory.push(temp); @@ -776,9 +776,9 @@ export class LcsDiff { * @param The right changes * @returns The concatenated list */ - private ConcatenateChanges(left:DiffChange[], right:DiffChange[]): DiffChange[] { - let mergedChangeArr:DiffChange[] = []; - let result:DiffChange[] = null; + 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; @@ -810,12 +810,11 @@ 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[]): 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'); - if (left.originalStart + left.originalLength >= right.originalStart || left.modifiedStart + left.modifiedLength >= right.modifiedStart) - { + if (left.originalStart + left.originalLength >= right.originalStart || left.modifiedStart + left.modifiedLength >= right.modifiedStart) { let originalStart = left.originalStart; let originalLength = left.originalLength; let modifiedStart = left.modifiedStart; @@ -849,7 +848,7 @@ export class LcsDiff { * @returns The clipped diagonal index. */ - private ClipDiagonalBound(diagonal:number, numDifferences:number, diagonalBaseIndex:number, numDiagonals:number): number { + private ClipDiagonalBound(diagonal: number, numDifferences: number, diagonalBaseIndex: number, numDiagonals: number): number { if (diagonal >= 0 && diagonal < numDiagonals) { // Nothing to clip, its in range return diagonal; diff --git a/src/vs/base/common/diff/diff2.ts b/src/vs/base/common/diff/diff2.ts index 8fddbbb62a984..c37b16e49e566 100644 --- a/src/vs/base/common/diff/diff2.ts +++ b/src/vs/base/common/diff/diff2.ts @@ -4,11 +4,11 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {DiffChange} from 'vs/base/common/diff/diffChange'; +import { DiffChange } from 'vs/base/common/diff/diffChange'; export interface ISequence { getLength(): number; - getElementHash(index:number): string; + getElementHash(index: number): string; } export interface IDiffChange { @@ -16,33 +16,33 @@ export interface IDiffChange { * The position of the first element in the original sequence which * this change affects. */ - originalStart:number; + originalStart: number; /** * The number of elements from the original sequence which were * affected. */ - originalLength:number; + originalLength: number; /** * The position of the first element in the modified sequence which * this change affects. */ - modifiedStart:number; + modifiedStart: number; /** * The number of elements from the modified sequence which were * affected (added). */ - modifiedLength:number; + modifiedLength: number; } export interface IContinueProcessingPredicate { - (furthestOriginalIndex:number, originalSequence:ISequence, matchLengthOfLongest:number): boolean; + (furthestOriginalIndex: number, originalSequence: ISequence, matchLengthOfLongest: number): boolean; } export interface IHashFunction { - (sequence: ISequence, index:number): string; + (sequence: ISequence, index: number): string; } /** @@ -50,22 +50,22 @@ export interface IHashFunction { */ export class LcsDiff2 { - private x:ISequence; - private y:ISequence; + private x: ISequence; + private y: ISequence; - private ids_for_x:number[]; - private ids_for_y:number[]; + private ids_for_x: number[]; + private ids_for_y: number[]; - private hashFunc:IHashFunction; + private hashFunc: IHashFunction; - private resultX:boolean[]; - private resultY:boolean[]; - private forwardPrev:number[]; - private forwardCurr:number[]; - private backwardPrev:number[]; - private backwardCurr:number[]; + private resultX: boolean[]; + private resultY: boolean[]; + private forwardPrev: number[]; + private forwardCurr: number[]; + private backwardPrev: number[]; + private backwardCurr: number[]; - constructor(originalSequence:ISequence, newSequence:ISequence, continueProcessingPredicate:IContinueProcessingPredicate, hashFunc:IHashFunction) { + constructor(originalSequence: ISequence, newSequence: ISequence, continueProcessingPredicate: IContinueProcessingPredicate, hashFunc: IHashFunction) { this.x = originalSequence; this.y = newSequence; this.ids_for_x = []; @@ -105,9 +105,9 @@ export class LcsDiff2 { // Create a new hash table for unique elements from the original // sequence. - let hashTable:{[key:string]:number;} = {}; + let hashTable: { [key: string]: number; } = {}; let currentUniqueId = 1; - let i:number; + let i: number; // Fill up the hash table for unique elements for (i = 0; i < xLength; i++) { @@ -135,7 +135,7 @@ export class LcsDiff2 { } } - private ElementsAreEqual(xIndex:number, yIndex:number): boolean { + private ElementsAreEqual(xIndex: number, yIndex: number): boolean { return this.ids_for_x[xIndex] === this.ids_for_y[yIndex]; } @@ -176,17 +176,17 @@ export class LcsDiff2 { return changes; } - private forward(xStart:number, xStop:number, yStart:number, yStop:number): number[] { + private forward(xStart: number, xStop: number, yStart: number, yStop: number): number[] { let prev = this.forwardPrev, curr = this.forwardCurr, - tmp:number[], - i:number, - j:number; + tmp: number[], + i: number, + j: number; // First line prev[yStart] = this.ElementsAreEqual(xStart, yStart) ? 1 : 0; for (j = yStart + 1; j <= yStop; j++) { - prev[j] = this.ElementsAreEqual(xStart, j) ? 1 : prev[j-1]; + prev[j] = this.ElementsAreEqual(xStart, j) ? 1 : prev[j - 1]; } for (i = xStart + 1; i <= xStop; i++) { @@ -195,9 +195,9 @@ export class LcsDiff2 { for (j = yStart + 1; j <= yStop; j++) { if (this.ElementsAreEqual(i, j)) { - curr[j] = prev[j-1] + 1; + curr[j] = prev[j - 1] + 1; } else { - curr[j] = prev[j] > curr[j-1] ? prev[j] : curr[j-1]; + curr[j] = prev[j] > curr[j - 1] ? prev[j] : curr[j - 1]; } } @@ -211,17 +211,17 @@ export class LcsDiff2 { return prev; } - private backward(xStart:number, xStop:number, yStart:number, yStop:number): number[] { + private backward(xStart: number, xStop: number, yStart: number, yStop: number): number[] { let prev = this.backwardPrev, curr = this.backwardCurr, - tmp:number[], - i:number, - j:number; + tmp: number[], + i: number, + j: number; // Last line prev[yStop] = this.ElementsAreEqual(xStop, yStop) ? 1 : 0; for (j = yStop - 1; j >= yStart; j--) { - prev[j] = this.ElementsAreEqual(xStop, j) ? 1 : prev[j+1]; + prev[j] = this.ElementsAreEqual(xStop, j) ? 1 : prev[j + 1]; } for (i = xStop - 1; i >= xStart; i--) { @@ -230,9 +230,9 @@ export class LcsDiff2 { for (j = yStop - 1; j >= yStart; j--) { if (this.ElementsAreEqual(i, j)) { - curr[j] = prev[j+1] + 1; + curr[j] = prev[j + 1] + 1; } else { - curr[j] = prev[j] > curr[j+1] ? prev[j] : curr[j+1]; + curr[j] = prev[j] > curr[j + 1] ? prev[j] : curr[j + 1]; } } @@ -246,17 +246,17 @@ export class LcsDiff2 { return prev; } - private findCut(xStart:number, xStop:number, yStart:number, yStop:number, middle:number): number { + private findCut(xStart: number, xStop: number, yStart: number, yStop: number, middle: number): number { let L1 = this.forward(xStart, middle, yStart, yStop); let L2 = this.backward(middle + 1, xStop, yStart, yStop); // First cut - let max = L2[yStart], cut = yStart-1; + let max = L2[yStart], cut = yStart - 1; // Middle cut for (let j = yStart; j < yStop; j++) { - if (L1[j] + L2[j+1] > max) { - max = L1[j] + L2[j+1]; + if (L1[j] + L2[j + 1] > max) { + max = L1[j] + L2[j + 1]; cut = j; } } @@ -270,28 +270,28 @@ export class LcsDiff2 { return cut; } - private execute(xStart:number, xStop:number, yStart:number, yStop:number) { + private execute(xStart: number, xStop: number, yStart: number, yStop: number) { // Do some prefix trimming while (xStart <= xStop && yStart <= yStop && this.ElementsAreEqual(xStart, yStart)) { this.resultX[xStart] = true; - xStart ++; + xStart++; this.resultY[yStart] = true; - yStart ++; + yStart++; } // Do some suffix trimming while (xStart <= xStop && yStart <= yStop && this.ElementsAreEqual(xStop, yStop)) { this.resultX[xStop] = true; - xStop --; + xStop--; this.resultY[yStop] = true; - yStop --; + yStop--; } if (xStart > xStop || yStart > yStop) { return; } - let found:number, i:number; + let found: number, i: number; if (xStart === xStop) { found = -1; for (i = yStart; i <= yStop; i++) { @@ -326,7 +326,7 @@ export class LcsDiff2 { } if (cut + 1 <= yStop) { - this.execute(middle+1, xStop, cut+1, yStop); + this.execute(middle + 1, xStop, cut + 1, yStop); } } } diff --git a/src/vs/base/common/diff/diffChange.ts b/src/vs/base/common/diff/diffChange.ts index dfe3341d59097..3a137d76f1096 100644 --- a/src/vs/base/common/diff/diffChange.ts +++ b/src/vs/base/common/diff/diffChange.ts @@ -5,9 +5,9 @@ 'use strict'; export const DifferenceType = { - Add : 0, - Remove : 1, - Change : 2 + Add: 0, + Remove: 1, + Change: 2 }; /** @@ -19,31 +19,31 @@ export class DiffChange { * The position of the first element in the original sequence which * this change affects. */ - public originalStart:number; + public originalStart: number; /** * The number of elements from the original sequence which were * affected. */ - public originalLength:number; + public originalLength: number; /** * The position of the first element in the modified sequence which * this change affects. */ - public modifiedStart:number; + public modifiedStart: number; /** * The number of elements from the modified sequence which were * affected (added). */ - public modifiedLength:number; + public modifiedLength: number; /** * Constructs a new DiffChange with the given sequence information * and content. */ - constructor(originalStart:number, originalLength:number, modifiedStart:number, modifiedLength:number) { + constructor(originalStart: number, originalLength: number, modifiedStart: number, modifiedLength: number) { //Debug.Assert(originalLength > 0 || modifiedLength > 0, "originalLength and modifiedLength cannot both be <= 0"); this.originalStart = originalStart; this.originalLength = originalLength; diff --git a/src/vs/base/common/errorMessage.ts b/src/vs/base/common/errorMessage.ts index 98080b8e98058..9f5ed7fda90d0 100644 --- a/src/vs/base/common/errorMessage.ts +++ b/src/vs/base/common/errorMessage.ts @@ -9,7 +9,7 @@ import objects = require('vs/base/common/objects'); import types = require('vs/base/common/types'); import arrays = require('vs/base/common/arrays'); import strings = require('vs/base/common/strings'); -import {IXHRResponse} from 'vs/base/common/http'; +import { IXHRResponse } from 'vs/base/common/http'; export interface IConnectionErrorData { status: number; diff --git a/src/vs/base/common/errors.ts b/src/vs/base/common/errors.ts index 33f9a32b6e119..5c1adfdc994e3 100644 --- a/src/vs/base/common/errors.ts +++ b/src/vs/base/common/errors.ts @@ -6,7 +6,7 @@ import platform = require('vs/base/common/platform'); import types = require('vs/base/common/types'); -import {IAction} from 'vs/base/common/actions'; +import { IAction } from 'vs/base/common/actions'; import Severity from 'vs/base/common/severity'; import { TPromise } from 'vs/base/common/winjs.base'; @@ -27,7 +27,7 @@ export class ErrorHandler { this.listeners = []; - this.unexpectedErrorHandler = function(e: any) { + this.unexpectedErrorHandler = function (e: any) { platform.setTimeout(() => { if (e.stack) { throw new Error(e.message + '\n\n' + e.stack); diff --git a/src/vs/base/common/event.ts b/src/vs/base/common/event.ts index 1e76db167f723..9f9d99f83d1c6 100644 --- a/src/vs/base/common/event.ts +++ b/src/vs/base/common/event.ts @@ -4,10 +4,10 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {IDisposable, dispose} from 'vs/base/common/lifecycle'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import CallbackList from 'vs/base/common/callbackList'; -import {EventEmitter} from 'vs/base/common/eventEmitter'; -import {TPromise} from 'vs/base/common/winjs.base'; +import { EventEmitter } from 'vs/base/common/eventEmitter'; +import { TPromise } from 'vs/base/common/winjs.base'; /** * To an event a function with one or zero parameters @@ -19,7 +19,7 @@ interface Event { namespace Event { const _disposable = { dispose() { } }; - export const None: Event = function() { return _disposable; }; + export const None: Event = function () { return _disposable; }; } export default Event; @@ -69,7 +69,7 @@ export class Emitter { */ get event(): Event { if (!this._event) { - this._event = (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[]) => { + this._event = (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[]) => { if (!this._callbacks) { this._callbacks = new CallbackList(); } @@ -92,13 +92,13 @@ export class Emitter { result.dispose = Emitter._noop; if (!this._disposed) { this._callbacks.remove(listener, thisArgs); - if(this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) { + if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) { this._options.onLastListenerRemove(this); } } } }; - if(Array.isArray(disposables)) { + if (Array.isArray(disposables)) { disposables.push(result); } @@ -119,7 +119,7 @@ export class Emitter { } dispose() { - if(this._callbacks) { + if (this._callbacks) { this._callbacks.dispose(); this._callbacks = undefined; this._disposed = true; @@ -154,7 +154,7 @@ export function fromEventEmitter(emitter: EventEmitter, eventType: string): E const result = emitter.addListener2(eventType, function () { listener.apply(thisArgs, arguments); }); - if(Array.isArray(disposables)) { + if (Array.isArray(disposables)) { disposables.push(result); } return result; @@ -312,11 +312,11 @@ export interface IChainableEvent { on(listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[]): IDisposable; } -export function mapEvent(event: Event, map: (i:I)=>O): Event { +export function mapEvent(event: Event, map: (i: I) => O): Event { return (listener, thisArgs = null, disposables?) => event(i => listener.call(thisArgs, map(i)), null, disposables); } -export function filterEvent(event: Event, filter: (e:T)=>boolean): Event { +export function filterEvent(event: Event, filter: (e: T) => boolean): Event { return (listener, thisArgs = null, disposables?) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables); } @@ -324,7 +324,7 @@ class ChainableEvent implements IChainableEvent { get event(): Event { return this._event; } - constructor(private _event: Event) {} + constructor(private _event: Event) { } map(fn) { return new ChainableEvent(mapEvent(this._event, fn)); diff --git a/src/vs/base/common/eventEmitter.ts b/src/vs/base/common/eventEmitter.ts index 027d3482257ab..229734e101420 100644 --- a/src/vs/base/common/eventEmitter.ts +++ b/src/vs/base/common/eventEmitter.ts @@ -5,55 +5,55 @@ 'use strict'; import Errors = require('vs/base/common/errors'); -import {IDisposable} from 'vs/base/common/lifecycle'; +import { IDisposable } from 'vs/base/common/lifecycle'; export class EmitterEvent { - private _type:string; - private _data:any; + private _type: string; + private _data: any; - constructor(eventType:string=null, data:any=null) { + constructor(eventType: string = null, data: any = null) { this._type = eventType; this._data = data; } - public getType():string { + public getType(): string { return this._type; } - public getData():any { + public getData(): any { return this._data; } } export interface ListenerCallback { - (value:any):void; + (value: any): void; } export interface BulkListenerCallback { - (value:EmitterEvent[]):void; + (value: EmitterEvent[]): void; } export interface IEventEmitter extends IDisposable { - addListener2(eventType:string, listener:ListenerCallback):IDisposable; - addOneTimeDisposableListener(eventType:string, listener:ListenerCallback):IDisposable; - addBulkListener2(listener:BulkListenerCallback):IDisposable; - addEmitter2(eventEmitter:IEventEmitter):IDisposable; + addListener2(eventType: string, listener: ListenerCallback): IDisposable; + addOneTimeDisposableListener(eventType: string, listener: ListenerCallback): IDisposable; + addBulkListener2(listener: BulkListenerCallback): IDisposable; + addEmitter2(eventEmitter: IEventEmitter): IDisposable; } export interface IListenersMap { - [key:string]:ListenerCallback[]; + [key: string]: ListenerCallback[]; } export class EventEmitter implements IEventEmitter { - protected _listeners:IListenersMap; - protected _bulkListeners:ListenerCallback[]; - private _collectedEvents:EmitterEvent[]; - private _deferredCnt:number; - private _allowedEventTypes:{[eventType:string]:boolean;}; + protected _listeners: IListenersMap; + protected _bulkListeners: ListenerCallback[]; + private _collectedEvents: EmitterEvent[]; + private _deferredCnt: number; + private _allowedEventTypes: { [eventType: string]: boolean; }; - constructor(allowedEventTypes:string[] = null) { + constructor(allowedEventTypes: string[] = null) { this._listeners = {}; this._bulkListeners = []; this._collectedEvents = []; @@ -76,7 +76,7 @@ export class EventEmitter implements IEventEmitter { this._allowedEventTypes = null; } - private addListener(eventType:string, listener:ListenerCallback):IDisposable { + private addListener(eventType: string, listener: ListenerCallback): IDisposable { if (eventType === '*') { throw new Error('Use addBulkListener(listener) to register your listener!'); } @@ -108,20 +108,20 @@ export class EventEmitter implements IEventEmitter { }; } - public addListener2(eventType:string, listener:ListenerCallback):IDisposable { + public addListener2(eventType: string, listener: ListenerCallback): IDisposable { return this.addListener(eventType, listener); } - public addOneTimeDisposableListener(eventType:string, listener:ListenerCallback):IDisposable { + public addOneTimeDisposableListener(eventType: string, listener: ListenerCallback): IDisposable { const disposable = this.addListener(eventType, value => { disposable.dispose(); listener(value); }); - + return disposable; } - protected addBulkListener(listener:BulkListenerCallback):IDisposable { + protected addBulkListener(listener: BulkListenerCallback): IDisposable { this._bulkListeners.push(listener); @@ -132,12 +132,12 @@ export class EventEmitter implements IEventEmitter { }; } - public addBulkListener2(listener:BulkListenerCallback):IDisposable { + public addBulkListener2(listener: BulkListenerCallback): IDisposable { return this.addBulkListener(listener); } - private addEmitter(eventEmitter:IEventEmitter):IDisposable { - return eventEmitter.addBulkListener2((events:EmitterEvent[]):void => { + private addEmitter(eventEmitter: IEventEmitter): IDisposable { + return eventEmitter.addBulkListener2((events: EmitterEvent[]): void => { var newEvents = events; if (this._deferredCnt === 0) { @@ -149,11 +149,11 @@ export class EventEmitter implements IEventEmitter { }); } - public addEmitter2(eventEmitter:IEventEmitter):IDisposable { + public addEmitter2(eventEmitter: IEventEmitter): IDisposable { return this.addEmitter(eventEmitter); } - private _removeListener(eventType:string, listener:ListenerCallback): void { + private _removeListener(eventType: string, listener: ListenerCallback): void { if (this._listeners.hasOwnProperty(eventType)) { var listeners = this._listeners[eventType]; for (var i = 0, len = listeners.length; i < len; i++) { @@ -166,7 +166,7 @@ export class EventEmitter implements IEventEmitter { } } - private _removeBulkListener(listener:BulkListenerCallback): void { + private _removeBulkListener(listener: BulkListenerCallback): void { for (var i = 0, len = this._bulkListeners.length; i < len; i++) { if (this._bulkListeners[i] === listener) { this._bulkListeners.splice(i, 1); @@ -175,7 +175,7 @@ export class EventEmitter implements IEventEmitter { } } - protected _emitToSpecificTypeListeners(eventType:string, data:any): void { + protected _emitToSpecificTypeListeners(eventType: string, data: any): void { if (this._listeners.hasOwnProperty(eventType)) { var listeners = this._listeners[eventType].slice(0); for (var i = 0, len = listeners.length; i < len; i++) { @@ -184,14 +184,14 @@ export class EventEmitter implements IEventEmitter { } } - protected _emitToBulkListeners(events:EmitterEvent[]): void { + protected _emitToBulkListeners(events: EmitterEvent[]): void { var bulkListeners = this._bulkListeners.slice(0); for (var i = 0, len = bulkListeners.length; i < len; i++) { safeInvoke1Arg(bulkListeners[i], events); } } - protected _emitEvents(events:EmitterEvent[]): void { + protected _emitEvents(events: EmitterEvent[]): void { if (this._bulkListeners.length > 0) { this._emitToBulkListeners(events); } @@ -202,7 +202,7 @@ export class EventEmitter implements IEventEmitter { } } - public emit(eventType:string, data:any={}):void { + public emit(eventType: string, data: any = {}): void { if (this._allowedEventTypes && !this._allowedEventTypes.hasOwnProperty(eventType)) { throw new Error('Cannot emit this event type because it wasn\'t white-listed!'); } @@ -220,7 +220,7 @@ export class EventEmitter implements IEventEmitter { } } - public deferredEmit(callback:()=>any):any { + public deferredEmit(callback: () => any): any { this._deferredCnt = this._deferredCnt + 1; var result: any = safeInvokeNoArg(callback); this._deferredCnt = this._deferredCnt - 1; @@ -259,12 +259,12 @@ export class OrderGuaranteeEventEmitter extends EventEmitter { private _emitQueue: EmitQueueElement[]; - constructor(allowedEventTypes:string[] = null) { + constructor(allowedEventTypes: string[] = null) { super(allowedEventTypes); this._emitQueue = []; } - protected _emitToSpecificTypeListeners(eventType:string, data:any): void { + protected _emitToSpecificTypeListeners(eventType: string, data: any): void { if (this._listeners.hasOwnProperty(eventType)) { let listeners = this._listeners[eventType]; for (let i = 0, len = listeners.length; i < len; i++) { @@ -273,14 +273,14 @@ export class OrderGuaranteeEventEmitter extends EventEmitter { } } - protected _emitToBulkListeners(events:EmitterEvent[]): void { + protected _emitToBulkListeners(events: EmitterEvent[]): void { let bulkListeners = this._bulkListeners; for (let i = 0, len = bulkListeners.length; i < len; i++) { this._emitQueue.push(new EmitQueueElement(bulkListeners[i], events)); } } - protected _emitEvents(events:EmitterEvent[]): void { + protected _emitEvents(events: EmitterEvent[]): void { super._emitEvents(events); while (this._emitQueue.length > 0) { @@ -290,18 +290,18 @@ export class OrderGuaranteeEventEmitter extends EventEmitter { } } -function safeInvokeNoArg(func:Function): any { +function safeInvokeNoArg(func: Function): any { try { return func(); - } catch(e) { + } catch (e) { Errors.onUnexpectedError(e); } } -function safeInvoke1Arg(func:Function, arg1:any): any { +function safeInvoke1Arg(func: Function, arg1: any): any { try { return func(arg1); - } catch(e) { + } catch (e) { Errors.onUnexpectedError(e); } } diff --git a/src/vs/base/common/filters.ts b/src/vs/base/common/filters.ts index 34ded84f8924f..9937770099828 100644 --- a/src/vs/base/common/filters.ts +++ b/src/vs/base/common/filters.ts @@ -5,8 +5,8 @@ 'use strict'; import strings = require('vs/base/common/strings'); -import {BoundedLinkedMap} from 'vs/base/common/map'; -import {CharCode} from 'vs/base/common/charCode'; +import { BoundedLinkedMap } from 'vs/base/common/map'; +import { CharCode } from 'vs/base/common/charCode'; export interface IFilter { // Returns null if word doesn't match. diff --git a/src/vs/base/common/flags.ts b/src/vs/base/common/flags.ts index acf51038d791b..16f8599ac78a8 100644 --- a/src/vs/base/common/flags.ts +++ b/src/vs/base/common/flags.ts @@ -5,7 +5,7 @@ 'use strict'; -import {globals} from 'vs/base/common/platform'; +import { globals } from 'vs/base/common/platform'; // Option for hosts to overwrite the worker script url (used in the standalone editor) export const getCrossOriginWorkerScriptUrl: (workerId: string, label: string) => string = environment('getWorkerUrl', null); diff --git a/src/vs/base/common/glob.ts b/src/vs/base/common/glob.ts index 61c28a4a77e8a..1e179d1f28278 100644 --- a/src/vs/base/common/glob.ts +++ b/src/vs/base/common/glob.ts @@ -7,8 +7,8 @@ import arrays = require('vs/base/common/arrays'); import strings = require('vs/base/common/strings'); import paths = require('vs/base/common/paths'); -import {BoundedLinkedMap} from 'vs/base/common/map'; -import {CharCode} from 'vs/base/common/charCode'; +import { BoundedLinkedMap } from 'vs/base/common/map'; +import { CharCode } from 'vs/base/common/charCode'; export interface IExpression { [pattern: string]: boolean | SiblingClause | any; @@ -240,11 +240,11 @@ interface ParsedExpressionPattern { const CACHE = new BoundedLinkedMap(10000); // bounded to 10000 elements -const FALSE = function() { +const FALSE = function () { return false; }; -const NULL = function(): string { +const NULL = function (): string { return null; }; @@ -316,7 +316,7 @@ function trivia2(base: string, originalPattern: string): ParsedStringPattern { } // repetition of common patterns (see above) {**/*.txt,**/*.png} -function trivia3 (pattern: string, options: IGlobOptions): ParsedStringPattern { +function trivia3(pattern: string, options: IGlobOptions): ParsedStringPattern { const parsedPatterns = aggregateBasenameMatches(pattern.slice(1, -1).split(',') .map(pattern => parsePattern(pattern, options)) .filter(pattern => pattern !== NULL), pattern); diff --git a/src/vs/base/common/graph.ts b/src/vs/base/common/graph.ts index 118fc2dfef9ae..fb34abb77d6bb 100644 --- a/src/vs/base/common/graph.ts +++ b/src/vs/base/common/graph.ts @@ -4,8 +4,8 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {isEmptyObject} from 'vs/base/common/types'; -import {forEach, contains, lookup} from 'vs/base/common/collections'; +import { isEmptyObject } from 'vs/base/common/types'; +import { forEach, contains, lookup } from 'vs/base/common/collections'; export interface Node { data: T; diff --git a/src/vs/base/common/hash.ts b/src/vs/base/common/hash.ts index 2377db5d7bb6b..e7149e43cd793 100644 --- a/src/vs/base/common/hash.ts +++ b/src/vs/base/common/hash.ts @@ -7,7 +7,7 @@ /** * Return a hash value for an object. */ -export function hash(obj: any, hashVal = 0) : number { +export function hash(obj: any, hashVal = 0): number { switch (typeof obj) { case 'object': if (obj === null) { @@ -29,11 +29,11 @@ export function hash(obj: any, hashVal = 0) : number { } } -function numberHash(val: number, initialHashVal: number) : number { +function numberHash(val: number, initialHashVal: number): number { return (((initialHashVal << 5) - initialHashVal) + val) | 0; // hashVal * 31 + ch, keep as int32 } -function booleanHash(b: boolean, initialHashVal: number) : number { +function booleanHash(b: boolean, initialHashVal: number): number { return numberHash(b ? 433 : 863, initialHashVal); } @@ -45,12 +45,12 @@ function stringHash(s: string, hashVal: number) { return hashVal; } -function arrayHash(arr: any[], initialHashVal: number) : number { +function arrayHash(arr: any[], initialHashVal: number): number { initialHashVal = numberHash(104579, initialHashVal); return arr.reduce((hashVal, item) => hash(item, hashVal), initialHashVal); } -function objectHash(obj: any, initialHashVal: number) : number { +function objectHash(obj: any, initialHashVal: number): number { initialHashVal = numberHash(181387, initialHashVal); return Object.keys(obj).sort().reduce((hashVal, key) => { hashVal = stringHash(key, hashVal); diff --git a/src/vs/base/common/htmlContent.ts b/src/vs/base/common/htmlContent.ts index 24d3d8dbbdefe..05ac455a51c69 100644 --- a/src/vs/base/common/htmlContent.ts +++ b/src/vs/base/common/htmlContent.ts @@ -17,7 +17,7 @@ export interface IHTMLContentElementCode { value: string; } -export function markedStringsEquals(a:MarkedString | MarkedString[], b:MarkedString |MarkedString[]): boolean { +export function markedStringsEquals(a: MarkedString | MarkedString[], b: MarkedString | MarkedString[]): boolean { if (!a && !b) { return true; } @@ -29,13 +29,13 @@ export function markedStringsEquals(a:MarkedString | MarkedString[], b:MarkedStr if (!Array.isArray(b)) { return false; } - return markedStringArrEquals( a, b); + return markedStringArrEquals(a, b); } - return markedStringEqual( a, b); + return markedStringEqual(a, b); } -function markedStringArrEquals(a:MarkedString[], b:MarkedString[]): boolean { +function markedStringArrEquals(a: MarkedString[], b: MarkedString[]): boolean { let aLen = a.length, bLen = b.length; @@ -51,7 +51,7 @@ function markedStringArrEquals(a:MarkedString[], b:MarkedString[]): boolean { return true; } -function markedStringEqual(a:MarkedString, b:MarkedString): boolean { +function markedStringEqual(a: MarkedString, b: MarkedString): boolean { if (!a && !b) { return true; } @@ -67,7 +67,7 @@ function markedStringEqual(a:MarkedString, b:MarkedString): boolean { ); } -export function textToMarkedString(text: string) : MarkedString { +export function textToMarkedString(text: string): MarkedString { return text.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash } @@ -76,7 +76,7 @@ export interface IHTMLContentElement { /** * supports **bold**, __italics__, and [[actions]] */ - formattedText?:string; + formattedText?: string; text?: string; className?: string; style?: string; @@ -89,7 +89,7 @@ export interface IHTMLContentElement { code?: IHTMLContentElementCode; } -function htmlContentElementCodeEqual(a:IHTMLContentElementCode, b:IHTMLContentElementCode): boolean { +function htmlContentElementCodeEqual(a: IHTMLContentElementCode, b: IHTMLContentElementCode): boolean { if (!a && !b) { return true; } @@ -102,7 +102,7 @@ function htmlContentElementCodeEqual(a:IHTMLContentElementCode, b:IHTMLContentEl ); } -function htmlContentElementEqual(a:IHTMLContentElement, b:IHTMLContentElement): boolean { +function htmlContentElementEqual(a: IHTMLContentElement, b: IHTMLContentElement): boolean { return ( a.formattedText === b.formattedText && a.text === b.text @@ -118,7 +118,7 @@ function htmlContentElementEqual(a:IHTMLContentElement, b:IHTMLContentElement): ); } -export function htmlContentElementArrEquals(a:IHTMLContentElement[], b:IHTMLContentElement[]): boolean { +export function htmlContentElementArrEquals(a: IHTMLContentElement[], b: IHTMLContentElement[]): boolean { if (!a && !b) { return true; } diff --git a/src/vs/base/common/http.ts b/src/vs/base/common/http.ts index b27569b585e40..59feccf6e04bf 100644 --- a/src/vs/base/common/http.ts +++ b/src/vs/base/common/http.ts @@ -7,26 +7,26 @@ import * as nls from 'vs/nls'; export interface IXHROptions { - type?:string; - url?:string; - user?:string; - password?:string; - responseType?:string; - headers?:any; + type?: string; + url?: string; + user?: string; + password?: string; + responseType?: string; + headers?: any; timeout?: number; followRedirects?: number; - data?:any; + data?: any; } export interface IXHRResponse { responseText: string; status: number; - readyState : number; - getResponseHeader: (header:string) => string; + readyState: number; + getResponseHeader: (header: string) => string; } -export function getErrorStatusDescription(status: number) : string { +export function getErrorStatusDescription(status: number): string { if (status < 400) { return void 0; } diff --git a/src/vs/base/common/idGenerator.ts b/src/vs/base/common/idGenerator.ts index 34ce058ff84bd..7287a3becd520 100644 --- a/src/vs/base/common/idGenerator.ts +++ b/src/vs/base/common/idGenerator.ts @@ -9,7 +9,7 @@ export class IdGenerator { private _prefix: string; private _lastId: number; - constructor(prefix:string) { + constructor(prefix: string) { this._prefix = prefix; this._lastId = 0; } diff --git a/src/vs/base/common/iterator.ts b/src/vs/base/common/iterator.ts index 9b0969d648e34..2bfcff36f6317 100644 --- a/src/vs/base/common/iterator.ts +++ b/src/vs/base/common/iterator.ts @@ -70,7 +70,7 @@ export class ArrayNavigator extends ArrayIterator implements INavigator export class MappedIterator implements IIterator { - constructor(protected iterator: IIterator, protected fn: (item:T)=>R) { + constructor(protected iterator: IIterator, protected fn: (item: T) => R) { // noop } @@ -87,7 +87,7 @@ export interface INavigator extends IIterator { export class MappedNavigator extends MappedIterator implements INavigator { - constructor(protected navigator: INavigator, fn: (item:T)=>R) { + constructor(protected navigator: INavigator, fn: (item: T) => R) { super(navigator, fn); } diff --git a/src/vs/base/common/json.ts b/src/vs/base/common/json.ts index fec94ad52b9ae..62ba0371429b3 100644 --- a/src/vs/base/common/json.ts +++ b/src/vs/base/common/json.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {localize} from 'vs/nls'; +import { localize } from 'vs/nls'; export enum ScanError { None, @@ -76,14 +76,14 @@ export interface JSONScanner { * Creates a JSON scanner on the given text. * If ignoreTrivia is set, whitespaces or comments are ignored. */ -export function createScanner(text:string, ignoreTrivia:boolean = false):JSONScanner { +export function createScanner(text: string, ignoreTrivia: boolean = false): JSONScanner { let pos = 0, len = text.length, - value:string = '', + value: string = '', tokenOffset = 0, - token:SyntaxKind = SyntaxKind.Unknown, - scanError:ScanError = ScanError.None; + token: SyntaxKind = SyntaxKind.Unknown, + scanError: ScanError = ScanError.None; function scanHexDigits(count: number, exact?: boolean): number { let digits = 0; @@ -234,14 +234,14 @@ export function createScanner(text:string, ignoreTrivia:boolean = false):JSONSca return result; } - function scanNext():SyntaxKind { + function scanNext(): SyntaxKind { value = ''; scanError = ScanError.None; tokenOffset = pos; - if(pos >= len) { + if (pos >= len) { // at the end tokenOffset = len; return token = SyntaxKind.EOF; @@ -270,7 +270,7 @@ export function createScanner(text:string, ignoreTrivia:boolean = false):JSONSca return token = SyntaxKind.LineBreakTrivia; } - switch(code) { + switch (code) { // tokens: []{}:, case CharacterCodes.openBrace: pos++; @@ -352,9 +352,9 @@ export function createScanner(text:string, ignoreTrivia:boolean = false):JSONSca if (pos === len || !isDigit(text.charCodeAt(pos))) { return token = SyntaxKind.Unknown; } - // found a minus, followed by a number so - // we fall through to proceed with scanning - // numbers + // found a minus, followed by a number so + // we fall through to proceed with scanning + // numbers case CharacterCodes._0: case CharacterCodes._1: case CharacterCodes._2: @@ -409,8 +409,8 @@ export function createScanner(text:string, ignoreTrivia:boolean = false):JSONSca } - function scanNextNonTrivia():SyntaxKind { - let result : SyntaxKind; + function scanNextNonTrivia(): SyntaxKind { + let result: SyntaxKind; do { result = scanNext(); } while (result >= SyntaxKind.LineCommentTrivia && result <= SyntaxKind.Trivia); @@ -586,13 +586,13 @@ const enum CharacterCodes { * them. Optionally replaces every none-newline character * of comments with a replaceCharacter */ -export function stripComments(text:string, replaceCh?:string):string { +export function stripComments(text: string, replaceCh?: string): string { let _scanner = createScanner(text), parts: string[] = [], - kind:SyntaxKind, + kind: SyntaxKind, offset = 0, - pos:number; + pos: number; do { pos = _scanner.getPosition(); @@ -601,16 +601,16 @@ export function stripComments(text:string, replaceCh?:string):string { case SyntaxKind.LineCommentTrivia: case SyntaxKind.BlockCommentTrivia: case SyntaxKind.EOF: - if(offset !== pos) { + if (offset !== pos) { parts.push(text.substring(offset, pos)); } - if(replaceCh !== void 0) { + if (replaceCh !== void 0) { parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh)); } offset = _scanner.getPosition(); break; } - } while(kind !== SyntaxKind.EOF); + } while (kind !== SyntaxKind.EOF); return parts.join(''); } @@ -631,7 +631,7 @@ export enum ParseErrorCode { EndOfFileExpected } -export function getParseErrorMessage(errorCode: ParseErrorCode) : string { +export function getParseErrorMessage(errorCode: ParseErrorCode): string { switch (errorCode) { case ParseErrorCode.InvalidSymbol: return localize('error.invalidSymbol', 'Invalid symbol'); case ParseErrorCode.InvalidNumberFormat: return localize('error.invalidNumberFormat', 'Invalid number format'); @@ -649,7 +649,7 @@ export function getParseErrorMessage(errorCode: ParseErrorCode) : string { export type NodeType = 'object' | 'array' | 'property' | 'string' | 'number' | 'boolean' | 'null'; -function getLiteralNodeType(value: any) : NodeType { +function getLiteralNodeType(value: any): NodeType { switch (typeof value) { case 'boolean': return 'boolean'; case 'number': return 'number'; @@ -697,11 +697,11 @@ export interface Location { /** * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. */ -export function getLocation(text:string, position: number) : Location { +export function getLocation(text: string, position: number): Location { let segments: any[] = []; // strings or numbers let earlyReturnException = new Object(); - let previousNode : Node = void 0; - const previousNodeInst : Node = { + let previousNode: Node = void 0; + const previousNodeInst: Node = { value: void 0, offset: void 0, length: void 0, @@ -823,20 +823,20 @@ export interface ParseOptions { * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. * 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 currentParent : any = []; - let previousParents : any[] = []; +export function parse(text: string, errors: ParseError[] = [], options?: ParseOptions): any { + let currentProperty: string = null; + let currentParent: any = []; + let previousParents: any[] = []; function onValue(value: any) { if (Array.isArray(currentParent)) { - ( currentParent).push(value); + (currentParent).push(value); } else if (currentProperty) { currentParent[currentProperty] = value; } } - let visitor : JSONVisitor = { + let visitor: JSONVisitor = { onObjectBegin: () => { let object = {}; onValue(object); @@ -861,8 +861,8 @@ export function parse(text:string, errors: ParseError[] = [], options?: ParseOpt currentParent = previousParents.pop(); }, onLiteralValue: onValue, - onError:(error:ParseErrorCode) => { - errors.push({error: error}); + onError: (error: ParseErrorCode) => { + errors.push({ error: error }); } }; visit(text, visitor, options); @@ -873,29 +873,29 @@ export function parse(text:string, errors: ParseError[] = [], options?: ParseOpt /** * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. */ -export function parseTree(text:string, errors: ParseError[] = [], options?: ParseOptions) : Node { - let currentParent : Node = { type: 'array', offset: -1, length: -1, children: [] }; // artificial root +export function parseTree(text: string, errors: ParseError[] = [], options?: ParseOptions): Node { + let currentParent: Node = { type: 'array', offset: -1, length: -1, children: [] }; // artificial root - function ensurePropertyComplete(endOffset:number) { + function ensurePropertyComplete(endOffset: number) { if (currentParent.type === 'property') { currentParent.length = endOffset - currentParent.offset; currentParent = currentParent.parent; } } - function onValue(valueNode: Node) : Node { + function onValue(valueNode: Node): Node { currentParent.children.push(valueNode); ensurePropertyComplete(valueNode.offset + valueNode.length); return valueNode; } - let visitor : JSONVisitor = { + let visitor: JSONVisitor = { onObjectBegin: (offset: number) => { currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] }); }, onObjectProperty: (name: string, offset: number, length: number) => { currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] }); - currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent}); + currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent }); }, onObjectEnd: (offset: number, length: number) => { ensurePropertyComplete(offset); @@ -921,8 +921,8 @@ export function parseTree(text:string, errors: ParseError[] = [], options?: Pars } } }, - onError:(error:ParseErrorCode) => { - errors.push({error: error}); + onError: (error: ParseErrorCode) => { + errors.push({ error: error }); } }; visit(text, visitor, options); @@ -934,7 +934,7 @@ export function parseTree(text:string, errors: ParseError[] = [], options?: Pars return result; } -export function findNodeAtLocation(root: Node, path: JSONPath) : Node { +export function findNodeAtLocation(root: Node, path: JSONPath): Node { if (!root) { return void 0; } @@ -956,7 +956,7 @@ export function findNodeAtLocation(root: Node, path: JSONPath) : Node { return void 0; } } else { - let index = segment; + let index = segment; if (node.type !== 'array' || index < 0 || index >= node.children.length) { return void 0; } @@ -966,7 +966,7 @@ export function findNodeAtLocation(root: Node, path: JSONPath) : Node { return node; } -export function getNodeValue(node: Node) : any { +export function getNodeValue(node: Node): any { if (node.type === 'array') { return node.children.map(getNodeValue); } else if (node.type === 'object') { @@ -983,14 +983,14 @@ export function getNodeValue(node: Node) : any { /** * Parses the given text and invokes the visitor functions for each object, array and literal reached. */ -export function visit(text:string, visitor: JSONVisitor, options?: ParseOptions) : any { +export function visit(text: string, visitor: JSONVisitor, options?: ParseOptions): any { let _scanner = createScanner(text, false); - function toNoArgVisit(visitFunction: (offset: number, length: number) => void) : () => void { + function toNoArgVisit(visitFunction: (offset: number, length: number) => void): () => void { return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength()) : () => true; } - function toOneArgVisit(visitFunction: (arg: T, offset: number, length: number) => void) : (arg: T) => void { + function toOneArgVisit(visitFunction: (arg: T, offset: number, length: number) => void): (arg: T) => void { return visitFunction ? (arg: T) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength()) : () => true; } @@ -1004,7 +1004,7 @@ export function visit(text:string, visitor: JSONVisitor, options?: ParseOptions) onError = toOneArgVisit(visitor.onError); let disallowComments = options && options.disallowComments; - function scanNext() : SyntaxKind { + function scanNext(): SyntaxKind { while (true) { let token = _scanner.scan(); switch (token) { @@ -1026,7 +1026,7 @@ export function visit(text:string, visitor: JSONVisitor, options?: ParseOptions) } } - function handleError(error:ParseErrorCode, skipUntilAfter: SyntaxKind[] = [], skipUntil: SyntaxKind[] = []) : void { + function handleError(error: ParseErrorCode, skipUntilAfter: SyntaxKind[] = [], skipUntil: SyntaxKind[] = []): void { onError(error); if (skipUntilAfter.length + skipUntil.length > 0) { let token = _scanner.getToken(); @@ -1042,7 +1042,7 @@ export function visit(text:string, visitor: JSONVisitor, options?: ParseOptions) } } - function parseString(isValue: boolean) : boolean { + function parseString(isValue: boolean): boolean { if (_scanner.getToken() !== SyntaxKind.StringLiteral) { return false; } @@ -1056,7 +1056,7 @@ export function visit(text:string, visitor: JSONVisitor, options?: ParseOptions) return true; } - function parseLiteral() : boolean { + function parseLiteral(): boolean { switch (_scanner.getToken()) { case SyntaxKind.NumericLiteral: let value = 0; @@ -1087,9 +1087,9 @@ export function visit(text:string, visitor: JSONVisitor, options?: ParseOptions) return true; } - function parseProperty() : boolean { + function parseProperty(): boolean { if (!parseString(false)) { - handleError(ParseErrorCode.PropertyNameExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken] ); + handleError(ParseErrorCode.PropertyNameExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]); return false; } if (_scanner.getToken() === SyntaxKind.ColonToken) { @@ -1097,15 +1097,15 @@ export function visit(text:string, visitor: JSONVisitor, options?: ParseOptions) scanNext(); // consume colon if (!parseValue()) { - handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken] ); + handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]); } } else { - handleError(ParseErrorCode.ColonExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken] ); + handleError(ParseErrorCode.ColonExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]); } return true; } - function parseObject() : boolean { + function parseObject(): boolean { if (_scanner.getToken() !== SyntaxKind.OpenBraceToken) { return false; } @@ -1116,15 +1116,15 @@ export function visit(text:string, visitor: JSONVisitor, options?: ParseOptions) while (_scanner.getToken() !== SyntaxKind.CloseBraceToken && _scanner.getToken() !== SyntaxKind.EOF) { if (_scanner.getToken() === SyntaxKind.CommaToken) { if (!needsComma) { - handleError(ParseErrorCode.ValueExpected, [], [] ); + handleError(ParseErrorCode.ValueExpected, [], []); } onSeparator(','); scanNext(); // consume comma } else if (needsComma) { - handleError(ParseErrorCode.CommaExpected, [], [] ); + handleError(ParseErrorCode.CommaExpected, [], []); } if (!parseProperty()) { - handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken] ); + handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]); } needsComma = true; } @@ -1137,7 +1137,7 @@ export function visit(text:string, visitor: JSONVisitor, options?: ParseOptions) return true; } - function parseArray() : boolean { + function parseArray(): boolean { if (_scanner.getToken() !== SyntaxKind.OpenBracketToken) { return false; } @@ -1148,15 +1148,15 @@ export function visit(text:string, visitor: JSONVisitor, options?: ParseOptions) while (_scanner.getToken() !== SyntaxKind.CloseBracketToken && _scanner.getToken() !== SyntaxKind.EOF) { if (_scanner.getToken() === SyntaxKind.CommaToken) { if (!needsComma) { - handleError(ParseErrorCode.ValueExpected, [], [] ); + handleError(ParseErrorCode.ValueExpected, [], []); } onSeparator(','); scanNext(); // consume comma } else if (needsComma) { - handleError(ParseErrorCode.CommaExpected, [], [] ); + handleError(ParseErrorCode.CommaExpected, [], []); } if (!parseValue()) { - handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBracketToken, SyntaxKind.CommaToken] ); + handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBracketToken, SyntaxKind.CommaToken]); } needsComma = true; } @@ -1169,7 +1169,7 @@ export function visit(text:string, visitor: JSONVisitor, options?: ParseOptions) return true; } - function parseValue() : boolean { + function parseValue(): boolean { return parseArray() || parseObject() || parseString(true) || parseLiteral(); } @@ -1191,40 +1191,40 @@ export interface JSONVisitor { /** * Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace. */ - onObjectBegin?: (offset:number, length:number) => void; + onObjectBegin?: (offset: number, length: number) => void; /** * Invoked when a property is encountered. The offset and length represent the location of the property name. */ - onObjectProperty?: (property: string, offset:number, length:number) => void; + onObjectProperty?: (property: string, offset: number, length: number) => void; /** * Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace. */ - onObjectEnd?: (offset:number, length:number) => void; + onObjectEnd?: (offset: number, length: number) => void; /** * Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket. */ - onArrayBegin?: (offset:number, length:number) => void; + onArrayBegin?: (offset: number, length: number) => void; /** * Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket. */ - onArrayEnd?: (offset:number, length:number) => void; + onArrayEnd?: (offset: number, length: number) => void; /** * Invoked when a literal value is encountered. The offset and length represent the location of the literal value. */ - onLiteralValue?: (value: any, offset:number, length:number) => void; + onLiteralValue?: (value: any, offset: number, length: number) => void; /** * Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator. */ - onSeparator?: (charcter: string, offset:number, length:number) => void; + onSeparator?: (charcter: string, offset: number, length: number) => void; /** * Invoked on an error. */ - onError?: (error: ParseErrorCode, offset:number, length:number) => void; + onError?: (error: ParseErrorCode, offset: number, length: number) => void; } diff --git a/src/vs/base/common/jsonEdit.ts b/src/vs/base/common/jsonEdit.ts index b02004fd88dea..8b254f7fd0450 100644 --- a/src/vs/base/common/jsonEdit.ts +++ b/src/vs/base/common/jsonEdit.ts @@ -7,11 +7,11 @@ import { ParseError, Node, parseTree, findNodeAtLocation, JSONPath, Segment } from 'vs/base/common/json'; import { Edit, FormattingOptions, format, applyEdit } from 'vs/base/common/jsonFormatter'; -export function removeProperty(text: string, path: JSONPath, formattingOptions: FormattingOptions) : Edit[] { +export function removeProperty(text: string, path: JSONPath, formattingOptions: FormattingOptions): Edit[] { return setProperty(text, path, void 0, formattingOptions); } -export function setProperty(text: string, path: JSONPath, value: any, formattingOptions: FormattingOptions, getInsertionIndex?: (properties: string[]) => number) : Edit[] { +export function setProperty(text: string, path: JSONPath, value: any, formattingOptions: FormattingOptions, getInsertionIndex?: (properties: string[]) => number): Edit[] { let errors: ParseError[] = []; let root = parseTree(text, errors); let parent: Node = void 0; @@ -24,7 +24,7 @@ export function setProperty(text: string, path: JSONPath, value: any, formatting if (typeof lastSegment === 'string') { value = { [lastSegment]: value }; } else { - value = [ value ]; + value = [value]; } } else { break; @@ -38,11 +38,11 @@ export function setProperty(text: string, path: JSONPath, value: any, formatting } return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, formattingOptions); } else if (parent.type === 'object' && typeof lastSegment === 'string') { - let existing = findNodeAtLocation(parent, [ lastSegment ]); + let existing = findNodeAtLocation(parent, [lastSegment]); if (existing !== void 0) { if (value === void 0) { // delete let propertyIndex = parent.children.indexOf(existing.parent); - let removeBegin : number; + let removeBegin: number; let removeEnd = existing.parent.offset + existing.parent.length; if (propertyIndex > 0) { // remove the comma of the previous node @@ -70,22 +70,22 @@ export function setProperty(text: string, path: JSONPath, value: any, formatting let edit: Edit; if (index > 0) { let previous = parent.children[index - 1]; - edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty}; + edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; } else if (parent.children.length === 0) { - edit = { offset: parent.offset + 1, length: 0, content: newProperty}; + edit = { offset: parent.offset + 1, length: 0, content: newProperty }; } else { - edit = { offset: parent.offset + 1, length: 0, content: newProperty + ','}; + edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' }; } return withFormatting(text, edit, formattingOptions); } } else if (parent.type === 'array' && typeof lastSegment === 'number') { throw new Error('Array modification not supported yet'); } else { - throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property' } to parent of type ${parent.type}`); + throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`); } } -function withFormatting(text:string, edit: Edit, formattingOptions: FormattingOptions) : Edit[] { +function withFormatting(text: string, edit: Edit, formattingOptions: FormattingOptions): Edit[] { // apply the edit let newText = applyEdit(text, edit); diff --git a/src/vs/base/common/jsonFormatter.ts b/src/vs/base/common/jsonFormatter.ts index 686ecd48b0c0e..f41a0d71216ac 100644 --- a/src/vs/base/common/jsonFormatter.ts +++ b/src/vs/base/common/jsonFormatter.ts @@ -27,18 +27,18 @@ export interface Edit { content: string; } -export function applyEdit(text: string, edit: Edit) : string { +export function applyEdit(text: string, edit: Edit): string { return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length); } -export function applyEdits(text: string, edits: Edit[]) : string { +export function applyEdits(text: string, edits: Edit[]): string { for (let i = edits.length - 1; i >= 0; i--) { text = applyEdit(text, edits[i]); } return text; } -export function format(documentText: string, range: { offset: number, length: number}, options: FormattingOptions): Edit[] { +export function format(documentText: string, range: { offset: number, length: number }, options: FormattingOptions): Edit[] { let initialIndentLevel: number; let value: string; let rangeStart: number; @@ -198,7 +198,7 @@ function getEOL(options: FormattingOptions, text: string): string { for (let i = 0; i < text.length; i++) { let ch = text.charAt(i); if (ch === '\r') { - if (i + 1 < text.length && text.charAt(i+1) === '\n') { + if (i + 1 < text.length && text.charAt(i + 1) === '\n') { return '\r\n'; } return '\r'; diff --git a/src/vs/base/common/jsonSchema.ts b/src/vs/base/common/jsonSchema.ts index 9b892d1cad897..ffde9dd6d2dee 100644 --- a/src/vs/base/common/jsonSchema.ts +++ b/src/vs/base/common/jsonSchema.ts @@ -45,5 +45,5 @@ export interface IJSONSchema { } export interface IJSONSchemaMap { - [name: string]:IJSONSchema; + [name: string]: IJSONSchema; } diff --git a/src/vs/base/common/keyCodes.ts b/src/vs/base/common/keyCodes.ts index 4581f40960f5b..54c502822b856 100644 --- a/src/vs/base/common/keyCodes.ts +++ b/src/vs/base/common/keyCodes.ts @@ -191,7 +191,7 @@ export const enum KeyCode { } export interface IReverseMap { - [str:string]:KeyCode; + [str: string]: KeyCode; } export class Mapping { @@ -204,11 +204,11 @@ export class Mapping { this._toKeyCode = toKeyCode; } - fromKeyCode(keyCode:KeyCode): string { + fromKeyCode(keyCode: KeyCode): string { return this._fromKeyCode[keyCode]; } - toKeyCode(str:string): KeyCode { + toKeyCode(str: string): KeyCode { if (this._toKeyCode.hasOwnProperty(str)) { return this._toKeyCode[str]; } @@ -217,7 +217,7 @@ export class Mapping { } -function createMapping(fill1:(map:string[])=>void, fill2:(reverseMap:IReverseMap)=>void): Mapping { +function createMapping(fill1: (map: string[]) => void, fill2: (reverseMap: IReverseMap) => void): Mapping { let MAP: string[] = []; fill1(MAP); @@ -242,28 +242,28 @@ function createMapping(fill1:(map:string[])=>void, fill2:(reverseMap:IReverseMap } let STRING = createMapping((TO_STRING_MAP) => { - TO_STRING_MAP[KeyCode.Unknown] = 'unknown'; - - TO_STRING_MAP[KeyCode.Backspace] = 'Backspace'; - TO_STRING_MAP[KeyCode.Tab] = 'Tab'; - TO_STRING_MAP[KeyCode.Enter] = 'Enter'; - TO_STRING_MAP[KeyCode.Shift] = 'Shift'; - TO_STRING_MAP[KeyCode.Ctrl] = 'Ctrl'; - TO_STRING_MAP[KeyCode.Alt] = 'Alt'; - TO_STRING_MAP[KeyCode.PauseBreak] = 'PauseBreak'; - TO_STRING_MAP[KeyCode.CapsLock] = 'CapsLock'; - TO_STRING_MAP[KeyCode.Escape] = 'Escape'; - TO_STRING_MAP[KeyCode.Space] = 'Space'; - TO_STRING_MAP[KeyCode.PageUp] = 'PageUp'; - TO_STRING_MAP[KeyCode.PageDown] = 'PageDown'; - TO_STRING_MAP[KeyCode.End] = 'End'; - TO_STRING_MAP[KeyCode.Home] = 'Home'; - TO_STRING_MAP[KeyCode.LeftArrow] = 'LeftArrow'; - TO_STRING_MAP[KeyCode.UpArrow] = 'UpArrow'; - TO_STRING_MAP[KeyCode.RightArrow] = 'RightArrow'; - TO_STRING_MAP[KeyCode.DownArrow] = 'DownArrow'; - TO_STRING_MAP[KeyCode.Insert] = 'Insert'; - TO_STRING_MAP[KeyCode.Delete] = 'Delete'; + TO_STRING_MAP[KeyCode.Unknown] = 'unknown'; + + TO_STRING_MAP[KeyCode.Backspace] = 'Backspace'; + TO_STRING_MAP[KeyCode.Tab] = 'Tab'; + TO_STRING_MAP[KeyCode.Enter] = 'Enter'; + TO_STRING_MAP[KeyCode.Shift] = 'Shift'; + TO_STRING_MAP[KeyCode.Ctrl] = 'Ctrl'; + TO_STRING_MAP[KeyCode.Alt] = 'Alt'; + TO_STRING_MAP[KeyCode.PauseBreak] = 'PauseBreak'; + TO_STRING_MAP[KeyCode.CapsLock] = 'CapsLock'; + TO_STRING_MAP[KeyCode.Escape] = 'Escape'; + TO_STRING_MAP[KeyCode.Space] = 'Space'; + TO_STRING_MAP[KeyCode.PageUp] = 'PageUp'; + TO_STRING_MAP[KeyCode.PageDown] = 'PageDown'; + TO_STRING_MAP[KeyCode.End] = 'End'; + TO_STRING_MAP[KeyCode.Home] = 'Home'; + TO_STRING_MAP[KeyCode.LeftArrow] = 'LeftArrow'; + TO_STRING_MAP[KeyCode.UpArrow] = 'UpArrow'; + TO_STRING_MAP[KeyCode.RightArrow] = 'RightArrow'; + TO_STRING_MAP[KeyCode.DownArrow] = 'DownArrow'; + TO_STRING_MAP[KeyCode.Insert] = 'Insert'; + TO_STRING_MAP[KeyCode.Delete] = 'Delete'; TO_STRING_MAP[KeyCode.KEY_0] = '0'; TO_STRING_MAP[KeyCode.KEY_1] = '1'; @@ -326,22 +326,22 @@ let STRING = createMapping((TO_STRING_MAP) => { TO_STRING_MAP[KeyCode.F19] = 'F19'; - TO_STRING_MAP[KeyCode.NumLock] = 'NumLock'; - TO_STRING_MAP[KeyCode.ScrollLock] = 'ScrollLock'; + TO_STRING_MAP[KeyCode.NumLock] = 'NumLock'; + TO_STRING_MAP[KeyCode.ScrollLock] = 'ScrollLock'; - TO_STRING_MAP[KeyCode.US_SEMICOLON] = ';'; - TO_STRING_MAP[KeyCode.US_EQUAL] = '='; - TO_STRING_MAP[KeyCode.US_COMMA] = ','; - TO_STRING_MAP[KeyCode.US_MINUS] = '-'; - TO_STRING_MAP[KeyCode.US_DOT] = '.'; - TO_STRING_MAP[KeyCode.US_SLASH] = '/'; - TO_STRING_MAP[KeyCode.US_BACKTICK] = '`'; - TO_STRING_MAP[KeyCode.US_OPEN_SQUARE_BRACKET] = '['; - TO_STRING_MAP[KeyCode.US_BACKSLASH] = '\\'; - TO_STRING_MAP[KeyCode.US_CLOSE_SQUARE_BRACKET] = ']'; - TO_STRING_MAP[KeyCode.US_QUOTE] = '\''; - TO_STRING_MAP[KeyCode.OEM_8] = 'OEM_8'; - TO_STRING_MAP[KeyCode.OEM_102] = 'OEM_102'; + TO_STRING_MAP[KeyCode.US_SEMICOLON] = ';'; + TO_STRING_MAP[KeyCode.US_EQUAL] = '='; + TO_STRING_MAP[KeyCode.US_COMMA] = ','; + TO_STRING_MAP[KeyCode.US_MINUS] = '-'; + TO_STRING_MAP[KeyCode.US_DOT] = '.'; + TO_STRING_MAP[KeyCode.US_SLASH] = '/'; + TO_STRING_MAP[KeyCode.US_BACKTICK] = '`'; + TO_STRING_MAP[KeyCode.US_OPEN_SQUARE_BRACKET] = '['; + TO_STRING_MAP[KeyCode.US_BACKSLASH] = '\\'; + TO_STRING_MAP[KeyCode.US_CLOSE_SQUARE_BRACKET] = ']'; + TO_STRING_MAP[KeyCode.US_QUOTE] = '\''; + TO_STRING_MAP[KeyCode.OEM_8] = 'OEM_8'; + TO_STRING_MAP[KeyCode.OEM_102] = 'OEM_102'; TO_STRING_MAP[KeyCode.NUMPAD_0] = 'NumPad0'; TO_STRING_MAP[KeyCode.NUMPAD_1] = 'NumPad1'; @@ -396,10 +396,10 @@ export let USER_SETTINGS = createMapping((TO_USER_SETTINGS_MAP) => { }); export namespace KeyCodeUtils { - export function toString(key:KeyCode): string { + export function toString(key: KeyCode): string { return STRING.fromKeyCode(key); } - export function fromString(key:string): KeyCode { + export function fromString(key: string): KeyCode { return STRING.toKeyCode(key); } } @@ -425,41 +425,41 @@ export const enum KeyMod { WinCtrl = 1 << 12, } -export function KeyChord(firstPart:number, secondPart:number): number { +export function KeyChord(firstPart: number, secondPart: number): number { return firstPart | ((secondPart & 0x0000ffff) << 16); } export class BinaryKeybindings { - public static extractFirstPart(keybinding:number): number { + public static extractFirstPart(keybinding: number): number { return keybinding & 0x0000ffff; } - public static extractChordPart(keybinding:number): number { + public static extractChordPart(keybinding: number): number { return (keybinding >> 16) & 0x0000ffff; } - public static hasChord(keybinding:number): boolean { + public static hasChord(keybinding: number): boolean { return (this.extractChordPart(keybinding) !== 0); } - public static hasCtrlCmd(keybinding:number): boolean { + public static hasCtrlCmd(keybinding: number): boolean { return (keybinding & BinaryKeybindingsMask.CtrlCmd ? true : false); } - public static hasShift(keybinding:number): boolean { + public static hasShift(keybinding: number): boolean { return (keybinding & BinaryKeybindingsMask.Shift ? true : false); } - public static hasAlt(keybinding:number): boolean { + public static hasAlt(keybinding: number): boolean { return (keybinding & BinaryKeybindingsMask.Alt ? true : false); } - public static hasWinCtrl(keybinding:number): boolean { + public static hasWinCtrl(keybinding: number): boolean { return (keybinding & BinaryKeybindingsMask.WinCtrl ? true : false); } - public static extractKeyCode(keybinding:number): KeyCode { + public static extractKeyCode(keybinding: number): KeyCode { return (keybinding & BinaryKeybindingsMask.KeyCode); } } diff --git a/src/vs/base/common/keybinding.ts b/src/vs/base/common/keybinding.ts index c891250abd37b..0a8478e992348 100644 --- a/src/vs/base/common/keybinding.ts +++ b/src/vs/base/common/keybinding.ts @@ -7,8 +7,8 @@ import * as nls from 'vs/nls'; import * as defaultPlatform from 'vs/base/common/platform'; -import {IHTMLContentElement} from 'vs/base/common/htmlContent'; -import {KeyCode, KeyMod, KeyChord, KeyCodeUtils, BinaryKeybindings, USER_SETTINGS} from 'vs/base/common/keyCodes'; +import { IHTMLContentElement } from 'vs/base/common/htmlContent'; +import { KeyCode, KeyMod, KeyChord, KeyCodeUtils, BinaryKeybindings, USER_SETTINGS } from 'vs/base/common/keyCodes'; export interface ISimplifiedPlatform { isMacintosh: boolean; @@ -20,35 +20,35 @@ export class Keybinding { /** * Format the binding to a format appropiate for rendering in the UI */ - private static _toUSLabel(value:number, Platform:ISimplifiedPlatform): string { + private static _toUSLabel(value: number, Platform: ISimplifiedPlatform): string { return _asString(value, (Platform.isMacintosh ? MacUIKeyLabelProvider.INSTANCE : ClassicUIKeyLabelProvider.INSTANCE), Platform); } /** * Format the binding to a format appropiate for placing in an aria-label. */ - private static _toUSAriaLabel(value:number, Platform:ISimplifiedPlatform): string { + private static _toUSAriaLabel(value: number, Platform: ISimplifiedPlatform): string { return _asString(value, AriaKeyLabelProvider.INSTANCE, Platform); } /** * Format the binding to a format appropiate for rendering in the UI */ - private static _toUSHTMLLabel(value:number, Platform:ISimplifiedPlatform): IHTMLContentElement[] { + private static _toUSHTMLLabel(value: number, Platform: ISimplifiedPlatform): IHTMLContentElement[] { return _asHTML(value, (Platform.isMacintosh ? MacUIKeyLabelProvider.INSTANCE : ClassicUIKeyLabelProvider.INSTANCE), Platform); } /** * Format the binding to a format appropiate for rendering in the UI */ - private static _toCustomLabel(value:number, labelProvider:IKeyBindingLabelProvider, Platform:ISimplifiedPlatform): string { + private static _toCustomLabel(value: number, labelProvider: IKeyBindingLabelProvider, Platform: ISimplifiedPlatform): string { return _asString(value, labelProvider, Platform); } /** * Format the binding to a format appropiate for rendering in the UI */ - private static _toCustomHTMLLabel(value:number, labelProvider:IKeyBindingLabelProvider, Platform:ISimplifiedPlatform): IHTMLContentElement[] { + private static _toCustomHTMLLabel(value: number, labelProvider: IKeyBindingLabelProvider, Platform: ISimplifiedPlatform): IHTMLContentElement[] { return _asHTML(value, labelProvider, Platform); } @@ -56,7 +56,7 @@ export class Keybinding { * This prints the binding in a format suitable for electron's accelerators. * See https://github.com/electron/electron/blob/master/docs/api/accelerator.md */ - private static _toElectronAccelerator(value:number, Platform:ISimplifiedPlatform): string { + private static _toElectronAccelerator(value: number, Platform: ISimplifiedPlatform): string { if (BinaryKeybindings.hasChord(value)) { // Electron cannot handle chords return null; @@ -75,7 +75,7 @@ export class Keybinding { let mod = '((ctrl|shift|alt|cmd|win|meta)\\+)*'; let keybinding = '(' + mod + key + ')'; - this._cachedKeybindingRegex = '"\\s*(' + keybinding + '(\\s+' + keybinding +')?' + ')\\s*"'; + this._cachedKeybindingRegex = '"\\s*(' + keybinding + '(\\s+' + keybinding + ')?' + ')\\s*"'; } return this._cachedKeybindingRegex; } @@ -83,7 +83,7 @@ export class Keybinding { /** * Format the binding to a format appropiate for the user settings file. */ - public static toUserSettingsLabel(value:number, Platform:ISimplifiedPlatform = defaultPlatform): string { + public static toUserSettingsLabel(value: number, Platform: ISimplifiedPlatform = defaultPlatform): string { let result = _asString(value, UserSettingsKeyLabelProvider.INSTANCE, Platform); result = result.toLowerCase(); @@ -106,7 +106,7 @@ export class Keybinding { shift = false, alt = false, winCtrl = false, - key:string = ''; + key: string = ''; while (/^(ctrl|shift|alt|meta|win|cmd)(\+|\-)/.test(input)) { if (/^ctrl(\+|\-)/.test(input)) { @@ -180,9 +180,9 @@ export class Keybinding { return KeyChord(result, chord); } - public value:number; + public value: number; - constructor(keybinding:number) { + constructor(keybinding: number) { this.value = keybinding; } @@ -209,35 +209,35 @@ export class Keybinding { /** * Format the binding to a format appropiate for rendering in the UI */ - public _toUSLabel(Platform:ISimplifiedPlatform = defaultPlatform): string { + public _toUSLabel(Platform: ISimplifiedPlatform = defaultPlatform): string { return Keybinding._toUSLabel(this.value, Platform); } /** * Format the binding to a format appropiate for placing in an aria-label. */ - public _toUSAriaLabel(Platform:ISimplifiedPlatform = defaultPlatform): string { + public _toUSAriaLabel(Platform: ISimplifiedPlatform = defaultPlatform): string { return Keybinding._toUSAriaLabel(this.value, Platform); } /** * Format the binding to a format appropiate for rendering in the UI */ - public _toUSHTMLLabel(Platform:ISimplifiedPlatform = defaultPlatform): IHTMLContentElement[] { + public _toUSHTMLLabel(Platform: ISimplifiedPlatform = defaultPlatform): IHTMLContentElement[] { return Keybinding._toUSHTMLLabel(this.value, Platform); } /** * Format the binding to a format appropiate for rendering in the UI */ - public toCustomLabel(labelProvider:IKeyBindingLabelProvider, Platform:ISimplifiedPlatform = defaultPlatform): string { + public toCustomLabel(labelProvider: IKeyBindingLabelProvider, Platform: ISimplifiedPlatform = defaultPlatform): string { return Keybinding._toCustomLabel(this.value, labelProvider, Platform); } /** * Format the binding to a format appropiate for rendering in the UI */ - public toCustomHTMLLabel(labelProvider:IKeyBindingLabelProvider, Platform:ISimplifiedPlatform = defaultPlatform): IHTMLContentElement[] { + public toCustomHTMLLabel(labelProvider: IKeyBindingLabelProvider, Platform: ISimplifiedPlatform = defaultPlatform): IHTMLContentElement[] { return Keybinding._toCustomHTMLLabel(this.value, labelProvider, Platform); } @@ -245,27 +245,27 @@ export class Keybinding { * This prints the binding in a format suitable for electron's accelerators. * See https://github.com/electron/electron/blob/master/docs/api/accelerator.md */ - public _toElectronAccelerator(Platform:ISimplifiedPlatform = defaultPlatform): string { + public _toElectronAccelerator(Platform: ISimplifiedPlatform = defaultPlatform): string { return Keybinding._toElectronAccelerator(this.value, Platform); } /** * Format the binding to a format appropiate for the user settings file. */ - public toUserSettingsLabel(Platform:ISimplifiedPlatform = defaultPlatform): string { + public toUserSettingsLabel(Platform: ISimplifiedPlatform = defaultPlatform): string { return Keybinding.toUserSettingsLabel(this.value, Platform); } } export interface IKeyBindingLabelProvider { - ctrlKeyLabel:string; - shiftKeyLabel:string; - altKeyLabel:string; - cmdKeyLabel:string; - windowsKeyLabel:string; - modifierSeparator:string; - getLabelForKey(keyCode:KeyCode): string; + ctrlKeyLabel: string; + shiftKeyLabel: string; + altKeyLabel: string; + cmdKeyLabel: string; + windowsKeyLabel: string; + modifierSeparator: string; + getLabelForKey(keyCode: KeyCode): string; } /** @@ -281,7 +281,7 @@ export class ElectronAcceleratorLabelProvider implements IKeyBindingLabelProvide public windowsKeyLabel = 'Super'; public modifierSeparator = '+'; - public getLabelForKey(keyCode:KeyCode): string { + public getLabelForKey(keyCode: KeyCode): string { switch (keyCode) { case KeyCode.UpArrow: return 'Up'; @@ -315,7 +315,7 @@ export class MacUIKeyLabelProvider implements IKeyBindingLabelProvider { public windowsKeyLabel = nls.localize('windowsKey', "Windows"); public modifierSeparator = ''; - public getLabelForKey(keyCode:KeyCode): string { + public getLabelForKey(keyCode: KeyCode): string { switch (keyCode) { case KeyCode.LeftArrow: return MacUIKeyLabelProvider.leftArrowUnicodeLabel; @@ -344,7 +344,7 @@ export class AriaKeyLabelProvider implements IKeyBindingLabelProvider { public windowsKeyLabel = nls.localize('windowsKey.long', "Windows"); public modifierSeparator = '+'; - public getLabelForKey(keyCode:KeyCode): string { + public getLabelForKey(keyCode: KeyCode): string { return KeyCodeUtils.toString(keyCode); } } @@ -362,7 +362,7 @@ export class ClassicUIKeyLabelProvider implements IKeyBindingLabelProvider { public windowsKeyLabel = nls.localize('windowsKey', "Windows"); public modifierSeparator = '+'; - public getLabelForKey(keyCode:KeyCode): string { + public getLabelForKey(keyCode: KeyCode): string { return KeyCodeUtils.toString(keyCode); } } @@ -381,13 +381,13 @@ class UserSettingsKeyLabelProvider implements IKeyBindingLabelProvider { public modifierSeparator = '+'; - public getLabelForKey(keyCode:KeyCode): string { + public getLabelForKey(keyCode: KeyCode): string { return USER_SETTINGS.fromKeyCode(keyCode); } } -function _asString(keybinding:number, labelProvider:IKeyBindingLabelProvider, Platform:ISimplifiedPlatform): string { - let result:string[] = [], +function _asString(keybinding: number, labelProvider: IKeyBindingLabelProvider, Platform: ISimplifiedPlatform): string { + let result: string[] = [], ctrlCmd = BinaryKeybindings.hasCtrlCmd(keybinding), shift = BinaryKeybindings.hasShift(keybinding), alt = BinaryKeybindings.hasAlt(keybinding), @@ -433,7 +433,7 @@ function _asString(keybinding:number, labelProvider:IKeyBindingLabelProvider, Pl return actualResult; } -function _pushKey(result:IHTMLContentElement[], str:string): void { +function _pushKey(result: IHTMLContentElement[], str: string): void { if (result.length > 0) { result.push({ tagName: 'span', @@ -447,8 +447,8 @@ function _pushKey(result:IHTMLContentElement[], str:string): void { }); } -function _asHTML(keybinding:number, labelProvider:IKeyBindingLabelProvider, Platform:ISimplifiedPlatform, isChord:boolean = false): IHTMLContentElement[] { - let result:IHTMLContentElement[] = [], +function _asHTML(keybinding: number, labelProvider: IKeyBindingLabelProvider, Platform: ISimplifiedPlatform, isChord: boolean = false): IHTMLContentElement[] { + let result: IHTMLContentElement[] = [], ctrlCmd = BinaryKeybindings.hasCtrlCmd(keybinding), shift = BinaryKeybindings.hasShift(keybinding), alt = BinaryKeybindings.hasAlt(keybinding), diff --git a/src/vs/base/common/lifecycle.ts b/src/vs/base/common/lifecycle.ts index 1777452f52708..ae0f900fb1c7e 100644 --- a/src/vs/base/common/lifecycle.ts +++ b/src/vs/base/common/lifecycle.ts @@ -47,7 +47,7 @@ export abstract class Disposable implements IDisposable { this._toDispose = dispose(this._toDispose); } - protected _register(t:T): T { + protected _register(t: T): T { this._toDispose.push(t); return t; } diff --git a/src/vs/base/common/map.ts b/src/vs/base/common/map.ts index b79e3bd0c5309..f274d1a72d67d 100644 --- a/src/vs/base/common/map.ts +++ b/src/vs/base/common/map.ts @@ -6,7 +6,7 @@ 'use strict'; export interface Key { - toString():string; + toString(): string; } export interface Entry { @@ -86,7 +86,7 @@ export class LinkedMap { } public delete(k: K): T { - let value:T= this.get(k); + let value: T = this.get(k); if (value) { this.pop(k); return value; @@ -115,7 +115,7 @@ export class LinkedMap { } protected peek(k: K): T { - const entry= this.map[k.toString()]; + const entry = this.map[k.toString()]; return entry ? entry.value : null; } } diff --git a/src/vs/base/common/marked/marked.d.ts b/src/vs/base/common/marked/marked.d.ts index 6b76d2b40a0e1..ee4c622d085a9 100644 --- a/src/vs/base/common/marked/marked.d.ts +++ b/src/vs/base/common/marked/marked.d.ts @@ -2,7 +2,7 @@ * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ - + // Type definitions for Marked // Project:https://github.com/chjj/marked // Definitions by:William Orr @@ -16,7 +16,7 @@ export interface MarkedStatic { * @param callback Function called when the markdownString has been fully parsed when using async highlighting * @return String of compiled HTML */ - (src:string, callback:Function):string; + (src: string, callback: Function): string; /** * Compiles markdown to HTML. @@ -26,13 +26,13 @@ export interface MarkedStatic { * @param callback Function called when the markdownString has been fully parsed when using async highlighting * @return String of compiled HTML */ - (src:string, options?:MarkedOptions, callback?:Function):string; + (src: string, options?: MarkedOptions, callback?: Function): string; /** * @param src String of markdown source to be compiled * @param options Hash of options */ - lexer(src:string, options?:MarkedOptions):any[]; + lexer(src: string, options?: MarkedOptions): any[]; /** * Compiles markdown to HTML. @@ -41,7 +41,7 @@ export interface MarkedStatic { * @param callback Function called when the markdownString has been fully parsed when using async highlighting * @return String of compiled HTML */ - parse(src:string, callback:Function):string; + parse(src: string, callback: Function): string; /** * Compiles markdown to HTML. @@ -51,112 +51,112 @@ export interface MarkedStatic { * @param callback Function called when the markdownString has been fully parsed when using async highlighting * @return String of compiled HTML */ - parse(src:string, options?:MarkedOptions, callback?:Function):string; + parse(src: string, options?: MarkedOptions, callback?: Function): string; /** * @param options Hash of options */ - parser(src:any[], options?:MarkedOptions):string; + parser(src: any[], options?: MarkedOptions): string; /** * Sets the default options. * * @param options Hash of options */ - setOptions(options:MarkedOptions):void; - + setOptions(options: MarkedOptions): void; + /** * Custom renderer for marked. */ - Renderer:Renderer; + Renderer: Renderer; } export interface Renderer { - prototype:MarkedRenderer; - new ():MarkedRenderer; + prototype: MarkedRenderer; + new (): MarkedRenderer; } export interface MarkedRenderer { - image(href:string, title:string, text:string):string; - code(code:string, language:string):string; - blockquote(quote:string):string; - html(html:string):string; - heading(text:string, level:number):string; - hr():string; - list(body:string, ordered:boolean):string; - listitem(text:string):string; - paragraph(text:string):string; - table(header:string, body:string):string; - tablerow(content:string):string; - tablecell(content:string, flags:ITableFlags):string; - strong(text:string):string; - em(text:string):string; - codespan(code:string):string; - br():string; - del(text:string):string; - link(href:string, title:string, text:string):string; + image(href: string, title: string, text: string): string; + code(code: string, language: string): string; + blockquote(quote: string): string; + html(html: string): string; + heading(text: string, level: number): string; + hr(): string; + list(body: string, ordered: boolean): string; + listitem(text: string): string; + paragraph(text: string): string; + table(header: string, body: string): string; + tablerow(content: string): string; + tablecell(content: string, flags: ITableFlags): string; + strong(text: string): string; + em(text: string): string; + codespan(code: string): string; + br(): string; + del(text: string): string; + link(href: string, title: string, text: string): string; } export interface ITableFlags { - header:boolean; - align:string; // 'center' || 'left' || 'right' + header: boolean; + align: string; // 'center' || 'left' || 'right' } export interface MarkedOptions { /** * Enable GitHub flavored markdown. */ - gfm?:boolean; + gfm?: boolean; /** * Enable GFM tables. This option requires the gfm option to be true. */ - tables?:boolean; + tables?: boolean; /** * Enable GFM line breaks. This option requires the gfm option to be true. */ - breaks?:boolean; + breaks?: boolean; /** * Conform to obscure parts of markdown.pl as much as possible. Don't fix any of the original markdown bugs or poor behavior. */ - pedantic?:boolean; + pedantic?: boolean; /** * Sanitize the output. Ignore any HTML that has been input. */ - sanitize?:boolean; + sanitize?: boolean; /** * Use smarter list behavior than the original markdown. May eventually be default with the old behavior moved into pedantic. */ - smartLists?:boolean; + smartLists?: boolean; /** * Shows an HTML error message when rendering fails. */ - silent?:boolean; + silent?: boolean; /** * A function to highlight code blocks. The function takes three arguments:code, lang, and callback. */ - highlight? (code:string, lang:string, callback?:Function):void; + highlight?(code: string, lang: string, callback?: Function): void; /** * Set the prefix for code block classes. */ - langPrefix?:string; + langPrefix?: string; /** * Use "smart" typograhic punctuation for things like quotes and dashes. */ - smartypants?:boolean; + smartypants?: boolean; /** * The renderer to use with marked rendering. */ - renderer?:any; + renderer?: any; } -export declare var marked:MarkedStatic; \ No newline at end of file +export declare var marked: MarkedStatic; \ No newline at end of file diff --git a/src/vs/base/common/mime.ts b/src/vs/base/common/mime.ts index 8357520cda7de..d47010f4e0b3a 100644 --- a/src/vs/base/common/mime.ts +++ b/src/vs/base/common/mime.ts @@ -7,7 +7,7 @@ import paths = require('vs/base/common/paths'); import types = require('vs/base/common/types'); import strings = require('vs/base/common/strings'); -import {match} from 'vs/base/common/glob'; +import { match } from 'vs/base/common/glob'; export let MIME_TEXT = 'text/plain'; export let MIME_BINARY = 'application/octet-stream'; diff --git a/src/vs/base/common/network.ts b/src/vs/base/common/network.ts index 293585f5eeb10..ee18a5ec9d2da 100644 --- a/src/vs/base/common/network.ts +++ b/src/vs/base/common/network.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {TPromise} from 'vs/base/common/winjs.base'; +import { TPromise } from 'vs/base/common/winjs.base'; export namespace Schemas { @@ -12,38 +12,38 @@ export namespace Schemas { * A schema that is used for models that exist in memory * only and that have no correspondence on a server or such. */ - export var inMemory:string = 'inmemory'; + export var inMemory: string = 'inmemory'; /** * A schema that is used for setting files */ - export var vscode:string = 'vscode'; + export var vscode: string = 'vscode'; /** * A schema that is used for internal private files */ - export var internal:string = 'private'; + export var internal: string = 'private'; - export var http:string = 'http'; + export var http: string = 'http'; - export var https:string = 'https'; + export var https: string = 'https'; - export var file:string = 'file'; + export var file: string = 'file'; } export interface IXHROptions { - type?:string; - url?:string; - user?:string; - password?:string; - responseType?:string; - headers?:any; - customRequestInitializer?:(req:any)=>void; - data?:any; + type?: string; + url?: string; + user?: string; + password?: string; + responseType?: string; + headers?: any; + customRequestInitializer?: (req: any) => void; + data?: any; } -export function xhr(options:IXHROptions): TPromise { - let req:XMLHttpRequest = null; +export function xhr(options: IXHROptions): TPromise { + let req: XMLHttpRequest = null; let canceled = false; return new TPromise((c, e, p) => { diff --git a/src/vs/base/common/numbers.ts b/src/vs/base/common/numbers.ts index 4b32bc9a4f542..c677d7fd20f76 100644 --- a/src/vs/base/common/numbers.ts +++ b/src/vs/base/common/numbers.ts @@ -7,7 +7,7 @@ import types = require('vs/base/common/types'); -export type NumberCallback = (index: number)=>void; +export type NumberCallback = (index: number) => void; export function count(to: number, callback: NumberCallback): void; export function count(from: number, to: number, callback: NumberCallback): void; @@ -16,11 +16,11 @@ export function count(fromOrTo: number, toOrCallback?: NumberCallback | number, if (types.isNumber(toOrCallback)) { from = fromOrTo; - to = toOrCallback; + to = toOrCallback; } else { from = 0; to = fromOrTo; - callback = toOrCallback; + callback = toOrCallback; } var op = from <= to ? (i: number) => i + 1 : (i: number) => i - 1; diff --git a/src/vs/base/common/objects.ts b/src/vs/base/common/objects.ts index 30c45bd7fc227..538f8cc1e3cbb 100644 --- a/src/vs/base/common/objects.ts +++ b/src/vs/base/common/objects.ts @@ -148,7 +148,7 @@ export function assign(destination: any, ...sources: any[]): any { return destination; } -export function toObject(arr: T[], keyMap: (T) => string, valueMap: (T) => R = x => x): { [key: string]: R } { +export function toObject(arr: T[], keyMap: (T) => string, valueMap: (T) => R = x => x): { [key: string]: R } { return arr.reduce((o, d) => assign(o, { [keyMap(d)]: valueMap(d) }), Object.create(null)); } @@ -182,13 +182,13 @@ export function equals(one: any, other: any): boolean { } } } else { - var oneKeys:string[] = []; + var oneKeys: string[] = []; for (key in one) { oneKeys.push(key); } oneKeys.sort(); - var otherKeys:string[] = []; + var otherKeys: string[] = []; for (key in other) { otherKeys.push(key); } @@ -288,7 +288,7 @@ export function safeStringify(obj: any): string { }); } -export function getOrDefault(obj: T, fn: (obj: T) => R, defaultValue: R = null): R { +export function getOrDefault(obj: T, fn: (obj: T) => R, defaultValue: R = null): R { const result = fn(obj); return typeof result === 'undefined' ? defaultValue : result; } \ No newline at end of file diff --git a/src/vs/base/common/paging.ts b/src/vs/base/common/paging.ts index 5e9fbcc8a02db..9b4966c2a203b 100644 --- a/src/vs/base/common/paging.ts +++ b/src/vs/base/common/paging.ts @@ -122,7 +122,7 @@ export class PagedModel implements IPagedModel { * Similar to array.map, `mapPager` lets you map the elements of an * abstract paged collection to another type. */ -export function mapPager(pager: IPager, fn: (t: T) => R): IPager { +export function mapPager(pager: IPager, fn: (t: T) => R): IPager { return { firstPage: pager.firstPage.map(fn), total: pager.total, diff --git a/src/vs/base/common/parsers.ts b/src/vs/base/common/parsers.ts index fb34ec93e7ffd..e97d340eb58d1 100644 --- a/src/vs/base/common/parsers.ts +++ b/src/vs/base/common/parsers.ts @@ -16,17 +16,17 @@ export enum ValidationState { } export class ValidationStatus { - private _state:ValidationState; + private _state: ValidationState; constructor() { this._state = ValidationState.OK; } - public get state():ValidationState { + public get state(): ValidationState { return this._state; } - public set state(value:ValidationState) { + public set state(value: ValidationState) { if (value > this._state) { this._state = value; } @@ -42,7 +42,7 @@ export class ValidationStatus { } export interface ILogger { - log(value:string):void; + log(value: string): void; } export abstract class Parser { @@ -67,7 +67,7 @@ export abstract class Parser { this._logger.log(message); } - protected is(value: any, func: (value:any) => boolean, wrongTypeState?: ValidationState, wrongTypeMessage?: string, undefinedState?: ValidationState, undefinedMessage?: string): boolean { + protected is(value: any, func: (value: any) => boolean, wrongTypeState?: ValidationState, wrongTypeMessage?: string, undefinedState?: ValidationState, undefinedMessage?: string): boolean { if (Types.isUndefined(value)) { if (undefinedState) { this.validationStatus.state = undefinedState; diff --git a/src/vs/base/common/paths.ts b/src/vs/base/common/paths.ts index 40b4190c0d59c..084eacd9782be 100644 --- a/src/vs/base/common/paths.ts +++ b/src/vs/base/common/paths.ts @@ -4,9 +4,9 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {isLinux, isWindows} from 'vs/base/common/platform'; -import {fill} from 'vs/base/common/arrays'; -import {CharCode} from 'vs/base/common/charCode'; +import { isLinux, isWindows } from 'vs/base/common/platform'; +import { fill } from 'vs/base/common/arrays'; +import { CharCode } from 'vs/base/common/charCode'; /** * The forward slash path separator. @@ -150,7 +150,7 @@ export function normalize(path: string, toOSPath?: boolean): string { } function streql(value: string, start: number, end: number, other: string): boolean { - return start + other.length === end && value.indexOf(other, start) === start; + return start + other.length === end && value.indexOf(other, start) === start; } /** diff --git a/src/vs/base/common/platform.ts b/src/vs/base/common/platform.ts index 5771fcbd54a95..3075beb0a977e 100644 --- a/src/vs/base/common/platform.ts +++ b/src/vs/base/common/platform.ts @@ -51,7 +51,7 @@ if (typeof process === 'object') { let rawNlsConfig = process.env['VSCODE_NLS_CONFIG']; if (rawNlsConfig) { try { - let nlsConfig:NLSConfig = JSON.parse(rawNlsConfig); + let nlsConfig: NLSConfig = JSON.parse(rawNlsConfig); let resolved = nlsConfig.availableLanguages['*']; _locale = nlsConfig.locale; // VSCode's default language is 'en' @@ -78,7 +78,7 @@ export enum Platform { Windows } -export let _platform:Platform = Platform.Web; +export let _platform: Platform = Platform.Web; if (_isNative) { if (_isMacintosh) { _platform = Platform.Mac; @@ -127,7 +127,7 @@ interface IGlobals { clearInterval(token: IntervalToken); } -const _globals = (typeof self === 'object' ? self : global); +const _globals = (typeof self === 'object' ? self : global); export const globals: any = _globals; export function hasWebWorkerSupport(): boolean { diff --git a/src/vs/base/common/processes.ts b/src/vs/base/common/processes.ts index afd581318cd1f..4acc85c681245 100644 --- a/src/vs/base/common/processes.ts +++ b/src/vs/base/common/processes.ts @@ -27,7 +27,7 @@ export interface CommandOptions { * The environment of the executed program or shell. If omitted * the parent process' environment is used. */ - env?: { [key:string]: string; }; + env?: { [key: string]: string; }; } export interface Executable { @@ -67,19 +67,19 @@ export enum Source { * The data send via a success callback */ export interface SuccessData { - error?:Error; - cmdCode?:number; - terminated?:boolean; + error?: Error; + cmdCode?: number; + terminated?: boolean; } /** * The data send via a error callback */ export interface ErrorData { - error?:Error; - terminated?:boolean; - stdout?:string; - stderr?:string; + error?: Error; + terminated?: boolean; + stdout?: string; + stderr?: string; } export interface TerminateResponse { @@ -115,7 +115,7 @@ export namespace Config { /** * Index signature */ - [key:string]: string | string[] | IStringDictionary; + [key: string]: string | string[] | IStringDictionary; } export interface BaseExecutable { diff --git a/src/vs/base/common/remote.ts b/src/vs/base/common/remote.ts index a605a56dadee5..eb5ccee9c8f58 100644 --- a/src/vs/base/common/remote.ts +++ b/src/vs/base/common/remote.ts @@ -4,16 +4,16 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {TPromise} from 'vs/base/common/winjs.base'; +import { TPromise } from 'vs/base/common/winjs.base'; export interface IManyHandler { - handle(rpcId:string, method:string, args:any[]): any; + handle(rpcId: string, method: string, args: any[]): any; } export interface IProxyHelper { - callOnRemote(proxyId: string, path: string, args:any[]): TPromise; + callOnRemote(proxyId: string, path: string, args: any[]): TPromise; } export interface IRemoteCom extends IProxyHelper { - setManyHandler(handler:IManyHandler): void; + setManyHandler(handler: IManyHandler): void; } diff --git a/src/vs/base/common/scorer.ts b/src/vs/base/common/scorer.ts index c61fdca2f41d1..79e879b8d2589 100644 --- a/src/vs/base/common/scorer.ts +++ b/src/vs/base/common/scorer.ts @@ -35,7 +35,7 @@ BEGIN THIRD PARTY * Start of string bonus: 8 */ const wordPathBoundary = ['-', '_', ' ', '/', '\\', '.']; -export function score(target: string, query: string, cache?: {[id: string]: number}): number { +export function score(target: string, query: string, cache?: { [id: string]: number }): number { if (!target || !query) { return 0; // return early if target or query are undefined } diff --git a/src/vs/base/common/scrollable.ts b/src/vs/base/common/scrollable.ts index fb5d6714f1499..877c85f0a2b88 100644 --- a/src/vs/base/common/scrollable.ts +++ b/src/vs/base/common/scrollable.ts @@ -4,8 +4,8 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {Disposable} from 'vs/base/common/lifecycle'; -import Event, {Emitter} from 'vs/base/common/event'; +import { Disposable } from 'vs/base/common/lifecycle'; +import Event, { Emitter } from 'vs/base/common/event'; export enum ScrollbarVisibility { Auto = 1, @@ -88,14 +88,14 @@ export class Scrollable extends Disposable { return this._scrollTop; } - public updateState(newState:INewScrollState): void { - let width = (typeof newState.width !== 'undefined' ? newState.width|0 : this._width); - let scrollWidth = (typeof newState.scrollWidth !== 'undefined' ? newState.scrollWidth|0 : this._scrollWidth); - let scrollLeft = (typeof newState.scrollLeft !== 'undefined' ? newState.scrollLeft|0 : this._scrollLeft); + public updateState(newState: INewScrollState): void { + let width = (typeof newState.width !== 'undefined' ? newState.width | 0 : this._width); + let scrollWidth = (typeof newState.scrollWidth !== 'undefined' ? newState.scrollWidth | 0 : this._scrollWidth); + let scrollLeft = (typeof newState.scrollLeft !== 'undefined' ? newState.scrollLeft | 0 : this._scrollLeft); - let height = (typeof newState.height !== 'undefined' ? newState.height|0 : this._height); - let scrollHeight = (typeof newState.scrollHeight !== 'undefined' ? newState.scrollHeight|0 : this._scrollHeight); - let scrollTop = (typeof newState.scrollTop !== 'undefined' ? newState.scrollTop|0 : this._scrollTop); + let height = (typeof newState.height !== 'undefined' ? newState.height | 0 : this._height); + let scrollHeight = (typeof newState.scrollHeight !== 'undefined' ? newState.scrollHeight | 0 : this._scrollHeight); + let scrollTop = (typeof newState.scrollTop !== 'undefined' ? newState.scrollTop | 0 : this._scrollTop); if (width < 0) { width = 0; diff --git a/src/vs/base/common/stopwatch.ts b/src/vs/base/common/stopwatch.ts index b1ae34e893d8d..4f0fc157da35d 100644 --- a/src/vs/base/common/stopwatch.ts +++ b/src/vs/base/common/stopwatch.ts @@ -14,7 +14,7 @@ export class StopWatch { private _startTime: number; private _stopTime: number; - public static create(highResolution:boolean = true): StopWatch { + public static create(highResolution: boolean = true): StopWatch { return new StopWatch(highResolution); } diff --git a/src/vs/base/common/strings.ts b/src/vs/base/common/strings.ts index 93a86fc32f9a7..c6fccf78c27c4 100644 --- a/src/vs/base/common/strings.ts +++ b/src/vs/base/common/strings.ts @@ -4,8 +4,8 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {BoundedLinkedMap} from 'vs/base/common/map'; -import {CharCode} from 'vs/base/common/charCode'; +import { BoundedLinkedMap } from 'vs/base/common/map'; +import { CharCode } from 'vs/base/common/charCode'; /** * The empty string. @@ -38,7 +38,7 @@ export function format(value: string, ...args: any[]): string { if (args.length === 0) { return value; } - return value.replace(_formatRegexp, function(match, group) { + return value.replace(_formatRegexp, function (match, group) { let idx = parseInt(group, 10); return isNaN(idx) || idx < 0 || idx >= args.length ? match : @@ -51,7 +51,7 @@ export function format(value: string, ...args: any[]): string { * being used e.g. in HTMLElement.innerHTML. */ export function escape(html: string): string { - return html.replace(/[<|>|&]/g, function(match) { + return html.replace(/[<|>|&]/g, function (match) { switch (match) { case '<': return '<'; case '>': return '>'; @@ -301,7 +301,7 @@ export function lastNonWhitespaceIndex(str: string, startIndex: number = str.len export function compare(a: string, b: string): number { if (a < b) { return -1; - } else if(a > b) { + } else if (a > b) { return 1; } else { return 0; @@ -396,15 +396,15 @@ export function commonSuffixLength(a: string, b: string): number { // } // return chrCode; //} -export function isHighSurrogate(charCode:number): boolean { +export function isHighSurrogate(charCode: number): boolean { return (0xD800 <= charCode && charCode <= 0xDBFF); } -export function isLowSurrogate(charCode:number): boolean { +export function isLowSurrogate(charCode: number): boolean { return (0xDC00 <= charCode && charCode <= 0xDFFF); } -export function isFullWidthCharacter(charCode:number): boolean { +export function isFullWidthCharacter(charCode: number): boolean { // Do a cheap trick to better support wrapping of wide characters, treat them as 2 columns // http://jrgraphix.net/research/unicode_blocks.php // 2E80 — 2EFF CJK Radicals Supplement @@ -575,7 +575,7 @@ export function safeBtoa(str: string): string { return btoa(encodeURIComponent(str)); // we use encodeURIComponent because btoa fails for non Latin 1 values } -export function repeat(s:string, count: number): string { +export function repeat(s: string, count: number): string { var result = ''; for (var i = 0; i < count; i++) { result += s; diff --git a/src/vs/base/common/timer.ts b/src/vs/base/common/timer.ts index 762b681dffef3..59e0072936830 100644 --- a/src/vs/base/common/timer.ts +++ b/src/vs/base/common/timer.ts @@ -7,7 +7,7 @@ import Platform = require('vs/base/common/platform'); import errors = require('vs/base/common/errors'); import precision = require('vs/base/common/stopwatch'); -import {IDisposable} from 'vs/base/common/lifecycle'; +import { IDisposable } from 'vs/base/common/lifecycle'; export var ENABLE_TIMER = false; var msWriteProfilerMark = Platform.globals['msWriteProfilerMark']; @@ -171,7 +171,7 @@ export class TimeKeeper { return ENABLE_TIMER; } - public start(topic: Topic|string, name: string, start?: Date, description?: string): ITimerEvent { + public start(topic: Topic | string, name: string, start?: Date, description?: string): ITimerEvent { if (!this.isEnabled()) { return nullEvent; } @@ -284,7 +284,7 @@ export class TimeKeeper { var timeKeeper = new TimeKeeper(); export var nullEvent: ITimerEvent = new NullTimerEvent(); -export function start(topic: Topic|string, name: string, start?: Date, description?: string): ITimerEvent { +export function start(topic: Topic | string, name: string, start?: Date, description?: string): ITimerEvent { return timeKeeper.start(topic, name, start, description); } diff --git a/src/vs/base/common/types.ts b/src/vs/base/common/types.ts index cbd795f064f2c..86840cb1ffe55 100644 --- a/src/vs/base/common/types.ts +++ b/src/vs/base/common/types.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {TPromise} from 'vs/base/common/winjs.base'; +import { TPromise } from 'vs/base/common/winjs.base'; const _typeof = { number: 'number', @@ -33,7 +33,7 @@ export function isArray(array: any): array is any[] { * @returns whether the provided parameter is a JavaScript String or not. */ export function isString(str: any): str is string { - if (typeof (str) === _typeof.string|| str instanceof String) { + if (typeof (str) === _typeof.string || str instanceof String) { return true; } diff --git a/src/vs/base/common/uri.ts b/src/vs/base/common/uri.ts index 840f0b3bb0b0a..c8b2c628d4970 100644 --- a/src/vs/base/common/uri.ts +++ b/src/vs/base/common/uri.ts @@ -155,27 +155,27 @@ export default class URI { let {scheme, authority, path, query, fragment} = change; if (scheme === void 0) { scheme = this.scheme; - } else if(scheme === null){ + } else if (scheme === null) { scheme = ''; } if (authority === void 0) { authority = this.authority; - } else if(authority === null){ + } else if (authority === null) { authority = ''; } if (path === void 0) { path = this.path; - } else if(path === null){ + } else if (path === null) { path = ''; } if (query === void 0) { query = this.query; - } else if(query === null){ + } else if (query === null) { query = ''; } if (fragment === void 0) { fragment = this.fragment; - } else if(fragment === null){ + } else if (fragment === null) { fragment = ''; } @@ -357,7 +357,7 @@ export default class URI { // when occurring in paths - otherwise the result // cannot be parsed back again let lastIdx = 0; - while(true) { + while (true) { let idx = path.indexOf(URI._slash, lastIdx); if (idx === -1) { parts.push(encoder(path.substring(lastIdx)).replace(/[#?]/, _encode)); @@ -378,7 +378,7 @@ export default class URI { } public toJSON(): any { - return { + return { scheme: this.scheme, authority: this.authority, path: this.path, @@ -392,12 +392,12 @@ export default class URI { static revive(data: any): URI { let result = new URI(); - result._scheme = ( data).scheme; - result._authority = ( data).authority; - result._path = ( data).path; - result._query = ( data).query; - result._fragment = ( data).fragment; - result._fsPath = ( data).fsPath; + result._scheme = (data).scheme; + result._authority = (data).authority; + result._path = (data).path; + result._query = (data).query; + result._fragment = (data).fragment; + result._fsPath = (data).fsPath; result._formatted = (data).external; URI._validate(result); return result; diff --git a/src/vs/base/common/uuid.ts b/src/vs/base/common/uuid.ts index 675167c31e8f1..f09ee1fc42e20 100644 --- a/src/vs/base/common/uuid.ts +++ b/src/vs/base/common/uuid.ts @@ -12,22 +12,22 @@ export interface UUID { /** * @returns the canonical representation in sets of hexadecimal numbers separated by dashes. */ - asHex():string; + asHex(): string; - equals(other:UUID):boolean; + equals(other: UUID): boolean; } class ValueUUID implements UUID { - constructor(public _value:string) { + constructor(public _value: string) { // empty } - public asHex():string { + public asHex(): string { return this._value; } - public equals(other:UUID):boolean { + public equals(other: UUID): boolean { return this.asHex() === other.asHex(); } } @@ -38,11 +38,11 @@ class V4UUID extends ValueUUID { private static _timeHighBits = ['8', '9', 'a', 'b']; - private static _oneOf(array:string[]):string { + private static _oneOf(array: string[]): string { return array[Math.floor(array.length * Math.random())]; } - private static _randomHex():string { + private static _randomHex(): string { return V4UUID._oneOf(V4UUID._chars); } @@ -91,9 +91,9 @@ class V4UUID extends ValueUUID { /** * An empty UUID that contains only zeros. */ -export const empty:UUID = new ValueUUID('00000000-0000-0000-0000-000000000000'); +export const empty: UUID = new ValueUUID('00000000-0000-0000-0000-000000000000'); -export function v4():UUID { +export function v4(): UUID { return new V4UUID(); } @@ -107,14 +107,14 @@ export function isUUID(value: string): boolean { * Parses a UUID that is of the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. * @param value A uuid string. */ -export function parse(value:string):UUID { - if(!isUUID(value)) { +export function parse(value: string): UUID { + if (!isUUID(value)) { throw new Error('invalid uuid'); } return new ValueUUID(value); } -export function generateUuid():string { +export function generateUuid(): string { return v4().asHex(); } \ No newline at end of file diff --git a/src/vs/base/common/winjs.base.d.ts b/src/vs/base/common/winjs.base.d.ts index 4d939a04f4e10..23b1d178f24f9 100644 --- a/src/vs/base/common/winjs.base.d.ts +++ b/src/vs/base/common/winjs.base.d.ts @@ -5,54 +5,54 @@ /// Interfaces for WinJS export interface ValueCallback { - (value:any):any; + (value: any): any; } export interface EventCallback { - (value:any):void; + (value: any): void; } export interface ErrorCallback { - (error:any):any; + (error: any): any; } export interface ProgressCallback { - (progress:any):any; + (progress: any): any; } export declare class Promise { - constructor(init:(complete:ValueCallback, error:ErrorCallback, progress:ProgressCallback)=>void, oncancel?: any); + constructor(init: (complete: ValueCallback, error: ErrorCallback, progress: ProgressCallback) => void, oncancel?: any); // commented out to speed up adoption of TPromise // static as(value:any):Promise; - static join(promises:{[name:string]:Promise;}):Promise; - static join(promises:Promise[]):Promise; - static any(promises:Promise[]):Promise; + static join(promises: { [name: string]: Promise; }): Promise; + static join(promises: Promise[]): Promise; + static any(promises: Promise[]): Promise; // commented out to speed up adoption of TPromise // static timeout(delay:number):Promise; - static wrapError(error:any):Promise; + static wrapError(error: any): Promise; static is(value: any): value is Thenable; - static addEventListener(type:string, fn:EventCallback):void; + static addEventListener(type: string, fn: EventCallback): void; - public then(success?:ValueCallback, error?:ErrorCallback, progress?:ProgressCallback):Promise; - public then(success?:ValueCallback, error?:ErrorCallback, progress?:ProgressCallback):TPromise; - public done(success?:ValueCallback, error?:ErrorCallback, progress?:ProgressCallback):void; - public cancel():void; + public then(success?: ValueCallback, error?: ErrorCallback, progress?: ProgressCallback): Promise; + public then(success?: ValueCallback, error?: ErrorCallback, progress?: ProgressCallback): TPromise; + public done(success?: ValueCallback, error?: ErrorCallback, progress?: ProgressCallback): void; + public cancel(): void; } /** * The value callback to complete a promise */ export interface TValueCallback { - (value:T):void; + (value: T): void; } export interface TProgressCallback { - (progress:T):void; + (progress: T): void; } /** @@ -60,57 +60,57 @@ export interface TProgressCallback { */ export declare class TPromise { - constructor(init:(complete: TValueCallback, error:(err:any)=>void, progress:ProgressCallback)=>void, oncancel?: any); - - public then(success?: (value:V)=>TPromise, error?: (err:any)=>TPromise, progress?:ProgressCallback): TPromise; - public then(success?: (value:V)=>TPromise, error?: (err:any)=>TPromise|U, progress?:ProgressCallback): TPromise; - public then(success?: (value:V)=>TPromise, error?: (err:any)=>U, progress?:ProgressCallback): TPromise; - public then(success?: (value:V)=>TPromise, error?: (err:any)=>void, progress?:ProgressCallback): TPromise; - public then(success?: (value:V)=>TPromise|U, error?: (err:any)=>TPromise, progress?:ProgressCallback): TPromise; - public then(success?: (value:V)=>TPromise|U, error?: (err:any)=>TPromise|U, progress?:ProgressCallback): TPromise; - public then(success?: (value:V)=>TPromise|U, error?: (err:any)=>U, progress?:ProgressCallback): TPromise; - public then(success?: (value:V)=>TPromise|U, error?: (err:any)=>void, progress?:ProgressCallback): TPromise; - public then(success?: (value:V)=>U, error?: (err:any)=>TPromise, progress?:ProgressCallback): TPromise; - public then(success?: (value:V)=>U, error?: (err:any)=>TPromise|U, progress?:ProgressCallback): TPromise; - public then(success?: (value:V)=>U, error?: (err:any)=>U, progress?:ProgressCallback): TPromise; - public then(success?: (value:V)=>U, error?: (err:any)=>void, progress?:ProgressCallback): TPromise; - - public done(success?: (value:V)=>void, error?: (err:any)=>any, progress?:ProgressCallback): void; - public cancel():void; - - public static as(value:ValueType):TPromise; + constructor(init: (complete: TValueCallback, error: (err: any) => void, progress: ProgressCallback) => void, oncancel?: any); + + public then(success?: (value: V) => TPromise, error?: (err: any) => TPromise, progress?: ProgressCallback): TPromise; + public then(success?: (value: V) => TPromise, error?: (err: any) => TPromise | U, progress?: ProgressCallback): TPromise; + public then(success?: (value: V) => TPromise, error?: (err: any) => U, progress?: ProgressCallback): TPromise; + public then(success?: (value: V) => TPromise, error?: (err: any) => void, progress?: ProgressCallback): TPromise; + public then(success?: (value: V) => TPromise | U, error?: (err: any) => TPromise, progress?: ProgressCallback): TPromise; + public then(success?: (value: V) => TPromise | U, error?: (err: any) => TPromise | U, progress?: ProgressCallback): TPromise; + public then(success?: (value: V) => TPromise | U, error?: (err: any) => U, progress?: ProgressCallback): TPromise; + public then(success?: (value: V) => TPromise | U, error?: (err: any) => void, progress?: ProgressCallback): TPromise; + public then(success?: (value: V) => U, error?: (err: any) => TPromise, progress?: ProgressCallback): TPromise; + public then(success?: (value: V) => U, error?: (err: any) => TPromise | U, progress?: ProgressCallback): TPromise; + public then(success?: (value: V) => U, error?: (err: any) => U, progress?: ProgressCallback): TPromise; + public then(success?: (value: V) => U, error?: (err: any) => void, progress?: ProgressCallback): TPromise; + + public done(success?: (value: V) => void, error?: (err: any) => any, progress?: ProgressCallback): void; + public cancel(): void; + + public static as(value: ValueType): TPromise; public static is(value: any): value is Thenable; - public static timeout(delay:number):TPromise; - public static join(promises:TPromise[]):TPromise; - public static join(promises:Thenable[]):Thenable; - public static join(promises: {[n:string]:TPromise}):TPromise<{[n:string]:ValueType}>; - public static any(promises:TPromise[]):TPromise<{ key:string; value:TPromise;}>; + public static timeout(delay: number): TPromise; + public static join(promises: TPromise[]): TPromise; + public static join(promises: Thenable[]): Thenable; + public static join(promises: { [n: string]: TPromise }): TPromise<{ [n: string]: ValueType }>; + public static any(promises: TPromise[]): TPromise<{ key: string; value: TPromise; }>; public static wrap(value: Thenable): TPromise; public static wrap(value: ValueType): TPromise; - public static wrapError(error:any):TPromise; + public static wrapError(error: any): TPromise; } // --- Generic promise with generic progress value -export declare class PPromise extends TPromise { - - constructor(init:(complete: TValueCallback, error:(err:any)=>void, progress: TProgressCallback

)=>void, oncancel?: any); - - public then(success?: (value:C)=>PPromise, error?: (err:any)=>PPromise, progress?:(value:P)=>void): PPromise; - public then(success?: (value:C)=>PPromise, error?: (err:any)=>U, progress?:(value:P)=>void): PPromise; - public then(success?: (value:C)=>PPromise, error?: (err:any)=>void, progress?:(value:P)=>void): PPromise; - public then(success?: (value:C)=>U, error?: (err:any)=>PPromise, progress?:(value:P)=>void): PPromise; - public then(success?: (value:C)=>U, error?: (err:any)=>U, progress?:(value:P)=>void): PPromise; - public then(success?: (value:C)=>U, error?: (err:any)=>void, progress?:(value:P)=>void): PPromise; - - public done(success?: (value:C)=>void, error?: (err:any)=>any, progress?:(value:P)=>void): void; - public cancel():void; - - public static as(value:V):TPromise; - public static timeout(delay:number):PPromise; - public static join(promises:PPromise[]):PPromise; - public static join(promises: {[n:string]:PPromise}):PPromise<{[n:string]:C},P>; - public static any(promises:PPromise[]):PPromise<{ key:string; value:PPromise;},P>; - public static wrapError(error:any):TPromise; +export declare class PPromise extends TPromise { + + constructor(init: (complete: TValueCallback, error: (err: any) => void, progress: TProgressCallback

) => void, oncancel?: any); + + public then(success?: (value: C) => PPromise, error?: (err: any) => PPromise, progress?: (value: P) => void): PPromise; + public then(success?: (value: C) => PPromise, error?: (err: any) => U, progress?: (value: P) => void): PPromise; + public then(success?: (value: C) => PPromise, error?: (err: any) => void, progress?: (value: P) => void): PPromise; + public then(success?: (value: C) => U, error?: (err: any) => PPromise, progress?: (value: P) => void): PPromise; + public then(success?: (value: C) => U, error?: (err: any) => U, progress?: (value: P) => void): PPromise; + public then(success?: (value: C) => U, error?: (err: any) => void, progress?: (value: P) => void): PPromise; + + public done(success?: (value: C) => void, error?: (err: any) => any, progress?: (value: P) => void): void; + public cancel(): void; + + public static as(value: V): TPromise; + public static timeout(delay: number): PPromise; + public static join(promises: PPromise[]): PPromise; + public static join(promises: { [n: string]: PPromise }): PPromise<{ [n: string]: C }, P>; + public static any(promises: PPromise[]): PPromise<{ key: string; value: PPromise; }, P>; + public static wrapError(error: any): TPromise; } \ No newline at end of file diff --git a/src/vs/base/common/worker/simpleWorker.ts b/src/vs/base/common/worker/simpleWorker.ts index 4c8554ef61fb7..38a4fcd30ecd9 100644 --- a/src/vs/base/common/worker/simpleWorker.ts +++ b/src/vs/base/common/worker/simpleWorker.ts @@ -4,26 +4,26 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {transformErrorForSerialization} from 'vs/base/common/errors'; -import {Disposable} from 'vs/base/common/lifecycle'; -import {ErrorCallback, TPromise, ValueCallback} from 'vs/base/common/winjs.base'; -import {ShallowCancelThenPromise} from 'vs/base/common/async'; -import {isWeb} from 'vs/base/common/platform'; +import { transformErrorForSerialization } from 'vs/base/common/errors'; +import { Disposable } from 'vs/base/common/lifecycle'; +import { ErrorCallback, TPromise, ValueCallback } from 'vs/base/common/winjs.base'; +import { ShallowCancelThenPromise } from 'vs/base/common/async'; +import { isWeb } from 'vs/base/common/platform'; const INITIALIZE = '$initialize'; export interface IWorker { - getId():number; - postMessage(message:string):void; - dispose():void; + getId(): number; + postMessage(message: string): void; + dispose(): void; } export interface IWorkerCallback { - (message:string):void; + (message: string): void; } export interface IWorkerFactory { - create(moduleId:string, callback:IWorkerCallback, onErrorCallback:(err:any)=>void):IWorker; + create(moduleId: string, callback: IWorkerCallback, onErrorCallback: (err: any) => void): IWorker; } let webWorkerWarningLogged = false; @@ -63,29 +63,29 @@ interface IMessageReply { } interface IMessageHandler { - sendMessage(msg:string): void; - handleMessage(method:string, args:any[]): TPromise; + sendMessage(msg: string): void; + handleMessage(method: string, args: any[]): TPromise; } class SimpleWorkerProtocol { private _workerId: number; private _lastSentReq: number; - private _pendingReplies: { [req:string]:IMessageReply; }; - private _handler:IMessageHandler; + private _pendingReplies: { [req: string]: IMessageReply; }; + private _handler: IMessageHandler; - constructor(handler:IMessageHandler) { + constructor(handler: IMessageHandler) { this._workerId = -1; this._handler = handler; this._lastSentReq = 0; this._pendingReplies = Object.create(null); } - public setWorkerId(workerId:number): void { + public setWorkerId(workerId: number): void { this._workerId = workerId; } - public sendMessage(method:string, args:any[]): TPromise { + public sendMessage(method: string, args: any[]): TPromise { let req = String(++this._lastSentReq); let reply: IMessageReply = { c: null, @@ -109,11 +109,11 @@ class SimpleWorkerProtocol { return result; } - public handleMessage(serializedMessage:string): void { - let message:IMessage; + public handleMessage(serializedMessage: string): void { + let message: IMessage; try { message = JSON.parse(serializedMessage); - } catch(e) { + } catch (e) { // nothing } if (!message.vsWorker) { @@ -125,7 +125,7 @@ class SimpleWorkerProtocol { this._handleMessage(message); } - private _handleMessage(msg:IMessage): void { + private _handleMessage(msg: IMessage): void { if (msg.seq) { let replyMessage = msg; if (!this._pendingReplies[replyMessage.seq]) { @@ -172,7 +172,7 @@ class SimpleWorkerProtocol { }); } - private _send(msg:IRequestMessage|IReplyMessage): void { + private _send(msg: IRequestMessage | IReplyMessage): void { let strMsg = JSON.stringify(msg); // console.log('SENDING: ' + strMsg); this._handler.sendMessage(strMsg); @@ -184,24 +184,24 @@ class SimpleWorkerProtocol { */ export class SimpleWorkerClient extends Disposable { - private _worker:IWorker; - private _onModuleLoaded:TPromise; + private _worker: IWorker; + private _onModuleLoaded: TPromise; private _protocol: SimpleWorkerProtocol; private _lazyProxy: TPromise; private _lastRequestTimestamp = -1; - constructor(workerFactory:IWorkerFactory, moduleId:string) { + constructor(workerFactory: IWorkerFactory, moduleId: string) { super(); - let lazyProxyFulfill : (v:T)=>void = null; - let lazyProxyReject: (err:any)=>void = null; + let lazyProxyFulfill: (v: T) => void = null; + let lazyProxyReject: (err: any) => void = null; this._worker = this._register(workerFactory.create( 'vs/base/common/worker/simpleWorker', - (msg:string) => { + (msg: string) => { this._protocol.handleMessage(msg); }, - (err:any) => { + (err: any) => { // in Firefox, web workers fail lazily :( // we will reject the proxy lazyProxyReject(err); @@ -209,10 +209,10 @@ export class SimpleWorkerClient extends Disposable { )); this._protocol = new SimpleWorkerProtocol({ - sendMessage: (msg:string): void => { + sendMessage: (msg: string): void => { this._worker.postMessage(msg); }, - handleMessage: (method:string, args:any[]): TPromise => { + handleMessage: (method: string, args: any[]): TPromise => { // Intentionally not supporting worker -> main requests return TPromise.as(null); } @@ -220,7 +220,7 @@ export class SimpleWorkerClient extends Disposable { this._protocol.setWorkerId(this._worker.getId()); // Gather loader configuration - let loaderConfiguration:any = null; + let loaderConfiguration: any = null; let globalRequire = (window).require; if (typeof globalRequire.getConfig === 'function') { // Get the configuration from the Monaco AMD Loader @@ -241,7 +241,7 @@ export class SimpleWorkerClient extends Disposable { moduleId, loaderConfiguration ]); - this._onModuleLoaded.then((availableMethods:string[]) => { + this._onModuleLoaded.then((availableMethods: string[]) => { let proxy = {}; for (let i = 0; i < availableMethods.length; i++) { proxy[availableMethods[i]] = createProxyMethod(availableMethods[i], proxyMethodRequest); @@ -253,11 +253,11 @@ export class SimpleWorkerClient extends Disposable { }); // Create proxy to loaded code - let proxyMethodRequest = (method:string, args:any[]):TPromise => { + let proxyMethodRequest = (method: string, args: any[]): TPromise => { return this._request(method, args); }; - let createProxyMethod = (method:string, proxyMethodRequest:(method:string, args:any[])=>TPromise): Function => { + let createProxyMethod = (method: string, proxyMethodRequest: (method: string, args: any[]) => TPromise): Function => { return function () { let args = Array.prototype.slice.call(arguments, 0); return proxyMethodRequest(method, args); @@ -274,7 +274,7 @@ export class SimpleWorkerClient extends Disposable { return this._lastRequestTimestamp; } - private _request(method:string, args:any[]): TPromise { + private _request(method: string, args: any[]): TPromise { return new TPromise((c, e, p) => { this._onModuleLoaded.then(() => { this._lastRequestTimestamp = Date.now(); @@ -285,7 +285,7 @@ export class SimpleWorkerClient extends Disposable { }); } - private _onError(message:string, error?:any): void { + private _onError(message: string, error?: any): void { console.error(message); console.info(error); } @@ -303,20 +303,20 @@ export class SimpleWorkerServer { private _protocol: SimpleWorkerProtocol; private _requestHandler: IRequestHandler; - constructor(postSerializedMessage:(msg:string)=>void) { + constructor(postSerializedMessage: (msg: string) => void) { this._protocol = new SimpleWorkerProtocol({ - sendMessage: (msg:string): void => { + sendMessage: (msg: string): void => { postSerializedMessage(msg); }, - handleMessage: (method:string, args:any[]): TPromise => this._handleMessage(method, args) + handleMessage: (method: string, args: any[]): TPromise => this._handleMessage(method, args) }); } - public onmessage(msg:string): void { + public onmessage(msg: string): void { this._protocol.handleMessage(msg); } - private _handleMessage(method: string, args:any[]): TPromise { + private _handleMessage(method: string, args: any[]): TPromise { if (method === INITIALIZE) { return this.initialize(args[0], args[1], args[2]); } @@ -332,7 +332,7 @@ export class SimpleWorkerServer { } } - private initialize(workerId: number, moduleId: string, loaderConfig:any): TPromise { + private initialize(workerId: number, moduleId: string, loaderConfig: any): TPromise { this._protocol.setWorkerId(workerId); if (loaderConfig) { @@ -348,7 +348,7 @@ export class SimpleWorkerServer { let nlsConfig = loaderConfig['vs/nls']; // We need to have pseudo translation if (nlsConfig && nlsConfig.pseudo) { - require(['vs/nls'], function(nlsPlugin) { + require(['vs/nls'], function (nlsPlugin) { nlsPlugin.setPseudoTranslation(nlsConfig.pseudo); }); } @@ -366,7 +366,7 @@ export class SimpleWorkerServer { }); // Use the global require to be sure to get the global config - (self).require([moduleId], (...result:any[]) => { + (self).require([moduleId], (...result: any[]) => { let handlerModule = result[0]; this._requestHandler = handlerModule.create(); @@ -387,6 +387,6 @@ export class SimpleWorkerServer { /** * Called on the worker side */ -export function create(postMessage:(msg:string)=>void): SimpleWorkerServer { +export function create(postMessage: (msg: string) => void): SimpleWorkerServer { return new SimpleWorkerServer(postMessage); } diff --git a/src/vs/base/node/config.ts b/src/vs/base/node/config.ts index 0db68f1c62970..e2a65bbf16215 100644 --- a/src/vs/base/node/config.ts +++ b/src/vs/base/node/config.ts @@ -8,8 +8,8 @@ import * as fs from 'fs'; import * as path from 'path'; import * as objects from 'vs/base/common/objects'; -import {IDisposable, dispose, toDisposable} from 'vs/base/common/lifecycle'; -import Event, {Emitter} from 'vs/base/common/event'; +import { IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle'; +import Event, { Emitter } from 'vs/base/common/event'; import * as json from 'vs/base/common/json'; export interface IConfigurationChangeEvent { diff --git a/src/vs/base/node/decoder.ts b/src/vs/base/node/decoder.ts index 7ea5eef766c0b..f8b2964545886 100644 --- a/src/vs/base/node/decoder.ts +++ b/src/vs/base/node/decoder.ts @@ -6,7 +6,7 @@ 'use strict'; import sd = require('string_decoder'); -import {CharCode} from 'vs/base/common/charCode'; +import { CharCode } from 'vs/base/common/charCode'; /** * Convenient way to iterate over output line by line. This helper accommodates for the fact that diff --git a/src/vs/base/node/event.ts b/src/vs/base/node/event.ts index f30a05111a4f9..8955ae2dd82c8 100644 --- a/src/vs/base/node/event.ts +++ b/src/vs/base/node/event.ts @@ -5,7 +5,7 @@ 'use strict'; -import Event, { Emitter } from 'vs/base/common/event'; +import Event, { Emitter } from 'vs/base/common/event'; import { EventEmitter } from 'events'; export function fromEventEmitter(emitter: EventEmitter, eventName: string, map: (...args: any[]) => T): Event { diff --git a/src/vs/base/node/pfs.ts b/src/vs/base/node/pfs.ts index 20440a71ce987..7420ca61aa1a9 100644 --- a/src/vs/base/node/pfs.ts +++ b/src/vs/base/node/pfs.ts @@ -33,9 +33,9 @@ export function mkdirp(path: string, mode?: number): TPromise { .then(null, (err: NodeJS.ErrnoException) => { if (err.code === 'EEXIST') { return nfcall(fs.stat, path) - .then((stat:fs.Stats) => stat.isDirectory + .then((stat: fs.Stats) => stat.isDirectory ? null - : Promise.wrapError(new Error(`'${ path }' exists and is not a directory.`))); + : Promise.wrapError(new Error(`'${path}' exists and is not a directory.`))); } return TPromise.wrapError(err); @@ -108,7 +108,7 @@ export function readlink(path: string): TPromise { return nfcall(fs.readlink, path); } -export function utimes(path: string, atime:Date, mtime:Date): Promise { +export function utimes(path: string, atime: Date, mtime: Date): Promise { return nfcall(fs.utimes, path, atime, mtime); } diff --git a/src/vs/base/node/ports.ts b/src/vs/base/node/ports.ts index 61dc57bb6fc37..83501989f27ee 100644 --- a/src/vs/base/node/ports.ts +++ b/src/vs/base/node/ports.ts @@ -14,7 +14,7 @@ import net = require('net'); export function findFreePort(startPort: number, giveUpAfter: number, timeout: number, clb: (port: number) => void): void { let done = false; - const timeoutHandle = setTimeout(() =>  { + const timeoutHandle = setTimeout(() => { if (!done) { done = true; diff --git a/src/vs/base/node/processes.ts b/src/vs/base/node/processes.ts index 4c9ae0573b31c..1fb759c976237 100644 --- a/src/vs/base/node/processes.ts +++ b/src/vs/base/node/processes.ts @@ -15,7 +15,7 @@ import { PassThrough } from 'stream'; import { fork } from './stdFork'; import nls = require('vs/nls'); -import { PPromise, Promise, TPromise, TValueCallback, TProgressCallback, ErrorCallback } from 'vs/base/common/winjs.base'; +import { PPromise, Promise, TPromise, TValueCallback, TProgressCallback, ErrorCallback } from 'vs/base/common/winjs.base'; import * as Types from 'vs/base/common/types'; import { IStringDictionary } from 'vs/base/common/collections'; import URI from 'vs/base/common/uri'; @@ -59,7 +59,7 @@ function getWindowsCode(status: number): TerminateResponseCode { export function terminateProcess(process: ChildProcess, cwd?: string): TerminateResponse { if (Platform.isWindows) { try { - let options:any = { + let options: any = { stdio: ['pipe', 'pipe', 'ignore'] }; if (cwd) { @@ -67,7 +67,7 @@ export function terminateProcess(process: ChildProcess, cwd?: string): Terminate } cp.execFileSync('taskkill', ['/T', '/F', '/PID', process.pid.toString()], options); } catch (err) { - return { success: false, error: err , code: err.status ? getWindowsCode(err.status) : TerminateResponseCode.Unknown }; + return { success: false, error: err, code: err.status ? getWindowsCode(err.status) : TerminateResponseCode.Unknown }; } } else if (Platform.isLinux || Platform.isMacintosh) { try { @@ -98,7 +98,7 @@ export abstract class AbstractProcess { private childProcess: ChildProcess; protected childProcessPromise: TPromise; - protected terminateRequested:boolean; + protected terminateRequested: boolean; private static WellKnowCommands: IStringDictionary = { 'ant': true, @@ -191,7 +191,7 @@ export abstract class AbstractProcess { } this.childProcess = exec(cmd, this.options, (error, stdout, stderr) => { this.childProcess = null; - let err:any = error; + let err: any = error; // This is tricky since executing a command shell reports error back in case the executed command return an // error or the command didn't exist at all. So we can't blindly treat an error as a failed command. So we // always parse the output and report success unless the job got killed. @@ -210,7 +210,7 @@ export abstract class AbstractProcess { let result: SuccessData = { terminated: this.terminateRequested }; - if (Types.isNumber(data)) { + if (Types.isNumber(data)) { result.cmdCode = data; } cc(result); @@ -270,9 +270,9 @@ export abstract class AbstractProcess { if (childProcess) { this.childProcess = childProcess; this.childProcessPromise = TPromise.as(childProcess); - childProcess.on('error', (error:Error) => { + childProcess.on('error', (error: Error) => { this.childProcess = null; - ee({ terminated: this.terminateRequested, error: error}); + ee({ terminated: this.terminateRequested, error: error }); }); if (childProcess.pid) { this.childProcess.on('close', closeHandler); @@ -293,17 +293,17 @@ export abstract class AbstractProcess { private static regexp = /^[^"].* .*[^"]/; private ensureQuotes(value: string) { - if (AbstractProcess.regexp.test(value)) { - return { - value: '"' + value + '"', //`"${value}"`, - quoted: true - }; - } else { - return { - value: value, - quoted: value.length > 0 && value[0] === '"' && value[value.length - 1] === '"' - }; - } + if (AbstractProcess.regexp.test(value)) { + return { + value: '"' + value + '"', //`"${value}"`, + quoted: true + }; + } else { + return { + value: value, + quoted: value.length > 0 && value[0] === '"' && value[value.length - 1] === '"' + }; + } } public isRunning(): boolean { @@ -336,10 +336,10 @@ export abstract class AbstractProcess { c(false); } let cmdShell = spawn(getWindowsShell(), ['/s', '/c']); - cmdShell.on('error', (error:Error) => { + cmdShell.on('error', (error: Error) => { c(true); }); - cmdShell.on('exit', (data:any) => { + cmdShell.on('exit', (data: any) => { c(false); }); }); @@ -359,15 +359,15 @@ export class LineProcess extends AbstractProcess { } protected handleExec(cc: TValueCallback, pp: TProgressCallback, error: Error, stdout: Buffer, stderr: Buffer) { - [stdout, stderr].forEach((buffer:Buffer, index:number) => { + [stdout, stderr].forEach((buffer: Buffer, index: number) => { let lineDecoder = new LineDecoder(); let lines = lineDecoder.write(buffer); lines.forEach((line) => { - pp({ line: line, source: index === 0 ? Source.stdout : Source.stderr }); + pp({ line: line, source: index === 0 ? Source.stdout : Source.stderr }); }); let line = lineDecoder.end(); if (line) { - pp({ line: line, source: index === 0 ? Source.stdout : Source.stderr }); + pp({ line: line, source: index === 0 ? Source.stdout : Source.stderr }); } }); cc({ terminated: this.terminateRequested, error: error }); @@ -376,11 +376,11 @@ export class LineProcess extends AbstractProcess { protected handleSpawn(childProcess: ChildProcess, cc: TValueCallback, pp: TProgressCallback, ee: ErrorCallback, sync: boolean): void { this.stdoutLineDecoder = new LineDecoder(); this.stderrLineDecoder = new LineDecoder(); - childProcess.stdout.on('data', (data:Buffer) => { + childProcess.stdout.on('data', (data: Buffer) => { let lines = this.stdoutLineDecoder.write(data); lines.forEach(line => pp({ line: line, source: Source.stdout })); }); - childProcess.stderr.on('data', (data:Buffer) => { + childProcess.stderr.on('data', (data: Buffer) => { let lines = this.stderrLineDecoder.write(data); lines.forEach(line => pp({ line: line, source: Source.stderr })); }); @@ -411,10 +411,10 @@ export class BufferProcess extends AbstractProcess { } protected handleSpawn(childProcess: ChildProcess, cc: TValueCallback, pp: TProgressCallback, ee: ErrorCallback, sync: boolean): void { - childProcess.stdout.on('data', (data:Buffer) => { + childProcess.stdout.on('data', (data: Buffer) => { pp({ data: data, source: Source.stdout }); }); - childProcess.stderr.on('data', (data:Buffer) => { + childProcess.stderr.on('data', (data: Buffer) => { pp({ data: data, source: Source.stderr }); }); } diff --git a/src/vs/base/node/request.ts b/src/vs/base/node/request.ts index 06ff673b5ed86..b71ed417ddeb6 100644 --- a/src/vs/base/node/request.ts +++ b/src/vs/base/node/request.ts @@ -87,7 +87,7 @@ export function request(options: IRequestOptions): TPromise { req.end(); }, - () => req && req.abort()); + () => req && req.abort()); } function isSuccess(context: IRequestContext): boolean { diff --git a/src/vs/base/node/stdFork.ts b/src/vs/base/node/stdFork.ts index 4e20df2187e61..44c6a3f3b1729 100644 --- a/src/vs/base/node/stdFork.ts +++ b/src/vs/base/node/stdFork.ts @@ -18,7 +18,7 @@ export interface IForkOpts { execArgv?: string[]; } -function makeRandomHexString(length:number): string { +function makeRandomHexString(length: number): string { let chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; let result = ''; for (let i = 0; i < length; i++) { @@ -38,10 +38,10 @@ function generatePipeName(): string { return path.join(os.tmpdir(), randomName + '.sock'); } -function generatePatchedEnv(env:any, stdInPipeName:string, stdOutPipeName:string, stdErrPipeName:string): any { +function generatePatchedEnv(env: any, stdInPipeName: string, stdOutPipeName: string, stdErrPipeName: string): any { // Set the two unique pipe names and the electron flag as process env - let newEnv:any = {}; + let newEnv: any = {}; for (let key in env) { newEnv[key] = env[key]; } @@ -54,7 +54,7 @@ function generatePatchedEnv(env:any, stdInPipeName:string, stdOutPipeName:string return newEnv; } -export function fork(modulePath: string, args: string[], options: IForkOpts, callback:(error:any, cp:cp.ChildProcess)=>void): void { +export function fork(modulePath: string, args: string[], options: IForkOpts, callback: (error: any, cp: cp.ChildProcess) => void): void { let callbackCalled = false; let resolve = (result: cp.ChildProcess) => { @@ -64,7 +64,7 @@ export function fork(modulePath: string, args: string[], options: IForkOpts, cal callbackCalled = true; callback(null, result); }; - let reject = (err:any) => { + let reject = (err: any) => { if (callbackCalled) { return; } @@ -92,7 +92,7 @@ export function fork(modulePath: string, args: string[], options: IForkOpts, cal let stdOutServer = net.createServer((stdOutStream) => { // The child process will write exactly one chunk with content `ready` when it has installed a listener to the stdin pipe - stdOutStream.once('data', (chunk:Buffer) => { + stdOutStream.once('data', (chunk: Buffer) => { // The child process is sending me the `ready` chunk, time to connect to the stdin pipe childProcess.stdin = net.connect(stdInPipeName); @@ -125,12 +125,12 @@ export function fork(modulePath: string, args: string[], options: IForkOpts, cal execArgv: options.execArgv }); - childProcess.once('error', (err:Error) => { + childProcess.once('error', (err: Error) => { closeServer(); reject(err); }); - childProcess.once('exit', (err:Error) => { + childProcess.once('exit', (err: Error) => { closeServer(); reject(err); }); diff --git a/src/vs/base/node/stream.ts b/src/vs/base/node/stream.ts index 02bc8a17c12d2..1a71b176fdb96 100644 --- a/src/vs/base/node/stream.ts +++ b/src/vs/base/node/stream.ts @@ -11,12 +11,12 @@ import stream = require('stream'); /** * Reads up to total bytes from the provided stream. */ -export function readExactlyByStream(stream:stream.Readable, totalBytes:number, callback:(err:Error, buffer:NodeBuffer, bytesRead:number) => void):void { +export function readExactlyByStream(stream: stream.Readable, totalBytes: number, callback: (err: Error, buffer: NodeBuffer, bytesRead: number) => void): void { let done = false; let buffer = new Buffer(totalBytes); let bytesRead = 0; - stream.on('data', (data:NodeBuffer) => { + stream.on('data', (data: NodeBuffer) => { let bytesToRead = Math.min(totalBytes - bytesRead, data.length); data.copy(buffer, bytesRead, 0, bytesToRead); bytesRead += bytesToRead; @@ -26,7 +26,7 @@ export function readExactlyByStream(stream:stream.Readable, totalBytes:number, c } }); - stream.on('error', (e:Error) => { + stream.on('error', (e: Error) => { if (!done) { done = true; callback(e, null, null); @@ -46,14 +46,14 @@ export function readExactlyByStream(stream:stream.Readable, totalBytes:number, c /** * Reads totalBytes from the provided file. */ -export function readExactlyByFile(file:string, totalBytes:number, callback:(error:Error, buffer:NodeBuffer, bytesRead:number)=>void):void { - fs.open(file, 'r', null, (err, fd)=>{ +export function readExactlyByFile(file: string, totalBytes: number, callback: (error: Error, buffer: NodeBuffer, bytesRead: number) => void): void { + fs.open(file, 'r', null, (err, fd) => { if (err) { return callback(err, null, 0); } - function end(err:Error, resultBuffer:NodeBuffer, bytesRead:number):void { - fs.close(fd, (closeError:Error)=>{ + function end(err: Error, resultBuffer: NodeBuffer, bytesRead: number): void { + fs.close(fd, (closeError: Error) => { if (closeError) { return callback(closeError, null, bytesRead); } @@ -69,8 +69,8 @@ export function readExactlyByFile(file:string, totalBytes:number, callback:(erro let buffer = new Buffer(totalBytes); let bytesRead = 0; let zeroAttempts = 0; - function loop():void { - fs.read(fd, buffer, bytesRead, totalBytes - bytesRead, null, (err, moreBytesRead)=>{ + function loop(): void { + fs.read(fd, buffer, bytesRead, totalBytes - bytesRead, null, (err, moreBytesRead) => { if (err) { return end(err, null, 0); } diff --git a/src/vs/base/node/zip.ts b/src/vs/base/node/zip.ts index afe7255aa4ab4..222149de1486d 100644 --- a/src/vs/base/node/zip.ts +++ b/src/vs/base/node/zip.ts @@ -78,7 +78,7 @@ function extractZip(zipfile: ZipFile, targetPath: string, options: IOptions): Pr } export function extract(zipPath: string, targetPath: string, options: IExtractOptions = {}): Promise { - const sourcePathRegex = new RegExp(options.sourcePath ? `^${ options.sourcePath }` : ''); + const sourcePathRegex = new RegExp(options.sourcePath ? `^${options.sourcePath}` : ''); let promise = nfcall(openZip, zipPath); diff --git a/src/vs/base/parts/ipc/common/ipc.electron.ts b/src/vs/base/parts/ipc/common/ipc.electron.ts index 9e4de8cd357d9..7f607938f308e 100644 --- a/src/vs/base/parts/ipc/common/ipc.electron.ts +++ b/src/vs/base/parts/ipc/common/ipc.electron.ts @@ -17,7 +17,7 @@ export interface Sender { send(channel: string, ...args: any[]): void; } -export interface IPC extends Sender, NodeJS.EventEmitter {} +export interface IPC extends Sender, NodeJS.EventEmitter { } class Protocol implements IMessagePassingProtocol { diff --git a/src/vs/base/parts/ipc/common/ipc.ts b/src/vs/base/parts/ipc/common/ipc.ts index 54a1a00926a35..7458c894afefe 100644 --- a/src/vs/base/parts/ipc/common/ipc.ts +++ b/src/vs/base/parts/ipc/common/ipc.ts @@ -6,7 +6,7 @@ 'use strict'; import { Promise, TPromise } from 'vs/base/common/winjs.base'; -import { IDisposable, toDisposable } from 'vs/base/common/lifecycle'; +import { IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import Event, { Emitter } from 'vs/base/common/event'; enum MessageType { @@ -37,7 +37,7 @@ interface IRawRequest extends IRawMessage { interface IRequest { raw: IRawRequest; emitter?: Emitter; - flush?: ()=>void; + flush?: () => void; } interface IRawResponse extends IRawMessage { @@ -88,7 +88,7 @@ export class ChannelServer { this.channels = Object.create(null); this.activeRequests = Object.create(null); this.protocolListener = this.protocol.onMessage(r => this.onMessage(r)); - this.protocol.send( { type: MessageType.ResponseInitialize }); + this.protocol.send({ type: MessageType.ResponseInitialize }); } registerChannel(channelName: string, channel: IChannel): void { @@ -120,22 +120,24 @@ export class ChannelServer { const id = request.id; const requestPromise = promise.then(data => { - this.protocol.send( { id, data, type: MessageType.ResponseSuccess }); + this.protocol.send({ id, data, type: MessageType.ResponseSuccess }); delete this.activeRequests[request.id]; }, data => { if (data instanceof Error) { - this.protocol.send( { id, data: { - message: data.message, - name: data.name, - stack: data.stack ? data.stack.split('\n') : void 0 - }, type: MessageType.ResponseError }); + this.protocol.send({ + id, data: { + message: data.message, + name: data.name, + stack: data.stack ? data.stack.split('\n') : void 0 + }, type: MessageType.ResponseError + }); } else { - this.protocol.send( { id, data, type: MessageType.ResponseErrorObj }); + this.protocol.send({ id, data, type: MessageType.ResponseErrorObj }); } delete this.activeRequests[request.id]; }, data => { - this.protocol.send( { id, data, type: MessageType.ResponseProgress }); + this.protocol.send({ id, data, type: MessageType.ResponseProgress }); }); this.activeRequests[request.id] = toDisposable(() => requestPromise.cancel()); @@ -223,7 +225,7 @@ export class ChannelClient implements IChannelClient, IDisposable { case MessageType.ResponseError: delete this.handlers[id]; const error = new Error(response.data.message); - ( error).stack = response.data.stack; + (error).stack = response.data.stack; error.name = response.data.name; e(error); break; @@ -241,7 +243,7 @@ export class ChannelClient implements IChannelClient, IDisposable { this.send(request.raw); }, - () => this.send({ id, type: MessageType.RequestCancel })); + () => this.send({ id, type: MessageType.RequestCancel })); } private bufferRequest(request: IRequest): Promise { @@ -332,10 +334,10 @@ export function getNextTickChannel(channel: T): T { return { call } as T; } -export type Serializer = (obj: T) => R; -export type Deserializer = (raw: R) => T; +export type Serializer = (obj: T) => R; +export type Deserializer = (raw: R) => T; -export function eventToCall(event: Event, serializer: Serializer = t => t): TPromise { +export function eventToCall(event: Event, serializer: Serializer = t => t): TPromise { let disposable: IDisposable; return new Promise( @@ -344,7 +346,7 @@ export function eventToCall(event: Event, serializer: Serializer = ); } -export function eventFromCall(channel: IChannel, name: string, arg: any = null, deserializer: Deserializer = t => t): Event { +export function eventFromCall(channel: IChannel, name: string, arg: any = null, deserializer: Deserializer = t => t): Event { let promise: Promise; const emitter = new Emitter({ diff --git a/src/vs/base/parts/ipc/node/ipc.cp.ts b/src/vs/base/parts/ipc/node/ipc.cp.ts index 8c9370dd6a0ea..f0c5c9b9be854 100644 --- a/src/vs/base/parts/ipc/node/ipc.cp.ts +++ b/src/vs/base/parts/ipc/node/ipc.cp.ts @@ -5,7 +5,7 @@ import { ChildProcess, fork } from 'child_process'; import { IDisposable } from 'vs/base/common/lifecycle'; -import { Promise} from 'vs/base/common/winjs.base'; +import { Promise } from 'vs/base/common/winjs.base'; import { Delayer } from 'vs/base/common/async'; import { clone, assign } from 'vs/base/common/objects'; import { Emitter } from 'vs/base/common/event'; @@ -33,27 +33,27 @@ export interface IIPCOptions { /** * Time in millies before killing the ipc process. The next request after killing will start it again. */ - timeout?:number; + timeout?: number; /** * Arguments to the module to execute. */ - args?:string[]; + args?: string[]; /** * Environment key-value pairs to be passed to the process that gets spawned for the ipc. */ - env?:any; + env?: any; /** * Allows to assign a debug port for debugging the application executed. */ - debug?:number; + debug?: number; /** * Allows to assign a debug port for debugging the application and breaking it on the first line. */ - debugBrk?:number; + debugBrk?: number; } export class Client implements IChannelClient, IDisposable { diff --git a/src/vs/base/parts/ipc/test/node/ipc.perf.ts b/src/vs/base/parts/ipc/test/node/ipc.perf.ts index 24f88b2bd71a3..c02ea404dcba4 100644 --- a/src/vs/base/parts/ipc/test/node/ipc.perf.ts +++ b/src/vs/base/parts/ipc/test/node/ipc.perf.ts @@ -43,21 +43,21 @@ suite('IPC performance', () => { ]; let i = 0, j = 0; const result = measure(service, 10, 10, 250) // warm-up - .then(() => { - return (function nextRun() { - if (i >= runs.length) { - if (++j >= dataSizes.length) { - return; + .then(() => { + return (function nextRun() { + if (i >= runs.length) { + if (++j >= dataSizes.length) { + return; + } + i = 0; } - i = 0; - } - const run = runs[i++]; - return measure(service, run.batches, run.size, dataSizes[j]) - .then(() => { - return nextRun(); - }); - })(); - }); + const run = runs[i++]; + return measure(service, run.batches, run.size, dataSizes[j]) + .then(() => { + return nextRun(); + }); + })(); + }); return always(result, () => client.dispose()); }); @@ -80,18 +80,18 @@ suite('IPC performance', () => { ]; let i = 0; const result = measure(service, 10, 10, 250) // warm-up - .then(() => { - return (function nextRun() { - if (i >= runs.length) { - return; - } - const run = runs[i++]; - return measure(service, run.batches, 1, run.dataSize) - .then(() => { - return nextRun(); - }); - })(); - }); + .then(() => { + return (function nextRun() { + if (i >= runs.length) { + return; + } + const run = runs[i++]; + return measure(service, run.batches, 1, run.dataSize) + .then(() => { + return nextRun(); + }); + })(); + }); return always(result, () => client.dispose()); }); @@ -101,14 +101,14 @@ suite('IPC performance', () => { let hits = 0; let count = 0; return service.batchPerf(batches, size, dataSize) - .then(() => { - console.log(`Batches: ${batches}, size: ${size}, dataSize: ${dataSize}, n: ${batches * size * dataSize}, duration: ${Date.now() - start}`); - assert.strictEqual(hits, batches); - assert.strictEqual(count, batches * size); - }, err => assert.fail(err), - batch => { - hits++; - count += batch.length; - }); + .then(() => { + console.log(`Batches: ${batches}, size: ${size}, dataSize: ${dataSize}, n: ${batches * size * dataSize}, duration: ${Date.now() - start}`); + assert.strictEqual(hits, batches); + assert.strictEqual(count, batches * size); + }, err => assert.fail(err), + batch => { + hits++; + count += batch.length; + }); } }); \ No newline at end of file diff --git a/src/vs/base/parts/ipc/test/node/testService.ts b/src/vs/base/parts/ipc/test/node/testService.ts index 1dd0def4f7000..71897c79dab67 100644 --- a/src/vs/base/parts/ipc/test/node/testService.ts +++ b/src/vs/base/parts/ipc/test/node/testService.ts @@ -15,7 +15,7 @@ export interface IMarcoPoloEvent { export interface ITestService { onMarco: Event; marco(): TPromise; - pong(ping:string): TPromise<{ incoming:string, outgoing:string }>; + pong(ping: string): TPromise<{ incoming: string, outgoing: string }>; cancelMe(): TPromise; batchPerf(batches: number, size: number, dataSize: number): PPromise; } @@ -32,7 +32,7 @@ export class TestService implements ITestService { return TPromise.as('polo'); } - pong(ping:string): TPromise<{ incoming:string, outgoing:string }> { + pong(ping: string): TPromise<{ incoming: string, outgoing: string }> { return TPromise.as({ incoming: ping, outgoing: 'pong' }); } @@ -41,7 +41,7 @@ export class TestService implements ITestService { } batchPerf(batches: number, size: number, dataSize: number): PPromise { - while(this._data.length < dataSize) { + while (this._data.length < dataSize) { this._data += this._data; } const self = this; @@ -104,7 +104,7 @@ export class TestServiceClient implements ITestService { return this.channel.call('marco'); } - pong(ping:string): TPromise<{ incoming:string, outgoing:string }> { + pong(ping: string): TPromise<{ incoming: string, outgoing: string }> { return this.channel.call('pong', ping); } diff --git a/src/vs/base/parts/quickopen/browser/quickOpenModel.ts b/src/vs/base/parts/quickopen/browser/quickOpenModel.ts index f3e3904462af1..18e6deabcbefe 100644 --- a/src/vs/base/parts/quickopen/browser/quickOpenModel.ts +++ b/src/vs/base/parts/quickopen/browser/quickOpenModel.ts @@ -6,21 +6,21 @@ 'use strict'; import nls = require('vs/nls'); -import {TPromise} from 'vs/base/common/winjs.base'; +import { TPromise } from 'vs/base/common/winjs.base'; import types = require('vs/base/common/types'); import URI from 'vs/base/common/uri'; -import {ITree, IElementCallback} from 'vs/base/parts/tree/browser/tree'; +import { ITree, IElementCallback } from 'vs/base/parts/tree/browser/tree'; import filters = require('vs/base/common/filters'); import strings = require('vs/base/common/strings'); import paths = require('vs/base/common/paths'); -import {IconLabel, IIconLabelOptions} from 'vs/base/browser/ui/iconLabel/iconLabel'; -import {IQuickNavigateConfiguration, IModel, IDataSource, IFilter, IAccessiblityProvider, IRenderer, IRunner, Mode} from 'vs/base/parts/quickopen/common/quickOpen'; -import {IActionProvider} from 'vs/base/parts/tree/browser/actionsRenderer'; -import {Action, IAction, IActionRunner} from 'vs/base/common/actions'; -import {compareAnything, compareByScore as doCompareByScore} from 'vs/base/common/comparers'; -import {ActionBar, IActionItem} from 'vs/base/browser/ui/actionbar/actionbar'; -import {LegacyRenderer, ILegacyTemplateData} from 'vs/base/parts/tree/browser/treeDefaults'; -import {HighlightedLabel} from 'vs/base/browser/ui/highlightedlabel/highlightedLabel'; +import { IconLabel, IIconLabelOptions } from 'vs/base/browser/ui/iconLabel/iconLabel'; +import { IQuickNavigateConfiguration, IModel, IDataSource, IFilter, IAccessiblityProvider, IRenderer, IRunner, Mode } from 'vs/base/parts/quickopen/common/quickOpen'; +import { IActionProvider } from 'vs/base/parts/tree/browser/actionsRenderer'; +import { Action, IAction, IActionRunner } from 'vs/base/common/actions'; +import { compareAnything, compareByScore as doCompareByScore } from 'vs/base/common/comparers'; +import { ActionBar, IActionItem } from 'vs/base/browser/ui/actionbar/actionbar'; +import { LegacyRenderer, ILegacyTemplateData } from 'vs/base/parts/tree/browser/treeDefaults'; +import { HighlightedLabel } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel'; import DOM = require('vs/base/browser/dom'); export interface IContext { @@ -591,7 +591,7 @@ class Renderer implements IRenderer { data.icon.className = iconClass; // Label - const options:IIconLabelOptions = entry.getLabelOptions() || Object.create(null); + const options: IIconLabelOptions = entry.getLabelOptions() || Object.create(null); options.matches = labelHighlights || []; data.label.setValue(entry.getLabel(), null, options); diff --git a/src/vs/base/parts/quickopen/browser/quickOpenViewer.ts b/src/vs/base/parts/quickopen/browser/quickOpenViewer.ts index ed31dbd93bfc6..ef143a5d41d5b 100644 --- a/src/vs/base/parts/quickopen/browser/quickOpenViewer.ts +++ b/src/vs/base/parts/quickopen/browser/quickOpenViewer.ts @@ -3,10 +3,10 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import {TPromise} from 'vs/base/common/winjs.base'; -import {isFunction} from 'vs/base/common/types'; -import {ITree, IRenderer, IFilter, IDataSource, IAccessibilityProvider} from 'vs/base/parts/tree/browser/tree'; -import {IModel} from 'vs/base/parts/quickopen/common/quickOpen'; +import { TPromise } from 'vs/base/common/winjs.base'; +import { isFunction } from 'vs/base/common/types'; +import { ITree, IRenderer, IFilter, IDataSource, IAccessibilityProvider } from 'vs/base/parts/tree/browser/tree'; +import { IModel } from 'vs/base/parts/quickopen/common/quickOpen'; export interface IModelProvider { getModel(): IModel; diff --git a/src/vs/base/parts/quickopen/browser/quickOpenWidget.ts b/src/vs/base/parts/quickopen/browser/quickOpenWidget.ts index 00d714c72d02b..30e3fdee311b3 100644 --- a/src/vs/base/parts/quickopen/browser/quickOpenWidget.ts +++ b/src/vs/base/parts/quickopen/browser/quickOpenWidget.ts @@ -6,27 +6,27 @@ import 'vs/css!./quickopen'; import nls = require('vs/nls'); -import {TPromise} from 'vs/base/common/winjs.base'; +import { TPromise } from 'vs/base/common/winjs.base'; import platform = require('vs/base/common/platform'); import browser = require('vs/base/browser/browser'); -import {EventType} from 'vs/base/common/events'; +import { EventType } from 'vs/base/common/events'; import types = require('vs/base/common/types'); import errors = require('vs/base/common/errors'); -import {IQuickNavigateConfiguration, IAutoFocus, IEntryRunContext, IModel, Mode} from 'vs/base/parts/quickopen/common/quickOpen'; -import {Filter, Renderer, DataSource, IModelProvider, AccessibilityProvider} from 'vs/base/parts/quickopen/browser/quickOpenViewer'; -import {Dimension, Builder, $} from 'vs/base/browser/builder'; -import {ISelectionEvent, IFocusEvent, ITree, ContextMenuEvent} from 'vs/base/parts/tree/browser/tree'; -import {InputBox, MessageType} from 'vs/base/browser/ui/inputbox/inputBox'; +import { IQuickNavigateConfiguration, IAutoFocus, IEntryRunContext, IModel, Mode } from 'vs/base/parts/quickopen/common/quickOpen'; +import { Filter, Renderer, DataSource, IModelProvider, AccessibilityProvider } from 'vs/base/parts/quickopen/browser/quickOpenViewer'; +import { Dimension, Builder, $ } from 'vs/base/browser/builder'; +import { ISelectionEvent, IFocusEvent, ITree, ContextMenuEvent } from 'vs/base/parts/tree/browser/tree'; +import { InputBox, MessageType } from 'vs/base/browser/ui/inputbox/inputBox'; import Severity from 'vs/base/common/severity'; -import {Tree} from 'vs/base/parts/tree/browser/treeImpl'; -import {ProgressBar} from 'vs/base/browser/ui/progressbar/progressbar'; -import {StandardKeyboardEvent} from 'vs/base/browser/keyboardEvent'; -import {DefaultController, ClickBehavior} from 'vs/base/parts/tree/browser/treeDefaults'; +import { Tree } from 'vs/base/parts/tree/browser/treeImpl'; +import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; +import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; +import { DefaultController, ClickBehavior } from 'vs/base/parts/tree/browser/treeDefaults'; import DOM = require('vs/base/browser/dom'); -import {IActionProvider} from 'vs/base/parts/tree/browser/actionsRenderer'; -import {KeyCode, KeyMod} from 'vs/base/common/keyCodes'; -import {IDisposable, dispose} from 'vs/base/common/lifecycle'; -import {ScrollbarVisibility} from 'vs/base/common/scrollable'; +import { IActionProvider } from 'vs/base/parts/tree/browser/actionsRenderer'; +import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; +import { ScrollbarVisibility } from 'vs/base/common/scrollable'; export interface IQuickOpenCallbacks { onOk: () => void; diff --git a/src/vs/base/parts/quickopen/common/quickOpen.ts b/src/vs/base/parts/quickopen/common/quickOpen.ts index a7fee71cb923e..ca6594e8c1bdf 100644 --- a/src/vs/base/parts/quickopen/common/quickOpen.ts +++ b/src/vs/base/parts/quickopen/common/quickOpen.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {Keybinding} from 'vs/base/common/keybinding'; +import { Keybinding } from 'vs/base/common/keybinding'; export interface IQuickNavigateConfiguration { keybindings: Keybinding[]; diff --git a/src/vs/base/parts/tree/browser/actionsRenderer.ts b/src/vs/base/parts/tree/browser/actionsRenderer.ts index f502eb38aa69b..8395b5022d9ad 100644 --- a/src/vs/base/parts/tree/browser/actionsRenderer.ts +++ b/src/vs/base/parts/tree/browser/actionsRenderer.ts @@ -19,31 +19,31 @@ var $ = Builder.$; export interface IActionProvider { - hasActions(tree:Tree.ITree, element:any):boolean; + hasActions(tree: Tree.ITree, element: any): boolean; ///

/// Returns whether or not the element has actions. These show up in place right /// to the element in the tree. /// - getActions(tree:Tree.ITree, element:any):WinJS.TPromise; + getActions(tree: Tree.ITree, element: any): WinJS.TPromise; /// /// Returns a promise of an array with the actions of the element that should show /// up in place right to the element in the tree. /// - hasSecondaryActions(tree:Tree.ITree, element:any):boolean; + hasSecondaryActions(tree: Tree.ITree, element: any): boolean; /// /// Returns whether or not the element has secondary actions. These show up once the /// user has expanded the element's action bar. /// - getSecondaryActions(tree:Tree.ITree, element:any):WinJS.TPromise; + getSecondaryActions(tree: Tree.ITree, element: any): WinJS.TPromise; /// /// Returns a promise of an array with the secondary actions of the element that should /// show up once the user has expanded the element's action bar. /// - getActionItem(tree:Tree.ITree, element:any, action:Actions.IAction):ActionBar.IActionItem; + getActionItem(tree: Tree.ITree, element: any, action: Actions.IAction): ActionBar.IActionItem; /// /// Returns an action item to render an action. /// @@ -59,7 +59,7 @@ export class ActionsRenderer extends TreeDefaults.LegacyRenderer implements Life private static CONTENTS_CLEANUP_FN_KEY: string = '__$ActionsRenderer.contentCleanupFn'; private static NO_OP = () => { /* noop */ }; - protected actionProvider:IActionProvider; + protected actionProvider: IActionProvider; protected actionRunner: Actions.IActionRunner; constructor(opts: IActionsRendererOptions) { @@ -68,11 +68,11 @@ export class ActionsRenderer extends TreeDefaults.LegacyRenderer implements Life this.actionRunner = opts.actionRunner; } - public getHeight(tree:Tree.ITree, element:any):number { + public getHeight(tree: Tree.ITree, element: any): number { return this.getContentHeight(tree, element); } - protected render(tree:Tree.ITree, element:any, container:HTMLElement, previousCleanupFn?: Tree.IElementCallback): Tree.IElementCallback { + protected render(tree: Tree.ITree, element: any, container: HTMLElement, previousCleanupFn?: Tree.IElementCallback): Tree.IElementCallback { try { Dom.clearNode(container); } catch (e) { @@ -136,15 +136,15 @@ export class ActionsRenderer extends TreeDefaults.LegacyRenderer implements Life return cleanupFn; } - /* protected */ public getContentHeight(tree:Tree.ITree, element:any):number { + /* protected */ public getContentHeight(tree: Tree.ITree, element: any): number { return 20; } - /* protected */ public renderContents(tree:Tree.ITree, element:any, container:HTMLElement, previousCleanupFn:Tree.IElementCallback):Tree.IElementCallback { + /* protected */ public renderContents(tree: Tree.ITree, element: any, container: HTMLElement, previousCleanupFn: Tree.IElementCallback): Tree.IElementCallback { return null; } - /* protected */ public getActionContext(tree:Tree.ITree, element:any):any { + /* protected */ public getActionContext(tree: Tree.ITree, element: any): any { return null; } diff --git a/src/vs/base/parts/tree/browser/tree.ts b/src/vs/base/parts/tree/browser/tree.ts index 5d5899bac2e1a..82fe76a9ec6c5 100644 --- a/src/vs/base/parts/tree/browser/tree.ts +++ b/src/vs/base/parts/tree/browser/tree.ts @@ -10,11 +10,11 @@ import Events = require('vs/base/common/eventEmitter'); import Mouse = require('vs/base/browser/mouseEvent'); import Keyboard = require('vs/base/browser/keyboardEvent'); import { INavigator } from 'vs/base/common/iterator'; -import {ScrollbarVisibility} from 'vs/base/common/scrollable'; +import { ScrollbarVisibility } from 'vs/base/common/scrollable'; export interface ITree extends Events.IEventEmitter { - emit(eventType:string, data?:any):void; + emit(eventType: string, data?: any): void; /** * Returns the tree's DOM element. @@ -122,7 +122,7 @@ export interface ITree extends Events.IEventEmitter { * Reveals an element in the tree. The relativeTop is a value between 0 and 1. The closer to 0 the more the * element will scroll up to the top. */ - reveal(element: any, relativeTop?:number): WinJS.Promise; + reveal(element: any, relativeTop?: number): WinJS.Promise; /** * Returns the relative top position of any given element, if visible. @@ -152,7 +152,7 @@ export interface ITree extends Events.IEventEmitter { * Sets the tree's highlight to be the given element. * Provide no arguments and it clears the tree's highlight. */ - setHighlight(element?: any, eventPayload?:any): void; + setHighlight(element?: any, eventPayload?: any): void; /** * Returns the currently highlighted element. @@ -167,47 +167,47 @@ export interface ITree extends Events.IEventEmitter { /** * Clears the highlight. */ - clearHighlight(eventPayload?:any): void; + clearHighlight(eventPayload?: any): void; /** * Selects an element. */ - select(element: any, eventPayload?:any): void; + select(element: any, eventPayload?: any): void; /** * Selects a range of elements. */ - selectRange(fromElement: any, toElement: any, eventPayload?:any): void; + selectRange(fromElement: any, toElement: any, eventPayload?: any): void; /** * Deselects a range of elements. */ - deselectRange(fromElement: any, toElement: any, eventPayload?:any): void; + deselectRange(fromElement: any, toElement: any, eventPayload?: any): void; /** * Selects several elements. */ - selectAll(elements: any[], eventPayload?:any): void; + selectAll(elements: any[], eventPayload?: any): void; /** * Deselects an element. */ - deselect(element: any, eventPayload?:any): void; + deselect(element: any, eventPayload?: any): void; /** * Deselects several elements. */ - deselectAll(elements: any[], eventPayload?:any): void; + deselectAll(elements: any[], eventPayload?: any): void; /** * Replaces the current selection with the given elements. */ - setSelection(elements: any[], eventPayload?:any): void; + setSelection(elements: any[], eventPayload?: any): void; /** * Toggles the element's selection. */ - toggleSelection(element: any, eventPayload?:any): void; + toggleSelection(element: any, eventPayload?: any): void; /** * Returns the currently selected elements. @@ -222,27 +222,27 @@ export interface ITree extends Events.IEventEmitter { /** * Selects the next `count`-nth element, in visible order. */ - selectNext(count?: number, clearSelection?: boolean, eventPayload?:any): void; + selectNext(count?: number, clearSelection?: boolean, eventPayload?: any): void; /** * Selects the previous `count`-nth element, in visible order. */ - selectPrevious(count?: number, clearSelection?: boolean, eventPayload?:any): void; + selectPrevious(count?: number, clearSelection?: boolean, eventPayload?: any): void; /** * Selects the currently selected element's parent. */ - selectParent(clearSelection?: boolean, eventPayload?:any): void; + selectParent(clearSelection?: boolean, eventPayload?: any): void; /** * Clears the selection. */ - clearSelection(eventPayload?:any): void; + clearSelection(eventPayload?: any): void; /** * Sets the focused element. */ - setFocus(element?: any, eventPayload?:any): void; + setFocus(element?: any, eventPayload?: any): void; /** * Returns whether an element is focused or not. @@ -257,12 +257,12 @@ export interface ITree extends Events.IEventEmitter { /** * Focuses the next `count`-nth element, in visible order. */ - focusNext(count?: number, eventPayload?:any): void; + focusNext(count?: number, eventPayload?: any): void; /** * Focuses the previous `count`-nth element, in visible order. */ - focusPrevious(count?: number, eventPayload?:any): void; + focusPrevious(count?: number, eventPayload?: any): void; /** * Focuses the currently focused element's parent. @@ -277,37 +277,37 @@ export interface ITree extends Events.IEventEmitter { /** * Focuses the second element, in visible order. */ - focusFirst(eventPayload?:any): void; + focusFirst(eventPayload?: any): void; /** * Focuses the nth element, in visible order. */ - focusNth(index:number, eventPayload?:any): void; + focusNth(index: number, eventPayload?: any): void; /** * Focuses the last element, in visible order. */ - focusLast(eventPayload?:any): void; + focusLast(eventPayload?: any): void; /** * Focuses the element at the end of the next page, in visible order. */ - focusNextPage(eventPayload?:any): void; + focusNextPage(eventPayload?: any): void; /** * Focuses the element at the beginning of the previous page, in visible order. */ - focusPreviousPage(eventPayload?:any): void; + focusPreviousPage(eventPayload?: any): void; /** * Clears the focus. */ - clearFocus(eventPayload?:any): void; + clearFocus(eventPayload?: any): void; /** * Adds the trait to elements. */ - addTraits(trait:string, elements: any[]): void; + addTraits(trait: string, elements: any[]): void; /** * Removes the trait from elements. @@ -566,18 +566,18 @@ export interface IDragAndDrop { /** * Sent when the drag operation is starting. */ - onDragStart(tree: ITree, data: IDragAndDropData, originalEvent:Mouse.DragMouseEvent): void; + onDragStart(tree: ITree, data: IDragAndDropData, originalEvent: Mouse.DragMouseEvent): void; /** * Returns a DragOverReaction indicating whether sources can be * dropped into target or some parent of the target. */ - onDragOver(tree: ITree, data: IDragAndDropData, targetElement: any, originalEvent:Mouse.DragMouseEvent): IDragOverReaction; + onDragOver(tree: ITree, data: IDragAndDropData, targetElement: any, originalEvent: Mouse.DragMouseEvent): IDragOverReaction; /** * Handles the action of dropping sources into target. */ - drop(tree: ITree, data: IDragAndDropData, targetElement: any, originalEvent:Mouse.DragMouseEvent): void; + drop(tree: ITree, data: IDragAndDropData, targetElement: any, originalEvent: Mouse.DragMouseEvent): void; } export interface IFilter { @@ -592,7 +592,7 @@ export interface IElementCallback { (tree: ITree, element: any): void; } -export type ICallback = ()=>void; +export type ICallback = () => void; export interface ISorter { @@ -637,9 +637,9 @@ export interface ITreeOptions { verticalScrollMode?: ScrollbarVisibility; alwaysFocused?: boolean; autoExpandSingleChildren?: boolean; - useShadows?:boolean; - paddingOnRow?:boolean; - ariaLabel?:string; + useShadows?: boolean; + paddingOnRow?: boolean; + ariaLabel?: string; } export interface ITreeContext extends ITreeConfiguration { diff --git a/src/vs/base/parts/tree/browser/treeDefaults.ts b/src/vs/base/parts/tree/browser/treeDefaults.ts index 3f2550e407b39..11449711b76ee 100644 --- a/src/vs/base/parts/tree/browser/treeDefaults.ts +++ b/src/vs/base/parts/tree/browser/treeDefaults.ts @@ -5,16 +5,16 @@ 'use strict'; import nls = require('vs/nls'); -import {TPromise} from 'vs/base/common/winjs.base'; -import {Action} from 'vs/base/common/actions'; +import { TPromise } from 'vs/base/common/winjs.base'; +import { Action } from 'vs/base/common/actions'; import platform = require('vs/base/common/platform'); import touch = require('vs/base/browser/touch'); import errors = require('vs/base/common/errors'); import dom = require('vs/base/browser/dom'); import mouse = require('vs/base/browser/mouseEvent'); -import {IKeyboardEvent} from 'vs/base/browser/keyboardEvent'; +import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import _ = require('vs/base/parts/tree/browser/tree'); -import {KeyCode, KeyMod} from 'vs/base/common/keyCodes'; +import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; export interface ILegacyTemplateData { root: HTMLElement; @@ -24,7 +24,7 @@ export interface ILegacyTemplateData { export class LegacyRenderer implements _.IRenderer { - public getHeight(tree:_.ITree, element:any):number { + public getHeight(tree: _.ITree, element: any): number { return 20; } @@ -33,7 +33,7 @@ export class LegacyRenderer implements _.IRenderer { } public renderTemplate(tree: _.ITree, templateId: string, container: HTMLElement): any { - return { + return { root: container, element: null, previousCleanupFn: null @@ -63,19 +63,19 @@ export class LegacyRenderer implements _.IRenderer { templateData.previousCleanupFn = null; } - protected render(tree:_.ITree, element:any, container:HTMLElement, previousCleanupFn?: _.IElementCallback):_.IElementCallback { + protected render(tree: _.ITree, element: any, container: HTMLElement, previousCleanupFn?: _.IElementCallback): _.IElementCallback { container.textContent = '' + element; return null; } } export interface IKeyBindingCallback { - (tree:_.ITree, event:IKeyboardEvent):void; + (tree: _.ITree, event: IKeyboardEvent): void; } export interface ICancelableEvent { - preventDefault():void; - stopPropagation():void; + preventDefault(): void; + stopPropagation(): void; } export enum ClickBehavior { @@ -92,7 +92,7 @@ export enum ClickBehavior { } export interface IControllerOptions { - clickBehavior?:ClickBehavior; + clickBehavior?: ClickBehavior; } interface IKeybindingDispatcherItem { @@ -108,14 +108,14 @@ export class KeybindingDispatcher { this._arr = []; } - public set(keybinding:number, callback:IKeyBindingCallback) { + public set(keybinding: number, callback: IKeyBindingCallback) { this._arr.push({ keybinding: keybinding, callback: callback }); } - public dispatch(keybinding:number): IKeyBindingCallback { + public dispatch(keybinding: number): IKeyBindingCallback { // Loop from the last to the first to handle overwrites for (let i = this._arr.length - 1; i >= 0; i--) { let item = this._arr[i]; @@ -132,9 +132,9 @@ export class DefaultController implements _.IController { protected downKeyBindingDispatcher: KeybindingDispatcher; protected upKeyBindingDispatcher: KeybindingDispatcher; - private options:IControllerOptions; + private options: IControllerOptions; - constructor(options:IControllerOptions = { clickBehavior: ClickBehavior.ON_MOUSE_UP }) { + constructor(options: IControllerOptions = { clickBehavior: ClickBehavior.ON_MOUSE_UP }) { this.options = options; this.downKeyBindingDispatcher = new KeybindingDispatcher(); @@ -152,7 +152,7 @@ export class DefaultController implements _.IController { this.upKeyBindingDispatcher.set(KeyMod.CtrlCmd | KeyCode.Enter, this.onEnter.bind(this)); } - public onMouseDown(tree:_.ITree, element: any, event:mouse.IMouseEvent, origin: string = 'mouse'):boolean { + public onMouseDown(tree: _.ITree, element: any, event: mouse.IMouseEvent, origin: string = 'mouse'): boolean { if (this.options.clickBehavior === ClickBehavior.ON_MOUSE_DOWN && event.leftButton) { if (event.target) { if (event.target.tagName && event.target.tagName.toLowerCase() === 'input') { @@ -171,7 +171,7 @@ export class DefaultController implements _.IController { return false; } - public onClick(tree:_.ITree, element: any, event:mouse.IMouseEvent):boolean { + public onClick(tree: _.ITree, element: any, event: mouse.IMouseEvent): boolean { var isMac = platform.isMacintosh; // A Ctrl click on the Mac is a context menu event @@ -196,7 +196,7 @@ export class DefaultController implements _.IController { return this.onLeftClick(tree, element, event); } - protected onLeftClick(tree:_.ITree, element: any, eventish:ICancelableEvent, origin: string = 'mouse'):boolean { + protected onLeftClick(tree: _.ITree, element: any, eventish: ICancelableEvent, origin: string = 'mouse'): boolean { var payload = { origin: origin, originalEvent: eventish }; if (tree.getInput() === element) { @@ -223,7 +223,7 @@ export class DefaultController implements _.IController { return true; } - public onContextMenu(tree:_.ITree, element: any, event:_.ContextMenuEvent):boolean { + public onContextMenu(tree: _.ITree, element: any, event: _.ContextMenuEvent): boolean { if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') { return false; // allow context menu on input fields } @@ -237,8 +237,8 @@ export class DefaultController implements _.IController { return false; } - public onTap(tree:_.ITree, element: any, event:touch.GestureEvent):boolean { - var target = event.initialTarget; + public onTap(tree: _.ITree, element: any, event: touch.GestureEvent): boolean { + var target = event.initialTarget; if (target && target.tagName && target.tagName.toLowerCase() === 'input') { return false; // Ignore event if target is a form input field (avoids browser specific issues) @@ -247,15 +247,15 @@ export class DefaultController implements _.IController { return this.onLeftClick(tree, element, event, 'touch'); } - public onKeyDown(tree:_.ITree, event:IKeyboardEvent):boolean { + public onKeyDown(tree: _.ITree, event: IKeyboardEvent): boolean { return this.onKey(this.downKeyBindingDispatcher, tree, event); } - public onKeyUp(tree:_.ITree, event:IKeyboardEvent):boolean { + public onKeyUp(tree: _.ITree, event: IKeyboardEvent): boolean { return this.onKey(this.upKeyBindingDispatcher, tree, event); } - private onKey(bindings:KeybindingDispatcher, tree:_.ITree, event:IKeyboardEvent):boolean { + private onKey(bindings: KeybindingDispatcher, tree: _.ITree, event: IKeyboardEvent): boolean { var handler = bindings.dispatch(event.asKeybinding()); if (handler) { if (handler(tree, event)) { @@ -267,7 +267,7 @@ export class DefaultController implements _.IController { return false; } - protected onUp(tree:_.ITree, event:IKeyboardEvent):boolean { + protected onUp(tree: _.ITree, event: IKeyboardEvent): boolean { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { @@ -279,7 +279,7 @@ export class DefaultController implements _.IController { return true; } - protected onPageUp(tree:_.ITree, event:IKeyboardEvent):boolean { + protected onPageUp(tree: _.ITree, event: IKeyboardEvent): boolean { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { @@ -291,7 +291,7 @@ export class DefaultController implements _.IController { return true; } - protected onDown(tree:_.ITree, event:IKeyboardEvent):boolean { + protected onDown(tree: _.ITree, event: IKeyboardEvent): boolean { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { @@ -303,7 +303,7 @@ export class DefaultController implements _.IController { return true; } - protected onPageDown(tree:_.ITree, event:IKeyboardEvent):boolean { + protected onPageDown(tree: _.ITree, event: IKeyboardEvent): boolean { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { @@ -315,7 +315,7 @@ export class DefaultController implements _.IController { return true; } - protected onLeft(tree:_.ITree, event:IKeyboardEvent):boolean { + protected onLeft(tree: _.ITree, event: IKeyboardEvent): boolean { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { @@ -332,7 +332,7 @@ export class DefaultController implements _.IController { return true; } - protected onRight(tree:_.ITree, event:IKeyboardEvent):boolean { + protected onRight(tree: _.ITree, event: IKeyboardEvent): boolean { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { @@ -349,7 +349,7 @@ export class DefaultController implements _.IController { return true; } - protected onEnter(tree:_.ITree, event:IKeyboardEvent):boolean { + protected onEnter(tree: _.ITree, event: IKeyboardEvent): boolean { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { @@ -362,7 +362,7 @@ export class DefaultController implements _.IController { return true; } - protected onSpace(tree:_.ITree, event:IKeyboardEvent):boolean { + protected onSpace(tree: _.ITree, event: IKeyboardEvent): boolean { if (tree.getHighlight()) { return false; } @@ -373,7 +373,7 @@ export class DefaultController implements _.IController { return true; } - protected onEscape(tree:_.ITree, event:IKeyboardEvent):boolean { + protected onEscape(tree: _.ITree, event: IKeyboardEvent): boolean { var payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { @@ -397,33 +397,33 @@ export class DefaultController implements _.IController { export class DefaultDragAndDrop implements _.IDragAndDrop { - public getDragURI(tree :_.ITree, element: any):string { + public getDragURI(tree: _.ITree, element: any): string { return null; } - public onDragStart(tree: _.ITree, data: _.IDragAndDropData, originalEvent: mouse.DragMouseEvent):void { + public onDragStart(tree: _.ITree, data: _.IDragAndDropData, originalEvent: mouse.DragMouseEvent): void { return; } - public onDragOver(tree: _.ITree, data: _.IDragAndDropData, targetElement: any, originalEvent: mouse.DragMouseEvent):_.IDragOverReaction { + public onDragOver(tree: _.ITree, data: _.IDragAndDropData, targetElement: any, originalEvent: mouse.DragMouseEvent): _.IDragOverReaction { return null; } - public drop(tree: _.ITree, data: _.IDragAndDropData, targetElement: any, originalEvent: mouse.DragMouseEvent):void { + public drop(tree: _.ITree, data: _.IDragAndDropData, targetElement: any, originalEvent: mouse.DragMouseEvent): void { return; } } export class DefaultFilter implements _.IFilter { - public isVisible(tree: _.ITree, element: any):boolean { + public isVisible(tree: _.ITree, element: any): boolean { return true; } } export class DefaultSorter implements _.ISorter { - public compare(tree: _.ITree, element: any, otherElement: any):number { + public compare(tree: _.ITree, element: any, otherElement: any): number { return 0; } } diff --git a/src/vs/base/parts/tree/browser/treeImpl.ts b/src/vs/base/parts/tree/browser/treeImpl.ts index 1031efb1a0a81..3ea5c7251b116 100644 --- a/src/vs/base/parts/tree/browser/treeImpl.ts +++ b/src/vs/base/parts/tree/browser/treeImpl.ts @@ -15,19 +15,19 @@ import { INavigator, MappedNavigator } from 'vs/base/common/iterator'; export class TreeContext implements _.ITreeContext { - public tree:_.ITree; - public configuration:_.ITreeConfiguration; - public options:_.ITreeOptions; - - public dataSource:_.IDataSource; - public renderer:_.IRenderer; - public controller:_.IController; - public dnd:_.IDragAndDrop; - public filter:_.IFilter; - public sorter:_.ISorter; - public accessibilityProvider:_.IAccessibilityProvider; - - constructor(tree:_.ITree, configuration:_.ITreeConfiguration, options:_.ITreeOptions = {}) { + public tree: _.ITree; + public configuration: _.ITreeConfiguration; + public options: _.ITreeOptions; + + public dataSource: _.IDataSource; + public renderer: _.IRenderer; + public controller: _.IController; + public dnd: _.IDragAndDrop; + public filter: _.IFilter; + public sorter: _.ISorter; + public accessibilityProvider: _.IAccessibilityProvider; + + constructor(tree: _.ITree, configuration: _.ITreeConfiguration, options: _.ITreeOptions = {}) { this.tree = tree; this.configuration = configuration; this.options = options; @@ -48,15 +48,15 @@ export class TreeContext implements _.ITreeContext { export class Tree extends Events.EventEmitter implements _.ITree { - private container:HTMLElement; - private configuration:_.ITreeConfiguration; - private options:_.ITreeOptions; + private container: HTMLElement; + private configuration: _.ITreeConfiguration; + private options: _.ITreeOptions; - private context:_.ITreeContext; - private model:Model.TreeModel; - private view:View.TreeView; + private context: _.ITreeContext; + private model: Model.TreeModel; + private view: View.TreeView; - constructor(container:HTMLElement, configuration:_.ITreeConfiguration, options:_.ITreeOptions = {}) { + constructor(container: HTMLElement, configuration: _.ITreeConfiguration, options: _.ITreeOptions = {}) { super(); this.container = container; @@ -83,7 +83,7 @@ export class Tree extends Events.EventEmitter implements _.ITree { return this.view.getHTMLElement(); } - public layout(height?:number): void { + public layout(height?: number): void { this.view.layout(height); } @@ -107,7 +107,7 @@ export class Tree extends Events.EventEmitter implements _.ITree { this.view.onHidden(); } - public setInput(element:any): WinJS.Promise { + public setInput(element: any): WinJS.Promise { return this.model.setInput(element); } @@ -115,39 +115,39 @@ export class Tree extends Events.EventEmitter implements _.ITree { return this.model.getInput(); } - public refresh(element:any = null, recursive = true): WinJS.Promise { + public refresh(element: any = null, recursive = true): WinJS.Promise { return this.model.refresh(element, recursive); } - public refreshAll(elements:any[], recursive = true): WinJS.Promise { + public refreshAll(elements: any[], recursive = true): WinJS.Promise { return this.model.refreshAll(elements, recursive); } - public expand(element:any):WinJS.Promise { + public expand(element: any): WinJS.Promise { return this.model.expand(element); } - public expandAll(elements:any[]):WinJS.Promise { + public expandAll(elements: any[]): WinJS.Promise { return this.model.expandAll(elements); } - public collapse(element:any, recursive:boolean = false):WinJS.Promise { + public collapse(element: any, recursive: boolean = false): WinJS.Promise { return this.model.collapse(element); } - public collapseAll(elements:any[] = null, recursive:boolean = false):WinJS.Promise { + public collapseAll(elements: any[] = null, recursive: boolean = false): WinJS.Promise { return this.model.collapseAll(elements, recursive); } - public toggleExpansion(element:any):WinJS.Promise { + public toggleExpansion(element: any): WinJS.Promise { return this.model.toggleExpansion(element); } - public toggleExpansionAll(elements:any[]):WinJS.Promise { + public toggleExpansionAll(elements: any[]): WinJS.Promise { return this.model.toggleExpansionAll(elements); } - public isExpanded(element:any):boolean { + public isExpanded(element: any): boolean { return this.model.isExpanded(element); } @@ -155,7 +155,7 @@ export class Tree extends Events.EventEmitter implements _.ITree { return this.model.getExpandedElements(); } - public reveal(element:any, relativeTop:number = null): WinJS.Promise { + public reveal(element: any, relativeTop: number = null): WinJS.Promise { return this.model.reveal(element, relativeTop); } @@ -176,55 +176,55 @@ export class Tree extends Events.EventEmitter implements _.ITree { return this.view.getTotalHeight(); } - public setHighlight(element?:any, eventPayload?:any):void { + public setHighlight(element?: any, eventPayload?: any): void { this.model.setHighlight(element, eventPayload); } - public getHighlight():any { + public getHighlight(): any { return this.model.getHighlight(); } - public isHighlighted(element:any):boolean { + public isHighlighted(element: any): boolean { return this.model.isFocused(element); } - public clearHighlight(eventPayload?:any): void { + public clearHighlight(eventPayload?: any): void { this.model.setHighlight(null, eventPayload); } - public select(element:any, eventPayload?:any): void { + public select(element: any, eventPayload?: any): void { this.model.select(element, eventPayload); } - public selectRange(fromElement: any, toElement: any, eventPayload?:any): void { + public selectRange(fromElement: any, toElement: any, eventPayload?: any): void { this.model.selectRange(fromElement, toElement, eventPayload); } - public deselectRange(fromElement: any, toElement: any, eventPayload?:any): void { + public deselectRange(fromElement: any, toElement: any, eventPayload?: any): void { this.model.deselectRange(fromElement, toElement, eventPayload); } - public selectAll(elements:any[], eventPayload?:any): void { + public selectAll(elements: any[], eventPayload?: any): void { this.model.selectAll(elements, eventPayload); } - public deselect(element:any, eventPayload?:any): void { + public deselect(element: any, eventPayload?: any): void { this.model.deselect(element, eventPayload); } - public deselectAll(elements:any[], eventPayload?:any): void { + public deselectAll(elements: any[], eventPayload?: any): void { this.model.deselectAll(elements, eventPayload); } - public setSelection(elements:any[], eventPayload?:any): void { + public setSelection(elements: any[], eventPayload?: any): void { this.model.setSelection(elements, eventPayload); } - public toggleSelection(element:any, eventPayload?:any): void { + public toggleSelection(element: any, eventPayload?: any): void { this.model.toggleSelection(element, eventPayload); } - public isSelected(element:any):boolean { + public isSelected(element: any): boolean { return this.model.isSelected(element); } @@ -232,27 +232,27 @@ export class Tree extends Events.EventEmitter implements _.ITree { return this.model.getSelection(); } - public clearSelection(eventPayload?:any): void { + public clearSelection(eventPayload?: any): void { this.model.setSelection([], eventPayload); } - public selectNext(count?:number, clearSelection?: boolean, eventPayload?:any): void { + public selectNext(count?: number, clearSelection?: boolean, eventPayload?: any): void { this.model.selectNext(count, clearSelection, eventPayload); } - public selectPrevious(count?:number, clearSelection?: boolean, eventPayload?:any): void { + public selectPrevious(count?: number, clearSelection?: boolean, eventPayload?: any): void { this.model.selectPrevious(count, clearSelection, eventPayload); } - public selectParent(clearSelection?: boolean, eventPayload?:any): void { + public selectParent(clearSelection?: boolean, eventPayload?: any): void { this.model.selectParent(clearSelection, eventPayload); } - public setFocus(element?:any, eventPayload?:any): void { + public setFocus(element?: any, eventPayload?: any): void { this.model.setFocus(element, eventPayload); } - public isFocused(element:any):boolean { + public isFocused(element: any): boolean { return this.model.isFocused(element); } @@ -260,47 +260,47 @@ export class Tree extends Events.EventEmitter implements _.ITree { return this.model.getFocus(); } - public focusNext(count?:number, eventPayload?:any): void { + public focusNext(count?: number, eventPayload?: any): void { this.model.focusNext(count, eventPayload); } - public focusPrevious(count?:number, eventPayload?:any): void { + public focusPrevious(count?: number, eventPayload?: any): void { this.model.focusPrevious(count, eventPayload); } - public focusParent(eventPayload?:any): void { + public focusParent(eventPayload?: any): void { this.model.focusParent(eventPayload); } - public focusFirstChild(eventPayload?:any): void { + public focusFirstChild(eventPayload?: any): void { this.model.focusFirstChild(eventPayload); } - public focusFirst(eventPayload?:any): void { + public focusFirst(eventPayload?: any): void { this.model.focusFirst(eventPayload); } - public focusNth(index:number, eventPayload?:any): void { + public focusNth(index: number, eventPayload?: any): void { this.model.focusNth(index, eventPayload); } - public focusLast(eventPayload?:any): void { + public focusLast(eventPayload?: any): void { this.model.focusLast(eventPayload); } - public focusNextPage(eventPayload?:any): void { + public focusNextPage(eventPayload?: any): void { this.view.focusNextPage(eventPayload); } - public focusPreviousPage(eventPayload?:any): void { + public focusPreviousPage(eventPayload?: any): void { this.view.focusPreviousPage(eventPayload); } - public clearFocus(eventPayload?:any): void { + public clearFocus(eventPayload?: any): void { this.model.setFocus(null, eventPayload); } - public addTraits(trait:string, elements: any[]): void { + public addTraits(trait: string, elements: any[]): void { this.model.addTraits(trait, elements); } diff --git a/src/vs/base/parts/tree/browser/treeModel.ts b/src/vs/base/parts/tree/browser/treeModel.ts index 68823423a5330..7bc735867baf0 100644 --- a/src/vs/base/parts/tree/browser/treeModel.ts +++ b/src/vs/base/parts/tree/browser/treeModel.ts @@ -14,8 +14,8 @@ import WinJS = require('vs/base/common/winjs.base'); import _ = require('./tree'); interface IMap { [id: string]: T; } -interface IItemMap extends IMap {} -interface ITraitMap extends IMap {} +interface IItemMap extends IMap { } +interface ITraitMap extends IMap { } export class LockData extends Events.EventEmitter { @@ -1250,7 +1250,7 @@ export class TreeModel extends Events.EventEmitter { } public addTraits(trait: string, elements: any[]): void { - var items: IItemMap = this.traitsToItems[trait] || {}; + var items: IItemMap = this.traitsToItems[trait] || {}; var item: Item; for (var i = 0, len = elements.length; i < len; i++) { item = this.getItem(elements[i]); @@ -1264,7 +1264,7 @@ export class TreeModel extends Events.EventEmitter { } public removeTraits(trait: string, elements: any[]): void { - var items: IItemMap = this.traitsToItems[trait] || {}; + var items: IItemMap = this.traitsToItems[trait] || {}; var item: Item; var id: string; @@ -1324,7 +1324,7 @@ export class TreeModel extends Events.EventEmitter { } } - var traitItems: IItemMap = this.traitsToItems[trait] || {}; + var traitItems: IItemMap = this.traitsToItems[trait] || {}; var itemsToRemoveTrait: Item[] = []; var id: string; diff --git a/src/vs/base/parts/tree/browser/treeView.ts b/src/vs/base/parts/tree/browser/treeView.ts index 689255f097ef0..7f0572ad9d336 100644 --- a/src/vs/base/parts/tree/browser/treeView.ts +++ b/src/vs/base/parts/tree/browser/treeView.ts @@ -18,11 +18,11 @@ import Model = require('vs/base/parts/tree/browser/treeModel'); import dnd = require('./treeDnd'); import { ArrayIterator, MappedIterator } from 'vs/base/common/iterator'; import { ScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement'; -import {ScrollbarVisibility} from 'vs/base/common/scrollable'; +import { ScrollbarVisibility } from 'vs/base/common/scrollable'; import { HeightMap } from 'vs/base/parts/tree/browser/treeViewModel'; import _ = require('vs/base/parts/tree/browser/tree'); import { IViewItem } from 'vs/base/parts/tree/browser/treeViewModel'; -import {KeyCode} from 'vs/base/common/keyCodes'; +import { KeyCode } from 'vs/base/common/keyCodes'; export interface IRow { element: HTMLElement; @@ -45,7 +45,7 @@ function removeFromParent(element: HTMLElement): void { export class RowCache implements Lifecycle.IDisposable { - private _cache: { [templateId:string]: IRow[]; }; + private _cache: { [templateId: string]: IRow[]; }; private scrollingRow: IRow; constructor(private context: _.ITreeContext) { @@ -57,7 +57,7 @@ export class RowCache implements Lifecycle.IDisposable { var result = this.cache(templateId).pop(); if (!result) { - var content = document.createElement('div'); + var content = document.createElement('div'); content.className = 'content'; var row = document.createElement('div'); @@ -146,7 +146,7 @@ export class ViewItem implements IViewItem { public top: number; public height: number; - public onDragStart: (e: DragEvent)=>void; + public onDragStart: (e: DragEvent) => void; public needsRender: boolean; public uri: string; @@ -260,7 +260,7 @@ export class ViewItem implements IViewItem { this.element.style.paddingLeft = this.context.options.twistiePixels + ((this.model.getDepth() - 1) * this.context.options.indentPixels) + 'px'; } else { this.element.style.paddingLeft = ((this.model.getDepth() - 1) * this.context.options.indentPixels) + 'px'; - ( this.row.element.firstElementChild).style.paddingLeft = this.context.options.twistiePixels + 'px'; + (this.row.element.firstElementChild).style.paddingLeft = this.context.options.twistiePixels + 'px'; } var uri = this.context.dnd.getDragURI(this.context.tree, this.model.getElement()); @@ -292,7 +292,7 @@ export class ViewItem implements IViewItem { this.row = this.context.cache.alloc(this.templateId); // used in reverse lookup from HTMLElement to Item - ( this.element)[TreeView.BINDING] = this; + (this.element)[TreeView.BINDING] = this; } if (this.element.parentElement) { @@ -325,7 +325,7 @@ export class ViewItem implements IViewItem { this.uri = null; - ( this.element)[TreeView.BINDING] = null; + (this.element)[TreeView.BINDING] = null; this.context.cache.release(this.templateId, this.row); this.row = null; } @@ -411,7 +411,7 @@ export class TreeView extends HeightMap { private scrollableElement: ScrollableElement; private wrapperGesture: Touch.Gesture; private msGesture: MSGesture; - private lastPointerType:string; + private lastPointerType: string; private lastClickTimeStamp: number = 0; private lastRenderTop: number; @@ -421,7 +421,7 @@ export class TreeView extends HeightMap { private items: { [id: string]: ViewItem; }; private isRefreshing = false; - private refreshingPreviousChildrenIds: { [id:string]:string[] } = {}; + private refreshingPreviousChildrenIds: { [id: string]: string[] } = {}; private dragAndDropListeners: { (): void; }[]; private currentDragAndDropData: _.IDragAndDropData; @@ -496,7 +496,7 @@ export class TreeView extends HeightMap { this.emit('scroll', e); // TODO@Joao: is anyone interested in this event? }); - if(Browser.isIE11orEarlier) { + if (Browser.isIE11orEarlier) { this.wrapper.style.msTouchAction = 'none'; this.wrapper.style.msContentZooming = 'none'; } else { @@ -520,12 +520,12 @@ export class TreeView extends HeightMap { this.viewListeners.push(DOM.addDisposableListener(this.wrapper, Touch.EventType.Tap, (e) => this.onTap(e))); this.viewListeners.push(DOM.addDisposableListener(this.wrapper, Touch.EventType.Change, (e) => this.onTouchChange(e))); - if(Browser.isIE11orEarlier) { + if (Browser.isIE11orEarlier) { this.viewListeners.push(DOM.addDisposableListener(this.wrapper, 'MSPointerDown', (e) => this.onMsPointerDown(e))); this.viewListeners.push(DOM.addDisposableListener(this.wrapper, 'MSGestureTap', (e) => this.onMsGestureTap(e))); // these events come too fast, we throttle them - this.viewListeners.push(DOM.addDisposableThrottledListener(this.wrapper, 'MSGestureChange', (e) => this.onThrottledMsGestureChange(e), (lastEvent:IThrottledGestureEvent, event:MSGestureEvent): IThrottledGestureEvent => { + this.viewListeners.push(DOM.addDisposableThrottledListener(this.wrapper, 'MSGestureChange', (e) => this.onThrottledMsGestureChange(e), (lastEvent: IThrottledGestureEvent, event: MSGestureEvent): IThrottledGestureEvent => { event.stopPropagation(); event.preventDefault(); @@ -596,7 +596,7 @@ export class TreeView extends HeightMap { } private setupMSGesture(): void { - if((window).MSGesture) { + if ((window).MSGesture) { this.msGesture = new MSGesture(); setTimeout(() => this.msGesture.target = this.wrapper, 100); // TODO@joh, TODO@IETeam } @@ -628,22 +628,22 @@ export class TreeView extends HeightMap { // when view scrolls down, start rendering from the renderBottom for (i = this.indexAfter(renderBottom) - 1, stop = this.indexAt(Math.max(thisRenderBottom, renderTop)); i >= stop; i--) { - this.insertItemInDOM( this.itemAtIndex(i)); + this.insertItemInDOM(this.itemAtIndex(i)); } // when view scrolls up, start rendering from either this.renderTop or renderBottom for (i = Math.min(this.indexAt(this.lastRenderTop), this.indexAfter(renderBottom)) - 1, stop = this.indexAt(renderTop); i >= stop; i--) { - this.insertItemInDOM( this.itemAtIndex(i)); + this.insertItemInDOM(this.itemAtIndex(i)); } // when view scrolls down, start unrendering from renderTop for (i = this.indexAt(this.lastRenderTop), stop = Math.min(this.indexAt(renderTop), this.indexAfter(thisRenderBottom)); i < stop; i++) { - this.removeItemFromDOM( this.itemAtIndex(i)); + this.removeItemFromDOM(this.itemAtIndex(i)); } // when view scrolls up, start unrendering from either renderBottom this.renderTop for (i = Math.max(this.indexAfter(renderBottom), this.indexAt(this.lastRenderTop)), stop = this.indexAfter(thisRenderBottom); i < stop; i++) { - this.removeItemFromDOM( this.itemAtIndex(i)); + this.removeItemFromDOM(this.itemAtIndex(i)); } var topItem = this.itemAtIndex(this.indexAt(renderTop)); @@ -663,7 +663,7 @@ export class TreeView extends HeightMap { this.modelListeners.push(this.model.addBulkListener2((e) => this.onModelEvents(e))); } - private onModelEvents(events:any[]): void { + private onModelEvents(events: any[]): void { var elementsToRefresh: Model.Item[] = []; for (var i = 0, len = events.length; i < len; i++) { @@ -738,7 +738,7 @@ export class TreeView extends HeightMap { this.scrollTop = scrollTop; } - public focusNextPage(eventPayload?:any): void { + public focusNextPage(eventPayload?: any): void { var lastPageIndex = this.indexAt(this.scrollTop + this.viewHeight); lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1; var lastPageElement = this.itemAtIndex(lastPageIndex).model.getElement(); @@ -760,8 +760,8 @@ export class TreeView extends HeightMap { } } - public focusPreviousPage(eventPayload?:any): void { - var firstPageIndex:number; + public focusPreviousPage(eventPayload?: any): void { + var firstPageIndex: number; if (this.scrollTop === 0) { firstPageIndex = this.indexAt(this.scrollTop); @@ -811,33 +811,33 @@ export class TreeView extends HeightMap { } public getScrollPosition(): number { - const height = this.getTotalHeight() - this.viewHeight; + const height = this.getTotalHeight() - this.viewHeight; return height <= 0 ? 0 : this.scrollTop / height; } public setScrollPosition(pos: number): void { - const height = this.getTotalHeight() - this.viewHeight; + const height = this.getTotalHeight() - this.viewHeight; this.scrollTop = height * pos; } // Events - private onClearingInput(e:Model.IInputEvent): void { - var item = e.item; + private onClearingInput(e: Model.IInputEvent): void { + var item = e.item; if (item) { this.onRemoveItems(new MappedIterator(item.getNavigator(), item => item && item.id)); this.onRowsChanged(); } } - private onSetInput(e:Model.IInputEvent): void { + private onSetInput(e: Model.IInputEvent): void { this.context.cache.garbageCollect(); - this.inputItem = new RootViewItem(this.context, e.item, this.wrapper); + this.inputItem = new RootViewItem(this.context, e.item, this.wrapper); this.emit('viewItem:create', { item: this.inputItem.model }); } - private onItemChildrenRefreshing(e:Model.IItemChildrenRefreshEvent): void { - var item = e.item; + private onItemChildrenRefreshing(e: Model.IItemChildrenRefreshEvent): void { + var item = e.item; var viewItem = this.items[item.id]; if (viewItem) { @@ -860,8 +860,8 @@ export class TreeView extends HeightMap { } } - private onItemChildrenRefreshed(e:Model.IItemChildrenRefreshEvent): void { - var item = e.item; + private onItemChildrenRefreshed(e: Model.IItemChildrenRefreshEvent): void { + var item = e.item; var viewItem = this.items[item.id]; if (viewItem) { @@ -890,11 +890,11 @@ export class TreeView extends HeightMap { if (!skipDiff) { const lcs = new Diff.LcsDiff({ getLength: () => previousChildrenIds.length, - getElementHash: (i:number) => previousChildrenIds[i] + getElementHash: (i: number) => previousChildrenIds[i] }, { - getLength: () => afterModelItems.length, - getElementHash: (i:number) => afterModelItems[i].id - }, null); + getLength: () => afterModelItems.length, + getElementHash: (i: number) => afterModelItems[i].id + }, null); diff = lcs.ComputeDiff(); @@ -943,20 +943,20 @@ export class TreeView extends HeightMap { } } - private onItemsRefresh(items:Model.Item[]): void { + private onItemsRefresh(items: Model.Item[]): void { this.onRefreshItemSet(items.filter(item => this.items.hasOwnProperty(item.id))); this.onRowsChanged(); } - private onItemExpanding(e:Model.IItemExpandEvent): void { + private onItemExpanding(e: Model.IItemExpandEvent): void { var viewItem = this.items[e.item.id]; if (viewItem) { viewItem.expanded = true; } } - private onItemExpanded(e:Model.IItemExpandEvent): void { - var item = e.item; + private onItemExpanded(e: Model.IItemExpandEvent): void { + var item = e.item; var viewItem = this.items[item.id]; if (viewItem) { viewItem.expanded = true; @@ -972,8 +972,8 @@ export class TreeView extends HeightMap { } } - private onItemCollapsing(e:Model.IItemCollapseEvent): void { - var item = e.item; + private onItemCollapsing(e: Model.IItemCollapseEvent): void { + var item = e.item; var viewItem = this.items[item.id]; if (viewItem) { viewItem.expanded = false; @@ -992,9 +992,9 @@ export class TreeView extends HeightMap { return -1; } - private onItemReveal(e:Model.IItemRevealEvent): void { - var item = e.item; - var relativeTop = e.relativeTop; + private onItemReveal(e: Model.IItemRevealEvent): void { + var item = e.item; + var relativeTop = e.relativeTop; var viewItem = this.items[item.id]; if (viewItem) { if (relativeTop !== null) { @@ -1017,9 +1017,9 @@ export class TreeView extends HeightMap { } } - private onItemAddTrait(e:Model.IItemTraitEvent): void { - var item = e.item; - var trait = e.trait; + private onItemAddTrait(e: Model.IItemTraitEvent): void { + var item = e.item; + var trait = e.trait; var viewItem = this.items[item.id]; if (viewItem) { viewItem.addClass(trait); @@ -1037,9 +1037,9 @@ export class TreeView extends HeightMap { } } - private onItemRemoveTrait(e:Model.IItemTraitEvent): void { - var item = e.item; - var trait = e.trait; + private onItemRemoveTrait(e: Model.IItemTraitEvent): void { + var item = e.item; + var trait = e.trait; var viewItem = this.items[item.id]; if (viewItem) { viewItem.removeClass(trait); @@ -1077,7 +1077,7 @@ export class TreeView extends HeightMap { this.items[item.id] = item; } - public onRefreshItem(item: ViewItem, needsRender= false): void { + public onRefreshItem(item: ViewItem, needsRender = false): void { item.needsRender = item.needsRender || needsRender; this.refreshViewItem(item); } @@ -1105,7 +1105,7 @@ export class TreeView extends HeightMap { // DOM Events - private onClick(e:MouseEvent): void { + private onClick(e: MouseEvent): void { if (this.lastPointerType && this.lastPointerType !== 'mouse') { return; } @@ -1117,7 +1117,7 @@ export class TreeView extends HeightMap { return; } - if(Browser.isIE10orLater && Date.now() - this.lastClickTimeStamp < 300) { + if (Browser.isIE10orLater && Date.now() - this.lastClickTimeStamp < 300) { // IE10+ doesn't set the detail property correctly. While IE10 simply // counts the number of clicks, IE11 reports always 1. To align with // other browser, we set the value to 2 if clicks events come in a 300ms @@ -1129,7 +1129,7 @@ export class TreeView extends HeightMap { this.context.controller.onClick(this.context.tree, item.model.getElement(), event); } - private onMouseDown(e:MouseEvent): void { + private onMouseDown(e: MouseEvent): void { this.didJustPressContextMenuKey = false; if (!this.context.controller.onMouseDown) { @@ -1155,7 +1155,7 @@ export class TreeView extends HeightMap { this.context.controller.onMouseDown(this.context.tree, item.model.getElement(), event); } - private onMouseUp(e:MouseEvent): void { + private onMouseUp(e: MouseEvent): void { if (!this.context.controller.onMouseUp) { return; } @@ -1179,8 +1179,8 @@ export class TreeView extends HeightMap { this.context.controller.onMouseUp(this.context.tree, item.model.getElement(), event); } - private onTap(e:Touch.GestureEvent): void { - var item = this.getItemAround( e.initialTarget); + private onTap(e: Touch.GestureEvent): void { + var item = this.getItemAround(e.initialTarget); if (!item) { return; @@ -1189,7 +1189,7 @@ export class TreeView extends HeightMap { this.context.controller.onTap(this.context.tree, item.model.getElement(), e); } - private onTouchChange(event:Touch.GestureEvent): void { + private onTouchChange(event: Touch.GestureEvent): void { event.preventDefault(); event.stopPropagation(); @@ -1218,8 +1218,8 @@ export class TreeView extends HeightMap { resultEvent = new _.KeyboardContextMenuEvent(position.left + position.width, position.top, keyboardEvent); - } else { - var mouseEvent = new Mouse.StandardMouseEvent( event); + } else { + var mouseEvent = new Mouse.StandardMouseEvent(event); var item = this.getItemAround(mouseEvent.target); if (!item) { @@ -1233,7 +1233,7 @@ export class TreeView extends HeightMap { this.context.controller.onContextMenu(this.context.tree, element, resultEvent); } - private onKeyDown(e:KeyboardEvent): void { + private onKeyDown(e: KeyboardEvent): void { var event = new Keyboard.StandardKeyboardEvent(e); this.didJustPressContextMenuKey = event.keyCode === KeyCode.ContextMenu || (event.shiftKey && event.keyCode === KeyCode.F10); @@ -1250,7 +1250,7 @@ export class TreeView extends HeightMap { this.context.controller.onKeyDown(this.context.tree, event); } - private onKeyUp(e:KeyboardEvent): void { + private onKeyUp(e: KeyboardEvent): void { if (this.didJustPressContextMenuKey) { this.onContextMenu(e); } @@ -1259,7 +1259,7 @@ export class TreeView extends HeightMap { this.context.controller.onKeyUp(this.context.tree, new Keyboard.StandardKeyboardEvent(e)); } - private onDragStart(item: ViewItem, e:any): void { + private onDragStart(item: ViewItem, e: any): void { if (this.model.getHighlight()) { return; } @@ -1276,7 +1276,7 @@ export class TreeView extends HeightMap { e.dataTransfer.effectAllowed = 'copyMove'; e.dataTransfer.setData('URL', item.uri); - if(e.dataTransfer.setDragImage) { + if (e.dataTransfer.setDragImage) { let label: string; if (this.context.dnd.getDragLabel) { @@ -1346,7 +1346,7 @@ export class TreeView extends HeightMap { } } - private onDragOver(e:DragEvent): boolean { + private onDragOver(e: DragEvent): boolean { var event = new Mouse.DragMouseEvent(e); var viewItem = this.getItemAround(event.target); @@ -1477,7 +1477,7 @@ export class TreeView extends HeightMap { return true; } - private onDrop(e:DragEvent): void { + private onDrop(e: DragEvent): void { if (this.currentDropElement) { var event = new Mouse.DragMouseEvent(e); event.preventDefault(); @@ -1488,7 +1488,7 @@ export class TreeView extends HeightMap { this.cancelDragAndDropScrollInterval(); } - private onDragEnd(e:DragEvent): void { + private onDragEnd(e: DragEvent): void { if (this.currentDropTarget) { this.currentDropTargets.forEach(i => i.dropTarget = false); this.currentDropTargets = []; @@ -1523,7 +1523,7 @@ export class TreeView extends HeightMap { // MS specific DOM Events - private onMsPointerDown(event: MSPointerEvent):void { + private onMsPointerDown(event: MSPointerEvent): void { if (!this.msGesture) { return; } @@ -1545,20 +1545,20 @@ export class TreeView extends HeightMap { this.msGesture.addPointer(event.pointerId); } - private onThrottledMsGestureChange(event: IThrottledGestureEvent):void { + private onThrottledMsGestureChange(event: IThrottledGestureEvent): void { this.scrollTop -= event.translationY; } - private onMsGestureTap(event:MSGestureEvent):void { - ( event).initialTarget = document.elementFromPoint(event.clientX, event.clientY); - this.onTap( event); + private onMsGestureTap(event: MSGestureEvent): void { + (event).initialTarget = document.elementFromPoint(event.clientX, event.clientY); + this.onTap(event); } // DOM changes private insertItemInDOM(item: ViewItem): void { var elementAfter: HTMLElement = null; - var itemAfter = this.itemAfter(item); + var itemAfter = this.itemAfter(item); if (itemAfter && itemAfter.element) { elementAfter = itemAfter.element; @@ -1578,10 +1578,10 @@ export class TreeView extends HeightMap { } private getItemAround(element: HTMLElement): ViewItem { - var candidate:ViewItem = this.inputItem; + var candidate: ViewItem = this.inputItem; do { - if (( element)[TreeView.BINDING]) { - candidate = ( element)[TreeView.BINDING]; + if ((element)[TreeView.BINDING]) { + candidate = (element)[TreeView.BINDING]; } if (element === this.wrapper || element === this.domNode) { diff --git a/src/vs/base/parts/tree/browser/treeViewModel.ts b/src/vs/base/parts/tree/browser/treeViewModel.ts index e950653ef6338..e3121cc2837a3 100644 --- a/src/vs/base/parts/tree/browser/treeViewModel.ts +++ b/src/vs/base/parts/tree/browser/treeViewModel.ts @@ -143,7 +143,7 @@ export class HeightMap extends EventEmitter { var item: Item; var viewItem: IViewItem; var newHeight: number; - var i: number, j:number = null; + var i: number, j: number = null; var cummDiff = 0; while (item = iterator.next()) { @@ -174,7 +174,7 @@ export class HeightMap extends EventEmitter { } } - public onRefreshItem(item:IViewItem, needsRender:boolean=false): void { + public onRefreshItem(item: IViewItem, needsRender: boolean = false): void { // noop } @@ -186,7 +186,7 @@ export class HeightMap extends EventEmitter { return this.heightMap[this.indexAt(position)].model.id; } - public withItemsInRange(start: number, end: number, fn: (item: string) =>void ): void { + public withItemsInRange(start: number, end: number, fn: (item: string) => void): void { start = this.indexAt(start); end = this.indexAt(end); for (var i = start; i <= end; i++) { diff --git a/src/vs/base/parts/tree/test/browser/treeModel.test.ts b/src/vs/base/parts/tree/test/browser/treeModel.test.ts index de245ea490ad0..aad5d56d60bd3 100644 --- a/src/vs/base/parts/tree/test/browser/treeModel.test.ts +++ b/src/vs/base/parts/tree/test/browser/treeModel.test.ts @@ -16,7 +16,7 @@ import TreeDefaults = require('vs/base/parts/tree/browser/treeDefaults'); export class FakeRenderer { - public getHeight(tree:_.ITree, element:any):number { + public getHeight(tree: _.ITree, element: any): number { return 20; } @@ -39,16 +39,16 @@ export class FakeRenderer { class TreeContext implements _.ITreeContext { - public tree:_.ITree = null; - public options:_.ITreeOptions = { autoExpandSingleChildren: true }; - public dataSource:_.IDataSource; - public renderer:_.IRenderer; - public controller:_.IController; - public dnd:_.IDragAndDrop; - public filter:_.IFilter; - public sorter:_.ISorter; + public tree: _.ITree = null; + public options: _.ITreeOptions = { autoExpandSingleChildren: true }; + public dataSource: _.IDataSource; + public renderer: _.IRenderer; + public controller: _.IController; + public dnd: _.IDragAndDrop; + public filter: _.IFilter; + public sorter: _.ISorter; - constructor(public configuration:_.ITreeConfiguration) { + constructor(public configuration: _.ITreeConfiguration) { this.dataSource = configuration.dataSource; this.renderer = configuration.renderer || new FakeRenderer(); this.controller = configuration.controller; @@ -60,7 +60,7 @@ class TreeContext implements _.ITreeContext { class TreeModel extends model.TreeModel { - constructor(configuration:_.ITreeConfiguration) { + constructor(configuration: _.ITreeConfiguration) { super(new TreeContext(configuration)); } } @@ -75,7 +75,7 @@ class EventCounter { this._count = 0; } - public listen(emitter: ee.IEventEmitter, event: string, fn:(e)=>void = null): ()=>void { + public listen(emitter: ee.IEventEmitter, event: string, fn: (e) => void = null): () => void { let r = emitter.addListener2(event, (e) => { this._count++; fn && fn(e); @@ -106,64 +106,82 @@ class EventCounter { } } -var SAMPLE:any = { +var SAMPLE: any = { ONE: { id: 'one' }, - AB:{ id: 'ROOT', children: [ - { id: 'a', children: [ - { id: 'aa' }, - { id: 'ab' } - ]}, - { id: 'b' }, - { id: 'c', children: [ - { id: 'ca' }, - { id: 'cb' } - ] } - ]}, - - DEEP: { id: 'ROOT', children: [ - { id: 'a', children: [ - { id: 'x', children: [ - { id: 'xa' }, - { id: 'xb' }, - ]} - ]}, - { id: 'b' } - ]}, - - DEEP2: { id: 'ROOT', children: [ - { id: 'a', children: [ - { id: 'x', children: [ - { id: 'xa' }, - { id: 'xb' }, - ]}, - { id: 'y' } - ]}, - { id: 'b' } - ]} + AB: { + id: 'ROOT', children: [ + { + id: 'a', children: [ + { id: 'aa' }, + { id: 'ab' } + ] + }, + { id: 'b' }, + { + id: 'c', children: [ + { id: 'ca' }, + { id: 'cb' } + ] + } + ] + }, + + DEEP: { + id: 'ROOT', children: [ + { + id: 'a', children: [ + { + id: 'x', children: [ + { id: 'xa' }, + { id: 'xb' }, + ] + } + ] + }, + { id: 'b' } + ] + }, + + DEEP2: { + id: 'ROOT', children: [ + { + id: 'a', children: [ + { + id: 'x', children: [ + { id: 'xa' }, + { id: 'xb' }, + ] + }, + { id: 'y' } + ] + }, + { id: 'b' } + ] + } }; class TestDataSource implements _.IDataSource { - public getId(tree, element):string { + public getId(tree, element): string { return element.id; } - public hasChildren(tree, element):boolean { + public hasChildren(tree, element): boolean { return !!element.children; } - public getChildren(tree, element):WinJS.Promise { + public getChildren(tree, element): WinJS.Promise { return WinJS.TPromise.as(element.children); } - public getParent(tree, element):WinJS.Promise { + public getParent(tree, element): WinJS.Promise { throw new Error('Not implemented'); } } suite('TreeModel', () => { - var model:model.TreeModel; - var counter:EventCounter; + var model: model.TreeModel; + var counter: EventCounter; setup(() => { counter = new EventCounter(); @@ -190,7 +208,7 @@ suite('TreeModel', () => { counter.listen(model, 'item:childrenRefreshing'); // 1 counter.listen(model, 'item:childrenRefreshed'); // 1 return model.refresh(null); - }).done(() =>{ + }).done(() => { assert.equal(counter.count, 8); done(); }); @@ -204,7 +222,7 @@ suite('TreeModel', () => { counter.listen(model, 'item:childrenRefreshing'); // 1 counter.listen(model, 'item:childrenRefreshed'); // 1 return model.refresh(SAMPLE.AB); - }).done(() =>{ + }).done(() => { assert.equal(counter.count, 8); done(); }); @@ -218,7 +236,7 @@ suite('TreeModel', () => { counter.listen(model, 'item:childrenRefreshing'); // 1 counter.listen(model, 'item:childrenRefreshed'); // 1 return model.refresh(SAMPLE.AB, false); - }).done(() =>{ + }).done(() => { assert.equal(counter.count, 5); done(); }); @@ -232,7 +250,7 @@ suite('TreeModel', () => { counter.listen(model, 'item:childrenRefreshing'); // 0 counter.listen(model, 'item:childrenRefreshed'); // 0 return model.refresh(SAMPLE.AB.children[0]); - }).done(() =>{ + }).done(() => { assert.equal(counter.count, 3); done(); }); @@ -248,7 +266,7 @@ suite('TreeModel', () => { counter.listen(model, 'item:childrenRefreshing'); // 1 counter.listen(model, 'item:childrenRefreshed'); // 1 return model.refresh(SAMPLE.AB.children[0]); - }).done(() =>{ + }).done(() => { assert.equal(counter.count, 7); done(); }); @@ -267,7 +285,7 @@ suite('TreeModel', () => { counter.listen(model, 'item:childrenRefreshing'); // 1 counter.listen(model, 'item:childrenRefreshed'); // 1 return model.refresh(SAMPLE.AB.children[0], false); - }).done(() =>{ + }).done(() => { assert.equal(counter.count, 6); done(); }); @@ -285,7 +303,7 @@ suite('TreeModel', () => { counter.listen(model, 'item:childrenRefreshed'); // 2 return model.refreshAll([SAMPLE.AB.children[0], SAMPLE.AB.children[1], SAMPLE.AB.children[2]]); - }).done(() =>{ + }).done(() => { assert.equal(counter.count, 17); done(); }); @@ -303,7 +321,7 @@ suite('TreeModel', () => { counter.listen(model, 'item:childrenRefreshed'); // 2 return model.refreshAll([SAMPLE.AB.children[0], SAMPLE.AB.children[1], SAMPLE.AB.children[2]], false); - }).done(() =>{ + }).done(() => { assert.equal(counter.count, 13); done(); }); @@ -329,7 +347,7 @@ suite('TreeModel', () => { }); return model.refresh(); - }).done(() =>{ + }).done(() => { assert.equal(counter.count, 16); done(); }); @@ -340,7 +358,7 @@ suite('TreeModel', () => { model.expandAll(['a', 'c']); // going internals - var r = ( model).registry; + var r = (model).registry; assert(r.getItem('a').intersects(r.getItem('a'))); assert(r.getItem('a').intersects(r.getItem('aa'))); @@ -359,8 +377,8 @@ suite('TreeModel', () => { }); suite('TreeModel - TreeNavigator', () => { - var model:model.TreeModel; - var counter:EventCounter; + var model: model.TreeModel; + var counter: EventCounter; setup(() => { counter = new EventCounter(); @@ -539,8 +557,8 @@ suite('TreeModel - TreeNavigator', () => { }); suite('TreeModel - Expansion', () => { - var model:model.TreeModel; - var counter:EventCounter; + var model: model.TreeModel; + var counter: EventCounter; setup(() => { counter = new EventCounter(); @@ -665,12 +683,12 @@ suite('TreeModel - Expansion', () => { assert.equal(nav.next().id, 'c'); assert.equal(nav.next() && false, null); - var f:()=>void = counter.listen(model, 'item:childrenRefreshing', (e) => { + var f: () => void = counter.listen(model, 'item:childrenRefreshing', (e) => { assert.equal(e.item.id, 'a'); f(); }); - var g:()=>void = counter.listen(model, 'item:childrenRefreshed', (e) => { + var g: () => void = counter.listen(model, 'item:childrenRefreshed', (e) => { assert.equal(e.item.id, 'a'); g(); }); @@ -711,21 +729,21 @@ suite('TreeModel - Expansion', () => { class TestFilter implements _.IFilter { - public fn:(any)=>boolean; + public fn: (any) => boolean; constructor() { this.fn = () => true; } - public isVisible(tree, element):boolean { + public isVisible(tree, element): boolean { return this.fn(element); } } suite('TreeModel - Filter', () => { - var model:model.TreeModel; - var counter:EventCounter; - var filter:TestFilter; + var model: model.TreeModel; + var counter: EventCounter; + var filter: TestFilter; setup(() => { counter = new EventCounter(); @@ -872,8 +890,8 @@ suite('TreeModel - Filter', () => { }); suite('TreeModel - Traits', () => { - var model:model.TreeModel; - var counter:EventCounter; + var model: model.TreeModel; + var counter: EventCounter; setup(() => { counter = new EventCounter(); @@ -1104,8 +1122,8 @@ suite('TreeModel - Traits', () => { class DynamicModel extends Events.EventEmitter implements _.IDataSource { - private data:any; - public promiseFactory:{ ():WinJS.Promise; }; + private data: any; + public promiseFactory: { (): WinJS.Promise; }; constructor() { super(); @@ -1137,15 +1155,15 @@ class DynamicModel extends Events.EventEmitter implements _.IDataSource { this.addChild(parent, newName); } - public getId(tree, element):string { + public getId(tree, element): string { return element; } - public hasChildren(tree, element):boolean { + public hasChildren(tree, element): boolean { return !!this.data[element]; } - public getChildren(tree, element):WinJS.Promise { + public getChildren(tree, element): WinJS.Promise { this.emit('getChildren', element); var result = this.promiseFactory ? this.promiseFactory() : WinJS.TPromise.as(null); return result.then(() => { @@ -1154,15 +1172,15 @@ class DynamicModel extends Events.EventEmitter implements _.IDataSource { }); } - public getParent(tree, element):WinJS.Promise { + public getParent(tree, element): WinJS.Promise { throw new Error('Not implemented'); } } suite('TreeModel - Dynamic data model', () => { - var model:model.TreeModel; - var dataModel:DynamicModel; - var counter:EventCounter; + var model: model.TreeModel; + var dataModel: DynamicModel; + var counter: EventCounter; setup(() => { counter = new EventCounter(); @@ -1640,7 +1658,7 @@ suite('TreeModel - Dynamic data model', () => { }); suite('TreeModel - bugs', () => { - var counter:EventCounter; + var counter: EventCounter; setup(() => { counter = new EventCounter(); @@ -1668,7 +1686,7 @@ suite('TreeModel - bugs', () => { } }); - let listeners = []; + let listeners = []; // helpers var getGetRootChildren = (children: string[], timeout = 0) => () => WinJS.TPromise.timeout(timeout).then(() => children); diff --git a/src/vs/base/parts/tree/test/browser/treeViewModel.test.ts b/src/vs/base/parts/tree/test/browser/treeViewModel.test.ts index 311ff2b38d506..b7a6d37fcb095 100644 --- a/src/vs/base/parts/tree/test/browser/treeViewModel.test.ts +++ b/src/vs/base/parts/tree/test/browser/treeViewModel.test.ts @@ -12,7 +12,7 @@ import Tree = require('vs/base/parts/tree/browser/treeImpl'); import { ArrayIterator } from 'vs/base/common/iterator'; import { HeightMap, IViewItem } from 'vs/base/parts/tree/browser/treeViewModel'; -function makeItem(id, height):any { +function makeItem(id, height): any { return { id: id, getHeight: function () { return height; }, @@ -21,7 +21,7 @@ function makeItem(id, height):any { }; } -function makeItems(...args:any[]) { +function makeItems(...args: any[]) { var r = []; for (var i = 0; i < args.length; i += 2) { @@ -31,7 +31,7 @@ function makeItems(...args:any[]) { return r; } -function makeNavigator(...args:any[]):any { +function makeNavigator(...args: any[]): any { var items = makeItems.apply(null, args); var i = 0; diff --git a/src/vs/base/test/browser/dom.test.ts b/src/vs/base/test/browser/dom.test.ts index 5bb93a8a14f23..ea9d1d809efb2 100644 --- a/src/vs/base/test/browser/dom.test.ts +++ b/src/vs/base/test/browser/dom.test.ts @@ -83,7 +83,7 @@ suite('dom', () => { // } //}); - test('safeStringify', function() { + test('safeStringify', function () { var obj1 = { friend: null }; @@ -95,7 +95,7 @@ suite('dom', () => { obj1.friend = obj2; obj2.friend = obj1; - var arr:any = [1]; + var arr: any = [1]; arr.push(arr); var circular = { @@ -117,17 +117,19 @@ suite('dom', () => { a: 42, b: '[Circular]', c: [ - {friend: { - friend: '[Circular]' - }}, + { + friend: { + friend: '[Circular]' + } + }, '[Circular]' ], d: [1, '[Circular]', '[Circular]'] }); }); - test('safeStringify2', function() { - var obj:any = { + test('safeStringify2', function () { + var obj: any = { a: null, b: document.createElement('div'), c: null, diff --git a/src/vs/base/test/browser/highlightedLabel.test.ts b/src/vs/base/test/browser/highlightedLabel.test.ts index 2916bd550522e..b9842e43499f7 100644 --- a/src/vs/base/test/browser/highlightedLabel.test.ts +++ b/src/vs/base/test/browser/highlightedLabel.test.ts @@ -19,37 +19,37 @@ suite('HighlightedLabel', () => { label = null; }); - test('empty label', function() { + test('empty label', function () { assert.equal(label.element.innerHTML, ''); }); - test('no decorations', function() { + test('no decorations', function () { label.set('hello'); assert.equal(label.element.innerHTML, 'hello'); }); - test('escape html', function() { + test('escape html', function () { label.set('helhel<lo'); }); - test('everything highlighted', function() { - label.set('hello', [ { start: 0, end: 5 } ]); + test('everything highlighted', function () { + label.set('hello', [{ start: 0, end: 5 }]); assert.equal(label.element.innerHTML, 'hello'); }); - test('beginning highlighted', function() { - label.set('hellothere', [ { start: 0, end: 5 } ]); + test('beginning highlighted', function () { + label.set('hellothere', [{ start: 0, end: 5 }]); assert.equal(label.element.innerHTML, 'hellothere'); }); - test('ending highlighted', function() { - label.set('goodbye', [ { start: 4, end: 7 } ]); + test('ending highlighted', function () { + label.set('goodbye', [{ start: 4, end: 7 }]); assert.equal(label.element.innerHTML, 'goodbye'); }); - test('middle highlighted', function() { - label.set('foobarfoo', [ { start: 3, end: 6 } ]); + test('middle highlighted', function () { + label.set('foobarfoo', [{ start: 3, end: 6 }]); assert.equal(label.element.innerHTML, 'foobarfoo'); }); }); \ No newline at end of file diff --git a/src/vs/base/test/browser/htmlContent.test.ts b/src/vs/base/test/browser/htmlContent.test.ts index acf8efe3edf79..02fcab1106871 100644 --- a/src/vs/base/test/browser/htmlContent.test.ts +++ b/src/vs/base/test/browser/htmlContent.test.ts @@ -10,7 +10,7 @@ import { renderHtml } from 'vs/base/browser/htmlContentRenderer'; suite('HtmlContent', () => { test('render text', () => { var result = renderHtml({ - text:'testing', + text: 'testing', isText: true }); assert.strictEqual(result.nodeType, document.TEXT_NODE); @@ -29,8 +29,8 @@ suite('HtmlContent', () => { test('render simple element', () => { - var result:HTMLElement = renderHtml({ - text:'testing' + var result: HTMLElement = renderHtml({ + text: 'testing' }); assert.strictEqual(result.nodeType, document.ELEMENT_NODE); assert.strictEqual(result.textContent, 'testing'); @@ -38,8 +38,8 @@ suite('HtmlContent', () => { }); test('render element with class', () => { - var result:HTMLElement = renderHtml({ - text:'testing', + var result: HTMLElement = renderHtml({ + text: 'testing', className: 'testClass' }); assert.strictEqual(result.nodeType, document.ELEMENT_NODE); @@ -47,25 +47,25 @@ suite('HtmlContent', () => { }); test('render element with style', () => { - var result:HTMLElement = renderHtml({ - text:'testing', + var result: HTMLElement = renderHtml({ + text: 'testing', style: 'width: 100px;' }); assert.strictEqual(result.getAttribute('style'), 'width: 100px;'); }); test('render element with custom style', () => { - var result:HTMLElement = renderHtml({ - text:'testing', + var result: HTMLElement = renderHtml({ + text: 'testing', customStyle: { - 'width':'100px' + 'width': '100px' } }); assert.strictEqual(result.style.width, '100px'); }); test('render element with children', () => { - var result:HTMLElement = renderHtml({ + var result: HTMLElement = renderHtml({ className: 'parent', children: [{ text: 'child' @@ -77,7 +77,7 @@ suite('HtmlContent', () => { }); test('simple formatting', () => { - var result:HTMLElement = renderHtml({ + var result: HTMLElement = renderHtml({ formattedText: '**bold**' }); assert.strictEqual(result.children.length, 1); @@ -85,13 +85,13 @@ suite('HtmlContent', () => { assert.strictEqual((result.firstChild).tagName, 'B'); assert.strictEqual(result.innerHTML, 'bold'); - result = renderHtml({ + result = renderHtml({ formattedText: '__italics__' }); assert.strictEqual(result.innerHTML, 'italics'); - result = renderHtml({ + result = renderHtml({ formattedText: 'this string has **bold** and __italics__' }); @@ -99,14 +99,14 @@ suite('HtmlContent', () => { }); test('no formatting', () => { - var result:HTMLElement = renderHtml({ + var result: HTMLElement = renderHtml({ formattedText: 'this is just a string' }); assert.strictEqual(result.innerHTML, 'this is just a string'); }); test('preserve newlines', () => { - var result:HTMLElement = renderHtml({ + var result: HTMLElement = renderHtml({ formattedText: 'line one\nline two' }); assert.strictEqual(result.innerHTML, 'line one
line two'); @@ -114,17 +114,17 @@ suite('HtmlContent', () => { test('action', () => { var callbackCalled = false; - var result:HTMLElement = renderHtml({ + var result: HTMLElement = renderHtml({ formattedText: '[[action]]' }, { - actionCallback(content) { - assert.strictEqual(content, '0'); - callbackCalled = true; - } - }); + actionCallback(content) { + assert.strictEqual(content, '0'); + callbackCalled = true; + } + }); assert.strictEqual(result.innerHTML, 'action'); - var event:MouseEvent = document.createEvent('MouseEvent'); + var event: MouseEvent = document.createEvent('MouseEvent'); event.initEvent('click', true, true); result.firstChild.dispatchEvent(event); assert.strictEqual(callbackCalled, true); @@ -132,24 +132,24 @@ suite('HtmlContent', () => { test('fancy action', () => { var callbackCalled = false; - var result:HTMLElement = renderHtml({ + var result: HTMLElement = renderHtml({ formattedText: '__**[[action]]**__' }, { - actionCallback(content) { - assert.strictEqual(content, '0'); - callbackCalled = true; - } - }); + actionCallback(content) { + assert.strictEqual(content, '0'); + callbackCalled = true; + } + }); assert.strictEqual(result.innerHTML, 'action'); - var event:MouseEvent = document.createEvent('MouseEvent'); + var event: MouseEvent = document.createEvent('MouseEvent'); event.initEvent('click', true, true); result.firstChild.firstChild.firstChild.dispatchEvent(event); assert.strictEqual(callbackCalled, true); }); test('escaped formatting', () => { - var result:HTMLElement = renderHtml({ + var result: HTMLElement = renderHtml({ formattedText: '\\*\\*bold\\*\\*' }); assert.strictEqual(result.children.length, 0); diff --git a/src/vs/base/test/common/actions.test.ts b/src/vs/base/test/common/actions.test.ts index 92676e49de9c0..5ad63777aac8c 100644 --- a/src/vs/base/test/common/actions.test.ts +++ b/src/vs/base/test/common/actions.test.ts @@ -8,24 +8,24 @@ import * as assert from 'assert'; import { Action, IAction, isAction } from 'vs/base/common/actions'; suite('Actions', () => { - test('isAction', function() { - assert(isAction(new Action('id', 'label', 'style', true, function() { return null; }))); - assert(isAction( { + test('isAction', function () { + assert(isAction(new Action('id', 'label', 'style', true, function () { return null; }))); + assert(isAction({ id: 'id', label: 'label', class: 'style', checked: true, enabled: true, - run: function() { return null; } + run: function () { return null; } })); assert(!isAction({ - // id: 'id', + // id: 'id', label: 'label', class: 'style', checked: true, enabled: true, - run: function() { return null; } + run: function () { return null; } })); assert(!isAction({ id: 1234, @@ -33,7 +33,7 @@ suite('Actions', () => { class: 'style', checked: true, enabled: true, - run: function() { return null; } + run: function () { return null; } })); assert(!isAction({ id: 'id', @@ -41,16 +41,16 @@ suite('Actions', () => { class: 'style', checked: 1, enabled: 1, - run: function() { return null; } + run: function () { return null; } })); assert(!isAction(null)); assert(!isAction({ id: 'id', label: 'label', - // class: 'style', + // class: 'style', checked: true, enabled: true, - // run: function() { return null; } + // run: function() { return null; } })); }); }); diff --git a/src/vs/base/test/common/arrays.test.ts b/src/vs/base/test/common/arrays.test.ts index cbf0694327f6e..ab56d3deabed3 100644 --- a/src/vs/base/test/common/arrays.test.ts +++ b/src/vs/base/test/common/arrays.test.ts @@ -33,7 +33,7 @@ suite('Arrays', () => { assert.equal(array[idx], 1); }); - test('binarySearch', function() { + test('binarySearch', function () { function compare(a: number, b: number): number { return a - b; } @@ -49,7 +49,7 @@ suite('Arrays', () => { }); - test('distinct', function() { + test('distinct', function () { function compare(a: string): string { return a; } diff --git a/src/vs/base/test/common/async.test.ts b/src/vs/base/test/common/async.test.ts index 634b5ae9bc63d..206057a567cc5 100644 --- a/src/vs/base/test/common/async.test.ts +++ b/src/vs/base/test/common/async.test.ts @@ -9,7 +9,7 @@ import { Promise, TPromise } from 'vs/base/common/winjs.base'; import Async = require('vs/base/common/async'); suite('Async', () => { - test('Throttler - non async', function(done) { + test('Throttler - non async', function (done) { var count = 0; var factory = () => { return TPromise.as(++count); @@ -26,7 +26,7 @@ suite('Async', () => { ]).done(() => done()); }); - test('Throttler', function(done) { + test('Throttler', function (done) { var count = 0; var factory = () => { return TPromise.timeout(0).then(() => { @@ -53,7 +53,7 @@ suite('Async', () => { }); }); - test('Throttler - cancel should not cancel other promises', function(done) { + test('Throttler - cancel should not cancel other promises', function (done) { var count = 0; var factory = () => { return TPromise.timeout(0).then(() => { @@ -74,7 +74,7 @@ suite('Async', () => { p1.cancel(); }); - test('Throttler - cancel the first queued promise should not cancel other promises', function(done) { + test('Throttler - cancel the first queued promise should not cancel other promises', function (done) { var count = 0; var factory = () => { return TPromise.timeout(0).then(() => { @@ -95,7 +95,7 @@ suite('Async', () => { p2.cancel(); }); - test('Throttler - cancel in the middle should not cancel other promises', function(done) { + test('Throttler - cancel in the middle should not cancel other promises', function (done) { var count = 0; var factory = () => { return TPromise.timeout(0).then(() => { @@ -116,7 +116,7 @@ suite('Async', () => { p3.cancel(); }); - test('Throttler - last factory should be the one getting called', function(done) { + test('Throttler - last factory should be the one getting called', function (done) { var factoryFactory = (n: number) => () => { return TPromise.timeout(0).then(() => n); }; @@ -132,7 +132,7 @@ suite('Async', () => { Promise.join(promises).done(() => done()); }); - test('Throttler - progress should work', function(done) { + test('Throttler - progress should work', function (done) { var order = 0; var factory = () => new Promise((c, e, p) => { TPromise.timeout(0).done(() => { @@ -157,7 +157,7 @@ suite('Async', () => { }); }); - test('Delayer', function(done) { + test('Delayer', function (done) { var count = 0; var factory = () => { return TPromise.as(++count); @@ -183,7 +183,7 @@ suite('Async', () => { }); }); - test('Delayer - simple cancel', function(done) { + test('Delayer - simple cancel', function (done) { var count = 0; var factory = () => { return TPromise.as(++count); @@ -204,7 +204,7 @@ suite('Async', () => { assert(!delayer.isTriggered()); }); - test('Delayer - cancel should cancel all calls to trigger', function(done) { + test('Delayer - cancel should cancel all calls to trigger', function (done) { var count = 0; var factory = () => { return TPromise.as(++count); @@ -232,7 +232,7 @@ suite('Async', () => { }); }); - test('Delayer - trigger, cancel, then trigger again', function(done) { + test('Delayer - trigger, cancel, then trigger again', function (done) { var count = 0; var factory = () => { return TPromise.as(++count); @@ -282,7 +282,7 @@ suite('Async', () => { assert(delayer.isTriggered()); }); - test('Delayer - last task should be the one getting called', function(done) { + test('Delayer - last task should be the one getting called', function (done) { var factoryFactory = (n: number) => () => { return TPromise.as(n); }; @@ -304,7 +304,7 @@ suite('Async', () => { assert(delayer.isTriggered()); }); - test('Delayer - progress should work', function(done) { + test('Delayer - progress should work', function (done) { var order = 0; var factory = () => new Promise((c, e, p) => { TPromise.timeout(0).done(() => { @@ -329,7 +329,7 @@ suite('Async', () => { }); }); - test('ThrottledDelayer - progress should work', function(done) { + test('ThrottledDelayer - progress should work', function (done) { var order = 0; var factory = () => new Promise((c, e, p) => { TPromise.timeout(0).done(() => { @@ -354,7 +354,7 @@ suite('Async', () => { }); }); - test('Sequence', function(done) { + test('Sequence', function (done) { var factoryFactory = (n: number) => () => { return TPromise.as(n); }; @@ -365,7 +365,7 @@ suite('Async', () => { factoryFactory(3), factoryFactory(4), factoryFactory(5), - ]).then((result)=>{ + ]).then((result) => { assert.equal(5, result.length); assert.equal(1, result[0]); assert.equal(2, result[1]); @@ -376,14 +376,14 @@ suite('Async', () => { }); }); - test('Limiter - sync', function(done) { + test('Limiter - sync', function (done) { var factoryFactory = (n: number) => () => { return TPromise.as(n); }; var limiter = new Async.Limiter(1); - var promises:Promise[] = []; + var promises: Promise[] = []; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(n => promises.push(limiter.queue(factoryFactory(n)))); Promise.join(promises).then((res) => { @@ -400,13 +400,13 @@ suite('Async', () => { }).done(() => done()); }); - test('Limiter - async', function(done) { + test('Limiter - async', function (done) { var factoryFactory = (n: number) => () => { return TPromise.timeout(0).then(() => n); }; var limiter = new Async.Limiter(1); - var promises:Promise[] = []; + var promises: Promise[] = []; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(n => promises.push(limiter.queue(factoryFactory(n)))); Promise.join(promises).then((res) => { @@ -423,7 +423,7 @@ suite('Async', () => { }).done(() => done()); }); - test('Limiter - assert degree of paralellism', function(done) { + test('Limiter - assert degree of paralellism', function (done) { var activePromises = 0; var factoryFactory = (n: number) => () => { activePromises++; @@ -433,7 +433,7 @@ suite('Async', () => { var limiter = new Async.Limiter(5); - var promises:Promise[] = []; + var promises: Promise[] = []; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(n => promises.push(limiter.queue(factoryFactory(n)))); Promise.join(promises).then((res) => { diff --git a/src/vs/base/test/common/cancellation.test.ts b/src/vs/base/test/common/cancellation.test.ts index 007b33b83a41f..760079da5b7cf 100644 --- a/src/vs/base/test/common/cancellation.test.ts +++ b/src/vs/base/test/common/cancellation.test.ts @@ -5,11 +5,11 @@ 'use strict'; import * as assert from 'assert'; -import {CancellationTokenSource, CancellationToken} from 'vs/base/common/cancellation'; +import { CancellationTokenSource, CancellationToken } from 'vs/base/common/cancellation'; -suite('CancellationToken', function() { +suite('CancellationToken', function () { - test('None', function() { + test('None', function () { assert.equal(CancellationToken.None.isCancellationRequested, false); assert.equal(typeof CancellationToken.None.onCancellationRequested, 'function'); }); @@ -48,7 +48,7 @@ suite('CancellationToken', function() { }); }); - test('cancel happens only once', function() { + test('cancel happens only once', function () { let source = new CancellationTokenSource(); assert.equal(source.token.isCancellationRequested, false); @@ -85,7 +85,7 @@ suite('CancellationToken', function() { assert.equal(count, 3); }); - test('token stays the same', function(){ + test('token stays the same', function () { let source = new CancellationTokenSource(); let token = source.token; diff --git a/src/vs/base/test/common/charCode.test.ts b/src/vs/base/test/common/charCode.test.ts index 89a7766b07942..903d6cee53594 100644 --- a/src/vs/base/test/common/charCode.test.ts +++ b/src/vs/base/test/common/charCode.test.ts @@ -5,12 +5,12 @@ 'use strict'; import * as assert from 'assert'; -import {CharCode} from 'vs/base/common/charCode'; +import { CharCode } from 'vs/base/common/charCode'; suite('CharCode', () => { test('has good values', () => { - function assertValue(actual:CharCode, expected:string): void { + function assertValue(actual: CharCode, expected: string): void { assert.equal(actual, expected.charCodeAt(0), 'char code ok for <<' + expected + '>>'); } diff --git a/src/vs/base/test/common/color.test.ts b/src/vs/base/test/common/color.test.ts index 67d2469f11ec3..e763e915b869c 100644 --- a/src/vs/base/test/common/color.test.ts +++ b/src/vs/base/test/common/color.test.ts @@ -5,7 +5,7 @@ 'use strict'; -import {Color} from 'vs/base/common/color'; +import { Color } from 'vs/base/common/color'; import * as assert from 'assert'; suite('Color', () => { diff --git a/src/vs/base/test/common/decorators.test.ts b/src/vs/base/test/common/decorators.test.ts index 4c082ada84305..9d6c1c5e434e9 100644 --- a/src/vs/base/test/common/decorators.test.ts +++ b/src/vs/base/test/common/decorators.test.ts @@ -6,14 +6,14 @@ 'use strict'; import * as assert from 'assert'; -import { memoize } from 'vs/base/common/decorators'; +import { memoize  } from 'vs/base/common/decorators'; suite('Decorators', () => { test('memoize should memoize methods', () => { class Foo { count = 0; - constructor(private _answer: number) {} + constructor(private _answer: number) { } @memoize answer() { @@ -58,7 +58,7 @@ suite('Decorators', () => { class Foo { count = 0; - constructor(private _answer: number) {} + constructor(private _answer: number) { } @memoize get answer() { diff --git a/src/vs/base/test/common/diff/diff.test.ts b/src/vs/base/test/common/diff/diff.test.ts index c03e0b0e96423..3e0c8b710d055 100644 --- a/src/vs/base/test/common/diff/diff.test.ts +++ b/src/vs/base/test/common/diff/diff.test.ts @@ -92,7 +92,7 @@ function stringPower(str: string, power: number): string { function lcsTest(Algorithm: any, originalStr: string, modifiedStr: string, answerStr: string) { lcsInnerTest(Algorithm, originalStr, modifiedStr, answerStr); for (var i = 2; i <= 5; i++) { - lcsInnerTest(Algorithm, stringPower(originalStr,i), stringPower(modifiedStr,i), stringPower(answerStr,i), true); + lcsInnerTest(Algorithm, stringPower(originalStr, i), stringPower(modifiedStr, i), stringPower(answerStr, i), true); } } diff --git a/src/vs/base/test/common/event.test.ts b/src/vs/base/test/common/event.test.ts index 7faccca0e84c3..bced04f77c433 100644 --- a/src/vs/base/test/common/event.test.ts +++ b/src/vs/base/test/common/event.test.ts @@ -5,11 +5,11 @@ 'use strict'; import * as assert from 'assert'; -import Event, {Emitter, fromEventEmitter, debounceEvent, EventBufferer, once, fromPromise, stopwatch, buffer} from 'vs/base/common/event'; -import {IDisposable} from 'vs/base/common/lifecycle'; -import {EventEmitter} from 'vs/base/common/eventEmitter'; +import Event, { Emitter, fromEventEmitter, debounceEvent, EventBufferer, once, fromPromise, stopwatch, buffer } from 'vs/base/common/event'; +import { IDisposable } from 'vs/base/common/lifecycle'; +import { EventEmitter } from 'vs/base/common/eventEmitter'; import Errors = require('vs/base/common/errors'); -import {TPromise} from 'vs/base/common/winjs.base'; +import { TPromise } from 'vs/base/common/winjs.base'; namespace Samples { @@ -32,7 +32,7 @@ namespace Samples { onDidChange: Event = this._onDidChange.event; - setText(value:string) { + setText(value: string) { //... this._onDidChange.fire(value); } @@ -48,14 +48,14 @@ namespace Samples { onDidChange = fromEventEmitter(this._eventBus, Document3b._didChange); - setText(value:string) { + setText(value: string) { //... this._eventBus.emit(Document3b._didChange, value); } } } -suite('Event',function(){ +suite('Event', function () { const counter = new Samples.EventCounter(); @@ -91,9 +91,9 @@ suite('Event',function(){ assert.equal(counter.count, 2); }); - test('Emitter, bucket', function(){ + test('Emitter, bucket', function () { - let bucket:IDisposable[] = []; + let bucket: IDisposable[] = []; let doc = new Samples.Document3(); let subscription = doc.onDidChange(counter.onEvent, counter, bucket); @@ -101,7 +101,7 @@ suite('Event',function(){ doc.setText('boo'); // unhook listener - while(bucket.length) { + while (bucket.length) { bucket.pop().dispose(); } @@ -112,9 +112,9 @@ suite('Event',function(){ assert.equal(counter.count, 2); }); - test('wrapEventEmitter, bucket', function(){ + test('wrapEventEmitter, bucket', function () { - let bucket:IDisposable[] = []; + let bucket: IDisposable[] = []; let doc = new Samples.Document3b(); let subscription = doc.onDidChange(counter.onEvent, counter, bucket); @@ -122,7 +122,7 @@ suite('Event',function(){ doc.setText('boo'); // unhook listener - while(bucket.length) { + while (bucket.length) { bucket.pop().dispose(); } @@ -133,7 +133,7 @@ suite('Event',function(){ assert.equal(counter.count, 2); }); - test('onFirstAdd|onLastRemove', function(){ + test('onFirstAdd|onLastRemove', function () { let firstCount = 0; let lastCount = 0; @@ -158,17 +158,17 @@ suite('Event',function(){ assert.equal(lastCount, 1); }); - test('throwingListener', function() { + test('throwingListener', function () { var origErrorHandler = Errors.errorHandler.getUnexpectedErrorHandler(); Errors.setUnexpectedErrorHandler(() => null); try { let a = new Emitter(); let hit = false; - a.event(function() { + a.event(function () { throw 9; }); - a.event(function() { + a.event(function () { hit = true; }); a.fire(undefined); @@ -199,7 +199,7 @@ suite('Event',function(){ if (count === 1) { doc.setText('4'); assert.deepEqual(keys, ['1', '2', '3']); - } else if (count === 2){ + } else if (count === 2) { assert.deepEqual(keys, ['4']); done(); } @@ -369,14 +369,14 @@ suite('Event utils', () => { assert.deepEqual(result, []); const listener = bufferedEvent(num => result.push(num)); - assert.deepEqual(result, [1,2,3]); + assert.deepEqual(result, [1, 2, 3]); emitter.fire(4); - assert.deepEqual(result, [1,2,3,4]); + assert.deepEqual(result, [1, 2, 3, 4]); listener.dispose(); emitter.fire(5); - assert.deepEqual(result, [1,2,3,4]); + assert.deepEqual(result, [1, 2, 3, 4]); }); test('should buffer events on next tick', () => { @@ -395,11 +395,11 @@ suite('Event utils', () => { return TPromise.timeout(10).then(() => { emitter.fire(4); - assert.deepEqual(result, [1,2,3,4]); + assert.deepEqual(result, [1, 2, 3, 4]); listener.dispose(); emitter.fire(5); - assert.deepEqual(result, [1,2,3,4]); + assert.deepEqual(result, [1, 2, 3, 4]); }); }); @@ -415,7 +415,7 @@ suite('Event utils', () => { assert.deepEqual(result, []); bufferedEvent(num => result.push(num)); - assert.deepEqual(result, [-2,-1,0,1,2,3]); + assert.deepEqual(result, [-2, -1, 0, 1, 2, 3]); }); }); diff --git a/src/vs/base/test/common/eventEmitter.test.ts b/src/vs/base/test/common/eventEmitter.test.ts index ff206fbc94aaa..e02e77d9f8cfc 100644 --- a/src/vs/base/test/common/eventEmitter.test.ts +++ b/src/vs/base/test/common/eventEmitter.test.ts @@ -209,16 +209,16 @@ suite('EventEmitter', () => { var emitter = new EventEmitter(); var actualCallOrder: string[] = []; - emitter.addListener2('foo', function() { + emitter.addListener2('foo', function () { actualCallOrder.push('listener1-foo'); emitter.emit('bar'); }); - emitter.addListener2('foo', function() { + emitter.addListener2('foo', function () { actualCallOrder.push('listener2-foo'); }); - emitter.addListener2('bar', function() { + emitter.addListener2('bar', function () { actualCallOrder.push('listener2-bar'); }); @@ -235,7 +235,7 @@ suite('EventEmitter', () => { var emitter = new EventEmitter(); var actualCallOrder: string[] = []; - emitter.addListener2('foo', function() { + emitter.addListener2('foo', function () { actualCallOrder.push('listener1-foo'); emitter.deferredEmit(() => { emitter.emit('bar'); @@ -243,10 +243,10 @@ suite('EventEmitter', () => { }); - emitter.addListener2('foo', function() { + emitter.addListener2('foo', function () { actualCallOrder.push('listener2-foo'); }); - emitter.addListener2('bar', function() { + emitter.addListener2('bar', function () { actualCallOrder.push('listener2-bar'); }); @@ -265,16 +265,16 @@ suite('EventEmitter', () => { var emitter = new OrderGuaranteeEventEmitter(); var actualCallOrder: string[] = []; - emitter.addListener2('foo', function() { + emitter.addListener2('foo', function () { actualCallOrder.push('listener1-foo'); emitter.emit('bar'); }); - emitter.addListener2('foo', function() { + emitter.addListener2('foo', function () { actualCallOrder.push('listener2-foo'); }); - emitter.addListener2('bar', function() { + emitter.addListener2('bar', function () { actualCallOrder.push('listener2-bar'); }); @@ -291,7 +291,7 @@ suite('EventEmitter', () => { var emitter = new OrderGuaranteeEventEmitter(); var actualCallOrder: string[] = []; - emitter.addListener2('foo', function() { + emitter.addListener2('foo', function () { actualCallOrder.push('listener1-foo'); emitter.deferredEmit(() => { emitter.emit('bar'); @@ -299,10 +299,10 @@ suite('EventEmitter', () => { }); - emitter.addListener2('foo', function() { + emitter.addListener2('foo', function () { actualCallOrder.push('listener2-foo'); }); - emitter.addListener2('bar', function() { + emitter.addListener2('bar', function () { actualCallOrder.push('listener2-bar'); }); diff --git a/src/vs/base/test/common/filters.test.ts b/src/vs/base/test/common/filters.test.ts index 1a8159a225fbf..ff2c5c463ba02 100644 --- a/src/vs/base/test/common/filters.test.ts +++ b/src/vs/base/test/common/filters.test.ts @@ -26,25 +26,25 @@ suite('Filters', () => { return function () { counters[i]++; return r; }; }; - counters = [0,0]; + counters = [0, 0]; filter = or(newFilter(0, false), newFilter(1, false)); filterNotOk(filter, 'anything', 'anything'); - assert.deepEqual(counters, [1,1]); + assert.deepEqual(counters, [1, 1]); - counters = [0,0]; + counters = [0, 0]; filter = or(newFilter(0, true), newFilter(1, false)); filterOk(filter, 'anything', 'anything'); - assert.deepEqual(counters, [1,0]); + assert.deepEqual(counters, [1, 0]); - counters = [0,0]; + counters = [0, 0]; filter = or(newFilter(0, true), newFilter(1, true)); filterOk(filter, 'anything', 'anything'); - assert.deepEqual(counters, [1,0]); + assert.deepEqual(counters, [1, 0]); - counters = [0,0]; + counters = [0, 0]; filter = or(newFilter(0, false), newFilter(1, true)); filterOk(filter, 'anything', 'anything'); - assert.deepEqual(counters, [1,1]); + assert.deepEqual(counters, [1, 1]); }); test('PrefixFilter - case sensitive', function () { @@ -171,19 +171,19 @@ suite('Filters', () => { filterOk(matchesWords, 'AlPh', 'alPHA', [{ start: 0, end: 4 }]); assert(matchesWords('Debug Console', 'Open: Debug Console')); - filterOk(matchesWords, 'gp', 'Git: Pull', [{ start: 0, end: 1 }, { start: 5, end: 6}]); - filterOk(matchesWords, 'g p', 'Git: Pull', [{ start: 0, end: 1 }, { start: 4, end: 6}]); - filterOk(matchesWords, 'gipu', 'Git: Pull', [{ start: 0, end: 2 }, { start: 5, end: 7}]); + filterOk(matchesWords, 'gp', 'Git: Pull', [{ start: 0, end: 1 }, { start: 5, end: 6 }]); + filterOk(matchesWords, 'g p', 'Git: Pull', [{ start: 0, end: 1 }, { start: 4, end: 6 }]); + filterOk(matchesWords, 'gipu', 'Git: Pull', [{ start: 0, end: 2 }, { start: 5, end: 7 }]); - filterOk(matchesWords, 'gp', 'Category: Git: Pull', [{ start: 10, end: 11 }, { start: 15, end: 16}]); - filterOk(matchesWords, 'g p', 'Category: Git: Pull', [{ start: 10, end: 11 }, { start: 14, end: 16}]); - filterOk(matchesWords, 'gipu', 'Category: Git: Pull', [{ start: 10, end: 12 }, { start: 15, end: 17}]); + filterOk(matchesWords, 'gp', 'Category: Git: Pull', [{ start: 10, end: 11 }, { start: 15, end: 16 }]); + filterOk(matchesWords, 'g p', 'Category: Git: Pull', [{ start: 10, end: 11 }, { start: 14, end: 16 }]); + filterOk(matchesWords, 'gipu', 'Category: Git: Pull', [{ start: 10, end: 12 }, { start: 15, end: 17 }]); filterNotOk(matchesWords, 'it', 'Git: Pull'); filterNotOk(matchesWords, 'll', 'Git: Pull'); filterOk(matchesWords, 'git: プル', 'git: プル', [{ start: 0, end: 7 }]); - filterOk(matchesWords, 'git プル', 'git: プル', [{ start: 0, end: 3 }, { start: 4, end: 7}]); + filterOk(matchesWords, 'git プル', 'git: プル', [{ start: 0, end: 3 }, { start: 4, end: 7 }]); filterOk(matchesWords, 'öäk', 'Öhm: Älles Klar', [{ start: 0, end: 1 }, { start: 5, end: 6 }, { start: 11, end: 12 }]); }); diff --git a/src/vs/base/test/common/glob.test.ts b/src/vs/base/test/common/glob.test.ts index c587290e23684..20a24e8a39282 100644 --- a/src/vs/base/test/common/glob.test.ts +++ b/src/vs/base/test/common/glob.test.ts @@ -637,7 +637,7 @@ suite('Glob', () => { '**/*.js': { when: '$(basename).ts' } }; - var sibilings = () => [ 'foo.ts', 'foo.js', 'foo', 'bar' ]; + var sibilings = () => ['foo.ts', 'foo.js', 'foo', 'bar']; assert.strictEqual(glob.match(expr, 'bar', sibilings), '**/bar'); assert.strictEqual(glob.match(expr, 'foo', sibilings), null); @@ -690,7 +690,7 @@ suite('Glob', () => { assert.strictEqual(glob.parse('{**/baz,**/foo}')('baz/foo', 'foo'), true); var expr = { '**/*.js': { when: '$(basename).ts' } }; - var sibilings = () => [ 'foo.ts', 'foo.js' ]; + var sibilings = () => ['foo.ts', 'foo.js']; assert.strictEqual(glob.parse(expr)('bar/baz.js', 'baz.js', sibilings), null); assert.strictEqual(glob.parse(expr)('bar/foo.js', 'foo.js', sibilings), '**/*.js'); @@ -728,28 +728,28 @@ suite('Glob', () => { '{**/bar/**,**/baz/**}': true, '**/bulb/**': false }, ['foo', 'bar', 'baz'], [ - ['bar/foo', '**/foo/**'], - ['foo/bar', '{**/bar/**,**/baz/**}'], - ['bar/nope', null] - ]); + ['bar/foo', '**/foo/**'], + ['foo/bar', '{**/bar/**,**/baz/**}'], + ['bar/nope', null] + ]); const siblingsFn = () => ['baz', 'baz.zip', 'nope']; testOptimizationForBasenames({ '**/foo/**': { when: '$(basename).zip' }, '**/bar/**': true }, ['bar'], [ - ['bar/foo', null], - ['bar/foo/baz', null], - ['bar/foo/nope', null], - ['foo/bar', '**/bar/**'], - ], [ - null, - siblingsFn, - siblingsFn - ]); + ['bar/foo', null], + ['bar/foo/baz', null], + ['bar/foo/nope', null], + ['foo/bar', '**/bar/**'], + ], [ + null, + siblingsFn, + siblingsFn + ]); }); - function testOptimizationForBasenames(pattern: string|glob.IExpression, basenameTerms: string[], matches: [string, string|boolean][], siblingsFns: (() => string[])[] = []) { + function testOptimizationForBasenames(pattern: string | glob.IExpression, basenameTerms: string[], matches: [string, string | boolean][], siblingsFns: (() => string[])[] = []) { const parsed = glob.parse(pattern, { trimForExclusions: true }); assert.deepStrictEqual(glob.getBasenameTerms(parsed), basenameTerms); matches.forEach(([text, result], i) => { @@ -831,29 +831,29 @@ suite('Glob', () => { // '{**/bar/bar/**,**/baz/bar/**}': true, '**/bulb/bar/**': false }, ['*/foo/bar'], [ - ['bar/foo/bar', '**/foo/bar/**'], - // Not supported - // ['foo/bar/bar', '{**/bar/bar/**,**/baz/bar/**}'], - ['/foo/bar/nope', null] - ]); + ['bar/foo/bar', '**/foo/bar/**'], + // Not supported + // ['foo/bar/bar', '{**/bar/bar/**,**/baz/bar/**}'], + ['/foo/bar/nope', null] + ]); const siblingsFn = () => ['baz', 'baz.zip', 'nope']; testOptimizationForPaths({ '**/foo/123/**': { when: '$(basename).zip' }, '**/bar/123/**': true }, ['*/bar/123'], [ - ['bar/foo/123', null], - ['bar/foo/123/baz', null], - ['bar/foo/123/nope', null], - ['foo/bar/123', '**/bar/123/**'], - ], [ - null, - siblingsFn, - siblingsFn - ]); + ['bar/foo/123', null], + ['bar/foo/123/baz', null], + ['bar/foo/123/nope', null], + ['foo/bar/123', '**/bar/123/**'], + ], [ + null, + siblingsFn, + siblingsFn + ]); }); - function testOptimizationForPaths(pattern: string|glob.IExpression, pathTerms: string[], matches: [string, string|boolean][], siblingsFns: (() => string[])[] = []) { + function testOptimizationForPaths(pattern: string | glob.IExpression, pathTerms: string[], matches: [string, string | boolean][], siblingsFns: (() => string[])[] = []) { const parsed = glob.parse(pattern, { trimForExclusions: true }); assert.deepStrictEqual(glob.getPathTerms(parsed), pathTerms); matches.forEach(([text, result], i) => { diff --git a/src/vs/base/test/common/graph.test.ts b/src/vs/base/test/common/graph.test.ts index fd4a59817205d..4ff83d5186945 100644 --- a/src/vs/base/test/common/graph.test.ts +++ b/src/vs/base/test/common/graph.test.ts @@ -14,23 +14,23 @@ suite('Graph', () => { graph = new Graph(s => s); }); - test('cannot be traversed when empty', function() { + test('cannot be traversed when empty', function () { graph.traverse('foo', true, () => assert(false)); graph.traverse('foo', false, () => assert(false)); assert(true); }); - test('is possible to lookup nodes that don\'t exist', function() { + test('is possible to lookup nodes that don\'t exist', function () { assert.deepEqual(graph.lookup('ddd'), null); }); - test('inserts nodes when not there yet', function() { + test('inserts nodes when not there yet', function () { assert.deepEqual(graph.lookup('ddd'), null); assert.deepEqual(graph.lookupOrInsertNode('ddd').data, 'ddd'); assert.deepEqual(graph.lookup('ddd').data, 'ddd'); }); - test('can remove nodes and get length', function() { + test('can remove nodes and get length', function () { assert.equal(graph.length, 0); assert.deepEqual(graph.lookup('ddd'), null); assert.deepEqual(graph.lookupOrInsertNode('ddd').data, 'ddd'); @@ -40,14 +40,14 @@ suite('Graph', () => { assert.equal(graph.length, 0); }); - test('traverse from leaf', function() { + test('traverse from leaf', function () { graph.insertEdge('foo', 'bar'); graph.traverse('bar', true, (node) => assert.equal(node, 'bar')); var items = ['bar', 'foo']; graph.traverse('bar', false, (node) => assert.equal(node, items.shift())); }); - test('traverse from center', function() { + test('traverse from center', function () { graph.insertEdge('1', '3'); graph.insertEdge('2', '3'); graph.insertEdge('3', '4'); @@ -60,7 +60,7 @@ suite('Graph', () => { graph.traverse('3', false, (node) => assert.equal(node, items.shift())); }); - test('traverse a chain', function() { + test('traverse a chain', function () { graph.insertEdge('1', '2'); graph.insertEdge('2', '3'); graph.insertEdge('3', '4'); @@ -73,7 +73,7 @@ suite('Graph', () => { graph.traverse('5', false, (node) => assert.equal(node, items.shift())); }); - test('root', function() { + test('root', function () { graph.insertEdge('1', '2'); var roots = graph.roots(); assert.equal(roots.length, 1); @@ -84,7 +84,7 @@ suite('Graph', () => { assert.equal(roots.length, 0); }); - test('root complex', function() { + test('root complex', function () { graph.insertEdge('1', '2'); graph.insertEdge('1', '3'); graph.insertEdge('3', '4'); diff --git a/src/vs/base/test/common/hash.test.ts b/src/vs/base/test/common/hash.test.ts index 7595ea8da5c27..7eb6326ddff6f 100644 --- a/src/vs/base/test/common/hash.test.ts +++ b/src/vs/base/test/common/hash.test.ts @@ -5,7 +5,7 @@ 'use strict'; import * as assert from 'assert'; -import {hash} from 'vs/base/common/hash'; +import { hash } from 'vs/base/common/hash'; suite('Hash', () => { test('string', () => { @@ -40,9 +40,9 @@ suite('Hash', () => { test('object', () => { assert.equal(hash({}), hash({})); - assert.equal(hash({'foo': 'bar'}), hash({'foo': 'bar'})); - assert.equal(hash({'foo': 'bar', 'foo2': void 0}), hash({'foo2': void 0, 'foo': 'bar'})); - assert.notEqual(hash({'foo': 'bar'}), hash({'foo': 'bar2'})); + assert.equal(hash({ 'foo': 'bar' }), hash({ 'foo': 'bar' })); + assert.equal(hash({ 'foo': 'bar', 'foo2': void 0 }), hash({ 'foo2': void 0, 'foo': 'bar' })); + assert.notEqual(hash({ 'foo': 'bar' }), hash({ 'foo': 'bar2' })); assert.notEqual(hash({}), hash([])); }); }); \ No newline at end of file diff --git a/src/vs/base/test/common/history.test.ts b/src/vs/base/test/common/history.test.ts index f668270211b6e..2c55c1cd05fe0 100644 --- a/src/vs/base/test/common/history.test.ts +++ b/src/vs/base/test/common/history.test.ts @@ -5,7 +5,7 @@ 'use strict'; import * as assert from 'assert'; -import {HistoryNavigator} from 'vs/base/common/history'; +import { HistoryNavigator } from 'vs/base/common/history'; suite('History Navigator', () => { diff --git a/src/vs/base/test/common/json.test.ts b/src/vs/base/test/common/json.test.ts index a84fc71f4112a..784434e677c8f 100644 --- a/src/vs/base/test/common/json.test.ts +++ b/src/vs/base/test/common/json.test.ts @@ -5,21 +5,23 @@ 'use strict'; import * as assert from 'assert'; -import { SyntaxKind, createScanner, parse, getLocation, Node, ParseError, parseTree, ParseErrorCode, - getParseErrorMessage, ParseOptions, Segment, findNodeAtLocation, getNodeValue } from 'vs/base/common/json'; +import { + SyntaxKind, createScanner, parse, getLocation, Node, ParseError, parseTree, ParseErrorCode, + getParseErrorMessage, ParseOptions, Segment, findNodeAtLocation, getNodeValue +} from 'vs/base/common/json'; -function assertKinds(text:string, ...kinds:SyntaxKind[]):void { +function assertKinds(text: string, ...kinds: SyntaxKind[]): void { var _json = createScanner(text); var kind: SyntaxKind; - while((kind = _json.scan()) !== SyntaxKind.EOF) { + while ((kind = _json.scan()) !== SyntaxKind.EOF) { assert.equal(kind, kinds.shift()); } assert.equal(kinds.length, 0); } -function assertValidParse(input:string, expected:any, options?: ParseOptions) : void { - var errors : {error: ParseErrorCode}[] = []; +function assertValidParse(input: string, expected: any, options?: ParseOptions): void { + var errors: { error: ParseErrorCode }[] = []; var actual = parse(input, errors, options); if (errors.length !== 0) { @@ -28,16 +30,16 @@ function assertValidParse(input:string, expected:any, options?: ParseOptions) : assert.deepEqual(actual, expected); } -function assertInvalidParse(input:string, expected:any, options?: ParseOptions) : void { - var errors : {error: ParseErrorCode}[] = []; +function assertInvalidParse(input: string, expected: any, options?: ParseOptions): void { + var errors: { error: ParseErrorCode }[] = []; var actual = parse(input, errors, options); assert(errors.length > 0); assert.deepEqual(actual, expected); } -function assertTree(input:string, expected:any) : void { - var errors : ParseError[] = []; +function assertTree(input: string, expected: any): void { + var errors: ParseError[] = []; var actual = parseTree(input, errors); assert.equal(errors.length, 0); @@ -55,16 +57,16 @@ function assertTree(input:string, expected:any) : void { assert.deepEqual(actual, expected); } -function assertNodeAtLocation(input:Node, segments: Segment[], expected: any) { +function assertNodeAtLocation(input: Node, segments: Segment[], expected: any) { let actual = findNodeAtLocation(input, segments); assert.deepEqual(actual ? getNodeValue(actual) : void 0, expected); } -function assertLocation(input:string, expectedSegments: Segment[], expectedNodeType: string, expectedCompleteProperty: boolean) : void { - var errors : {error: ParseErrorCode}[] = []; +function assertLocation(input: string, expectedSegments: Segment[], expectedNodeType: string, expectedCompleteProperty: boolean): void { + var errors: { error: ParseErrorCode }[] = []; var offset = input.indexOf('|'); - input = input.substring(0, offset) + input.substring(offset+1, input.length); + input = input.substring(0, offset) + input.substring(offset + 1, input.length); var actual = getLocation(input, offset); assert(actual); assert.deepEqual(actual.path, expectedSegments, input); @@ -192,18 +194,18 @@ suite('JSON', () => { assertValidParse('{ "foo": true }', { foo: true }); assertValidParse('{ "bar": 8, "xoo": "foo" }', { bar: 8, xoo: 'foo' }); assertValidParse('{ "hello": [], "world": {} }', { hello: [], world: {} }); - assertValidParse('{ "a": false, "b": true, "c": [ 7.4 ] }', { a: false, b: true, c: [ 7.4 ]}); - assertValidParse('{ "lineComment": "//", "blockComment": ["/*", "*/"], "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ] }', { lineComment: '//', blockComment: ["/*", "*/"], brackets: [ ["{", "}"], ["[", "]"], ["(", ")"] ] }); + assertValidParse('{ "a": false, "b": true, "c": [ 7.4 ] }', { a: false, b: true, c: [7.4] }); + assertValidParse('{ "lineComment": "//", "blockComment": ["/*", "*/"], "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ] }', { lineComment: '//', blockComment: ["/*", "*/"], brackets: [["{", "}"], ["[", "]"], ["(", ")"]] }); assertValidParse('{ "hello": [], "world": {} }', { hello: [], world: {} }); - assertValidParse('{ "hello": { "again": { "inside": 5 }, "world": 1 }}', { hello: { again: { inside: 5 }, world: 1 }}); + assertValidParse('{ "hello": { "again": { "inside": 5 }, "world": 1 }}', { hello: { again: { inside: 5 }, world: 1 } }); assertValidParse('{ "foo": /*hello*/true }', { foo: true }); }); test('parse: arrays', () => { assertValidParse('[]', []); assertValidParse('[ [], [ [] ]]', [[], [[]]]); - assertValidParse('[ 1, 2, 3 ]', [ 1, 2, 3 ]); - assertValidParse('[ { "a": null } ]', [ { a: null } ]); + assertValidParse('[ 1, 2, 3 ]', [1, 2, 3]); + assertValidParse('[ { "a": null } ]', [{ a: null }]); }); test('parse: objects with errors', () => { @@ -218,16 +220,16 @@ suite('JSON', () => { test('parse: array with errors', () => { assertInvalidParse('[,]', []); - assertInvalidParse('[ 1, 2, ]', [ 1, 2]); - assertInvalidParse('[ 1 2, 3 ]', [ 1, 2, 3 ]); - assertInvalidParse('[ ,1, 2, 3 ]', [ 1, 2, 3 ]); - assertInvalidParse('[ ,1, 2, 3, ]', [ 1, 2, 3 ]); + assertInvalidParse('[ 1, 2, ]', [1, 2]); + assertInvalidParse('[ 1 2, 3 ]', [1, 2, 3]); + assertInvalidParse('[ ,1, 2, 3 ]', [1, 2, 3]); + assertInvalidParse('[ ,1, 2, 3, ]', [1, 2, 3]); }); test('parse: disallow commments', () => { let options = { disallowComments: true }; - assertValidParse('[ 1, 2, null, "foo" ]', [ 1, 2, null, "foo"], options); + assertValidParse('[ 1, 2, null, "foo" ]', [1, 2, null, "foo"], options); assertValidParse('{ "hello": [], "world": {} }', { hello: [], world: {} }, options); assertInvalidParse('{ "foo": /*comment*/ true }', { foo: true }, options); @@ -236,22 +238,22 @@ suite('JSON', () => { test('location: properties', () => { assertLocation('|{ "foo": "bar" }', [], void 0, false); assertLocation('{| "foo": "bar" }', [], void 0, true); - assertLocation('{ |"foo": "bar" }', ["foo" ], "property", true); - assertLocation('{ "foo|": "bar" }', [ "foo" ], "property", true); - assertLocation('{ "foo"|: "bar" }', ["foo" ], "property", true); - assertLocation('{ "foo": "bar"| }', ["foo" ], "string", false); - assertLocation('{ "foo":| "bar" }', ["foo" ], void 0, false); - assertLocation('{ "foo": {"bar|": 1, "car": 2 } }', ["foo", "bar" ], "property", true); - assertLocation('{ "foo": {"bar": 1|, "car": 3 } }', ["foo", "bar" ], "number", false); + assertLocation('{ |"foo": "bar" }', ["foo"], "property", true); + assertLocation('{ "foo|": "bar" }', ["foo"], "property", true); + assertLocation('{ "foo"|: "bar" }', ["foo"], "property", true); + assertLocation('{ "foo": "bar"| }', ["foo"], "string", false); + assertLocation('{ "foo":| "bar" }', ["foo"], void 0, false); + assertLocation('{ "foo": {"bar|": 1, "car": 2 } }', ["foo", "bar"], "property", true); + assertLocation('{ "foo": {"bar": 1|, "car": 3 } }', ["foo", "bar"], "number", false); assertLocation('{ "foo": {"bar": 1,| "car": 4 } }', ["foo"], void 0, true); - assertLocation('{ "foo": {"bar": 1, "ca|r": 5 } }', ["foo", "car" ], "property", true); - assertLocation('{ "foo": {"bar": 1, "car": 6| } }', ["foo", "car" ], "number", false); + assertLocation('{ "foo": {"bar": 1, "ca|r": 5 } }', ["foo", "car"], "property", true); + assertLocation('{ "foo": {"bar": 1, "car": 6| } }', ["foo", "car"], "number", false); assertLocation('{ "foo": {"bar": 1, "car": 7 }| }', ["foo"], void 0, false); assertLocation('{ "foo": {"bar": 1, "car": 8 },| "goo": {} }', [], void 0, true); - assertLocation('{ "foo": {"bar": 1, "car": 9 }, "go|o": {} }', ["goo" ], "property", true); - assertLocation('{ "dep": {"bar": 1, "car": |', ["dep", "car" ], void 0, false); - assertLocation('{ "dep": {"bar": 1,, "car": |', ["dep", "car" ], void 0, false); - assertLocation('{ "dep": {"bar": "na", "dar": "ma", "car": | } }', ["dep", "car" ], void 0, false); + assertLocation('{ "foo": {"bar": 1, "car": 9 }, "go|o": {} }', ["goo"], "property", true); + assertLocation('{ "dep": {"bar": 1, "car": |', ["dep", "car"], void 0, false); + assertLocation('{ "dep": {"bar": 1,, "car": |', ["dep", "car"], void 0, false); + assertLocation('{ "dep": {"bar": "na", "dar": "ma", "car": | } }', ["dep", "car"], void 0, false); }); test('location: arrays', () => { @@ -277,51 +279,67 @@ suite('JSON', () => { test('tree: arrays', () => { assertTree('[]', { type: 'array', offset: 0, length: 2, children: [] }); assertTree('[ 1 ]', { type: 'array', offset: 0, length: 5, children: [{ type: 'number', offset: 2, length: 1, value: 1 }] }); - assertTree('[ 1,"x"]', { type: 'array', offset: 0, length: 8, children: [ - { type: 'number', offset: 2, length: 1, value: 1 }, - { type: 'string', offset: 4, length: 3, value: 'x' } - ]}); - assertTree('[[]]', { type: 'array', offset: 0, length: 4, children: [ - { type: 'array', offset: 1, length: 2, children: []} - ]}); + assertTree('[ 1,"x"]', { + type: 'array', offset: 0, length: 8, children: [ + { type: 'number', offset: 2, length: 1, value: 1 }, + { type: 'string', offset: 4, length: 3, value: 'x' } + ] + }); + assertTree('[[]]', { + type: 'array', offset: 0, length: 4, children: [ + { type: 'array', offset: 1, length: 2, children: [] } + ] + }); }); test('tree: objects', () => { assertTree('{ }', { type: 'object', offset: 0, length: 3, children: [] }); - assertTree('{ "val": 1 }', { type: 'object', offset: 0, length: 12, children: [ - { type: 'property', offset: 2, length: 8, columnOffset: 7, children: [ - { type: 'string', offset: 2, length: 5, value: 'val' }, - { type: 'number', offset: 9, length: 1, value: 1 } - ]} - ]}); + assertTree('{ "val": 1 }', { + type: 'object', offset: 0, length: 12, children: [ + { + type: 'property', offset: 2, length: 8, columnOffset: 7, children: [ + { type: 'string', offset: 2, length: 5, value: 'val' }, + { type: 'number', offset: 9, length: 1, value: 1 } + ] + } + ] + }); assertTree('{"id": "$", "v": [ null, null] }', - { type: 'object', offset: 0, length: 32, children: [ - { type: 'property', offset: 1, length: 9, columnOffset: 5, children: [ - { type: 'string', offset: 1, length: 4, value: 'id' }, - { type: 'string', offset: 7, length: 3, value: '$' } - ]}, - { type: 'property', offset: 12, length: 19, columnOffset: 15, children: [ - { type: 'string', offset: 12, length: 3, value: 'v' }, - { type: 'array', offset: 17, length: 13, children: [ - { type: 'null', offset: 19, length: 4, value: null }, - { type: 'null', offset: 25, length: 4, value: null } - ]} - ]} - ]} + { + type: 'object', offset: 0, length: 32, children: [ + { + type: 'property', offset: 1, length: 9, columnOffset: 5, children: [ + { type: 'string', offset: 1, length: 4, value: 'id' }, + { type: 'string', offset: 7, length: 3, value: '$' } + ] + }, + { + type: 'property', offset: 12, length: 19, columnOffset: 15, children: [ + { type: 'string', offset: 12, length: 3, value: 'v' }, + { + type: 'array', offset: 17, length: 13, children: [ + { type: 'null', offset: 19, length: 4, value: null }, + { type: 'null', offset: 25, length: 4, value: null } + ] + } + ] + } + ] + } ); }); test('tree: find location', () => { let root = parseTree('{ "key1": { "key11": [ "val111", "val112" ] }, "key2": [ { "key21": false, "key22": 221 }, null, [{}] ] }'); - assertNodeAtLocation(root, [ "key1"], { key11: [ 'val111', 'val112' ]}); - assertNodeAtLocation(root, [ "key1", "key11"], [ 'val111', 'val112' ]); - assertNodeAtLocation(root, [ "key1", "key11", 0], 'val111'); - assertNodeAtLocation(root, [ "key1", "key11", 1], 'val112'); - assertNodeAtLocation(root, [ "key1", "key11", 2], void 0); - assertNodeAtLocation(root, [ "key2", 0, "key21"], false); - assertNodeAtLocation(root, [ "key2", 0, "key22"], 221); - assertNodeAtLocation(root, [ "key2", 1], null); - assertNodeAtLocation(root, [ "key2", 2], [{}]); - assertNodeAtLocation(root, [ "key2", 2, 0], {}); + assertNodeAtLocation(root, ["key1"], { key11: ['val111', 'val112'] }); + assertNodeAtLocation(root, ["key1", "key11"], ['val111', 'val112']); + assertNodeAtLocation(root, ["key1", "key11", 0], 'val111'); + assertNodeAtLocation(root, ["key1", "key11", 1], 'val112'); + assertNodeAtLocation(root, ["key1", "key11", 2], void 0); + assertNodeAtLocation(root, ["key2", 0, "key21"], false); + assertNodeAtLocation(root, ["key2", 0, "key22"], 221); + assertNodeAtLocation(root, ["key2", 1], null); + assertNodeAtLocation(root, ["key2", 2], [{}]); + assertNodeAtLocation(root, ["key2", 2, 0], {}); }); }); diff --git a/src/vs/base/test/common/jsonEdit.test.ts b/src/vs/base/test/common/jsonEdit.test.ts index 6593efb4df12d..3eacab846a4ca 100644 --- a/src/vs/base/test/common/jsonEdit.test.ts +++ b/src/vs/base/test/common/jsonEdit.test.ts @@ -5,8 +5,8 @@ 'use strict'; import json = require('vs/base/common/json'); -import {FormattingOptions, Edit} from 'vs/base/common/jsonFormatter'; -import {setProperty, removeProperty} from 'vs/base/common/jsonEdit'; +import { FormattingOptions, Edit } from 'vs/base/common/jsonFormatter'; +import { setProperty, removeProperty } from 'vs/base/common/jsonEdit'; import assert = require('assert'); suite('JSON - edits', () => { @@ -25,7 +25,7 @@ suite('JSON - edits', () => { assert.equal(content, expected); } - let formatterOptions : FormattingOptions = { + let formatterOptions: FormattingOptions = { insertSpaces: true, tabSize: 2, eol: '\n' diff --git a/src/vs/base/test/common/keyCodes.test.ts b/src/vs/base/test/common/keyCodes.test.ts index 9ae049b420569..fe3850d4606f2 100644 --- a/src/vs/base/test/common/keyCodes.test.ts +++ b/src/vs/base/test/common/keyCodes.test.ts @@ -5,7 +5,7 @@ 'use strict'; import * as assert from 'assert'; -import {KeyCode, KeyMod, KeyChord, BinaryKeybindings} from 'vs/base/common/keyCodes'; +import { KeyCode, KeyMod, KeyChord, BinaryKeybindings } from 'vs/base/common/keyCodes'; interface ITestKeybinding { ctrlCmd?: boolean; @@ -18,7 +18,7 @@ interface ITestKeybinding { suite('keyCodes', () => { test('binary encoding', () => { - function test(keybinding:ITestKeybinding, k:number): void { + function test(keybinding: ITestKeybinding, k: number): void { keybinding = keybinding || { key: KeyCode.Unknown }; assert.equal(BinaryKeybindings.hasCtrlCmd(k), !!keybinding.ctrlCmd); assert.equal(BinaryKeybindings.hasShift(k), !!keybinding.shift); @@ -41,21 +41,21 @@ suite('keyCodes', () => { test({ key: KeyCode.Enter }, KeyCode.Enter); test({ key: KeyCode.Enter, chord: { key: KeyCode.Tab } }, KeyChord(KeyCode.Enter, KeyCode.Tab)); test({ ctrlCmd: false, shift: false, alt: false, winCtrl: false, key: KeyCode.Enter }, KeyCode.Enter); - test({ ctrlCmd: false, shift: false, alt: false, winCtrl: true, key: KeyCode.Enter }, KeyMod.WinCtrl | KeyCode.Enter); - test({ ctrlCmd: false, shift: false, alt: true, winCtrl: false, key: KeyCode.Enter }, KeyMod.Alt | KeyCode.Enter); - test({ ctrlCmd: false, shift: false, alt: true, winCtrl: true, key: KeyCode.Enter }, KeyMod.Alt | KeyMod.WinCtrl | KeyCode.Enter); - test({ ctrlCmd: false, shift: true, alt: false, winCtrl: false, key: KeyCode.Enter }, KeyMod.Shift | KeyCode.Enter); - test({ ctrlCmd: false, shift: true, alt: false, winCtrl: true, key: KeyCode.Enter }, KeyMod.Shift | KeyMod.WinCtrl | KeyCode.Enter); - test({ ctrlCmd: false, shift: true, alt: true, winCtrl: false, key: KeyCode.Enter }, KeyMod.Shift | KeyMod.Alt | KeyCode.Enter); - test({ ctrlCmd: false, shift: true, alt: true, winCtrl: true, key: KeyCode.Enter }, KeyMod.Shift | KeyMod.Alt | KeyMod.WinCtrl | KeyCode.Enter); - test({ ctrlCmd: true, shift: false, alt: false, winCtrl: false, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyCode.Enter); - test({ ctrlCmd: true, shift: false, alt: false, winCtrl: true, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.Enter); - test({ ctrlCmd: true, shift: false, alt: true, winCtrl: false, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.Enter); - test({ ctrlCmd: true, shift: false, alt: true, winCtrl: true, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyMod.Alt | KeyMod.WinCtrl | KeyCode.Enter); - test({ ctrlCmd: true, shift: true, alt: false, winCtrl: false, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter); - test({ ctrlCmd: true, shift: true, alt: false, winCtrl: true, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.WinCtrl | KeyCode.Enter); - test({ ctrlCmd: true, shift: true, alt: true, winCtrl: false, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.Alt | KeyCode.Enter); - test({ ctrlCmd: true, shift: true, alt: true, winCtrl: true, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.Alt | KeyMod.WinCtrl | KeyCode.Enter); + test({ ctrlCmd: false, shift: false, alt: false, winCtrl: true, key: KeyCode.Enter }, KeyMod.WinCtrl | KeyCode.Enter); + test({ ctrlCmd: false, shift: false, alt: true, winCtrl: false, key: KeyCode.Enter }, KeyMod.Alt | KeyCode.Enter); + test({ ctrlCmd: false, shift: false, alt: true, winCtrl: true, key: KeyCode.Enter }, KeyMod.Alt | KeyMod.WinCtrl | KeyCode.Enter); + test({ ctrlCmd: false, shift: true, alt: false, winCtrl: false, key: KeyCode.Enter }, KeyMod.Shift | KeyCode.Enter); + test({ ctrlCmd: false, shift: true, alt: false, winCtrl: true, key: KeyCode.Enter }, KeyMod.Shift | KeyMod.WinCtrl | KeyCode.Enter); + test({ ctrlCmd: false, shift: true, alt: true, winCtrl: false, key: KeyCode.Enter }, KeyMod.Shift | KeyMod.Alt | KeyCode.Enter); + test({ ctrlCmd: false, shift: true, alt: true, winCtrl: true, key: KeyCode.Enter }, KeyMod.Shift | KeyMod.Alt | KeyMod.WinCtrl | KeyCode.Enter); + test({ ctrlCmd: true, shift: false, alt: false, winCtrl: false, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyCode.Enter); + test({ ctrlCmd: true, shift: false, alt: false, winCtrl: true, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyMod.WinCtrl | KeyCode.Enter); + test({ ctrlCmd: true, shift: false, alt: true, winCtrl: false, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.Enter); + test({ ctrlCmd: true, shift: false, alt: true, winCtrl: true, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyMod.Alt | KeyMod.WinCtrl | KeyCode.Enter); + test({ ctrlCmd: true, shift: true, alt: false, winCtrl: false, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter); + test({ ctrlCmd: true, shift: true, alt: false, winCtrl: true, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.WinCtrl | KeyCode.Enter); + test({ ctrlCmd: true, shift: true, alt: true, winCtrl: false, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.Alt | KeyCode.Enter); + test({ ctrlCmd: true, shift: true, alt: true, winCtrl: true, key: KeyCode.Enter }, KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.Alt | KeyMod.WinCtrl | KeyCode.Enter); let encoded = KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_Y, KeyCode.KEY_Z); let encodedFirstPart = BinaryKeybindings.extractFirstPart(encoded); diff --git a/src/vs/base/test/common/map.test.ts b/src/vs/base/test/common/map.test.ts index 6c219c8fd8ec8..64d92dcf0ef38 100644 --- a/src/vs/base/test/common/map.test.ts +++ b/src/vs/base/test/common/map.test.ts @@ -5,7 +5,7 @@ 'use strict'; -import {BoundedLinkedMap, LRUCache, LinkedMap} from 'vs/base/common/map'; +import { BoundedLinkedMap, LRUCache, LinkedMap } from 'vs/base/common/map'; import * as assert from 'assert'; suite('Map', () => { diff --git a/src/vs/base/test/common/marshalling.test.ts b/src/vs/base/test/common/marshalling.test.ts index d8894de5699e2..675e9a6759ecb 100644 --- a/src/vs/base/test/common/marshalling.test.ts +++ b/src/vs/base/test/common/marshalling.test.ts @@ -6,14 +6,14 @@ import * as assert from 'assert'; import URI from 'vs/base/common/uri'; -import {parse, stringify} from 'vs/base/common/marshalling'; +import { parse, stringify } from 'vs/base/common/marshalling'; suite('Marshalling', () => { - test('RegExp', function() { + test('RegExp', function () { let value = /foo/img; let raw = stringify(value); - let clone = parse(raw); + let clone = parse(raw); assert.equal(value.source, clone.source); assert.equal(value.global, clone.global); @@ -24,7 +24,7 @@ suite('Marshalling', () => { test('URI', function () { let value = URI.from({ scheme: 'file', authority: 'server', path: '/shares/c#files', query: 'q', fragment: 'f' }); let raw = stringify(value); - let clone = parse(raw); + let clone = parse(raw); assert.equal(value.scheme, clone.scheme); assert.equal(value.authority, clone.authority); diff --git a/src/vs/base/test/common/network.test.ts b/src/vs/base/test/common/network.test.ts index 3dfb17aff2f64..e2354ef561408 100644 --- a/src/vs/base/test/common/network.test.ts +++ b/src/vs/base/test/common/network.test.ts @@ -7,7 +7,7 @@ import * as assert from 'assert'; import URI from 'vs/base/common/uri'; -function assertUrl(raw:string, scheme:string, domain:string, port:string, path:string, queryString:string, fragmentId:string): void { +function assertUrl(raw: string, scheme: string, domain: string, port: string, path: string, queryString: string, fragmentId: string): void { // check for equivalent behaviour var uri = URI.parse(raw); assert.equal(uri.scheme, scheme); diff --git a/src/vs/base/test/common/objects.test.ts b/src/vs/base/test/common/objects.test.ts index 1fd5d9ceb633f..b08748487712c 100644 --- a/src/vs/base/test/common/objects.test.ts +++ b/src/vs/base/test/common/objects.test.ts @@ -19,7 +19,7 @@ var checkNot = (one, other, msg) => { suite('Objects', () => { - test('equals', function() { + test('equals', function () { check(null, null, 'null'); check(undefined, undefined, 'undefined'); check(1234, 1234, 'numbers'); @@ -27,7 +27,7 @@ suite('Objects', () => { check('1234', '1234', 'strings'); check([], [], 'empty arrays'); // check(['', 123], ['', 123], 'arrays'); - check([[1,2,3], [4,5,6]], [[1,2,3], [4,5,6]], 'nested arrays'); + check([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]], 'nested arrays'); check({}, {}, 'empty objects'); check({ a: 1, b: '123' }, { a: 1, b: '123' }, 'objects'); check({ a: 1, b: '123' }, { b: '123', a: 1 }, 'objects (key order)'); @@ -51,14 +51,14 @@ suite('Objects', () => { checkNot('1234', 1234, 'string !== number'); - checkNot([[1,2,3], [4,5,6]], [[1,2,3], [4,5,6000]], 'arrays'); + checkNot([[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6000]], 'arrays'); checkNot({ a: { b: 1, c: 2 }, b: 3 }, { b: 3, a: { b: 9, c: 2 } }, 'objects'); }); - test('mixin - array', function() { + test('mixin - array', function () { - var foo:any = {}; - objects.mixin(foo, { bar: [1,2,3] }); + var foo: any = {}; + objects.mixin(foo, { bar: [1, 2, 3] }); assert(foo.bar); assert(Array.isArray(foo.bar)); @@ -68,12 +68,12 @@ suite('Objects', () => { assert.equal(foo.bar[2], 3); }); - test('mixin - no overwrite', function() { - var foo:any = { + test('mixin - no overwrite', function () { + var foo: any = { bar: '123' }; - var bar:any = { + var bar: any = { bar: '456' }; @@ -82,16 +82,16 @@ suite('Objects', () => { assert.equal(foo.bar, '123'); }); - test('cloneAndChange',() => { + test('cloneAndChange', () => { var o1 = { something: 'hello' }; var o = { o1: o1, o2: o1 }; - assert.deepEqual(objects.cloneAndChange(o,() => { }), o); + assert.deepEqual(objects.cloneAndChange(o, () => { }), o); }); - test('safeStringify', function() { + test('safeStringify', function () { var obj1 = { friend: null }; @@ -103,7 +103,7 @@ suite('Objects', () => { obj1.friend = obj2; obj2.friend = obj1; - var arr:any = [1]; + var arr: any = [1]; arr.push(arr); var circular = { @@ -127,31 +127,33 @@ suite('Objects', () => { a: 42, b: '[Circular]', c: [ - {friend: { - friend: '[Circular]' - }}, + { + friend: { + friend: '[Circular]' + } + }, '[Circular]' ], d: [1, '[Circular]', '[Circular]'] }); }); - test('derive', function() { + test('derive', function () { var someValue = 2; - function Base():void { + function Base(): void { //example } (Base).favoriteColor = 'blue'; - Base.prototype.test = function() { return 42; }; + Base.prototype.test = function () { return 42; }; - function Child():void { + function Child(): void { //example } - Child.prototype.test2 = function() { return 43; }; + Child.prototype.test2 = function () { return 43; }; Object.defineProperty(Child.prototype, 'getter', { - get: function() { return someValue; }, + get: function () { return someValue; }, enumerable: true, configurable: true }); diff --git a/src/vs/base/test/common/uri.test.ts b/src/vs/base/test/common/uri.test.ts index 0fd201af25597..a80a276f70f5e 100644 --- a/src/vs/base/test/common/uri.test.ts +++ b/src/vs/base/test/common/uri.test.ts @@ -6,7 +6,7 @@ import * as assert from 'assert'; import URI from 'vs/base/common/uri'; -import {normalize} from 'vs/base/common/paths'; +import { normalize } from 'vs/base/common/paths'; suite('URI', () => { test('file#toString', () => { @@ -368,7 +368,7 @@ suite('URI', () => { test('file://monacotools1/certificates/SSL/', '\\\\monacotools1\\certificates\\SSL\\'); }); - test('URI - http, query & toString', function() { + test('URI - http, query & toString', function () { let uri = URI.parse('https://go.microsoft.com/fwlink/?LinkId=518008'); assert.equal(uri.query, 'LinkId=518008'); @@ -404,7 +404,7 @@ suite('URI', () => { // console.profile(); // let c = 100000; // while (c-- > 0) { - for(let value of values) { + for (let value of values) { let data = value.toJSON(); let clone = URI.revive(data); diff --git a/src/vs/base/test/node/config.test.ts b/src/vs/base/test/node/config.test.ts index c338d9a6ba007..ba968101d7616 100644 --- a/src/vs/base/test/node/config.test.ts +++ b/src/vs/base/test/node/config.test.ts @@ -12,7 +12,7 @@ import path = require('path'); import fs = require('fs'); import extfs = require('vs/base/node/extfs'); import uuid = require('vs/base/common/uuid'); -import {ConfigWatcher} from 'vs/base/node/config'; +import { ConfigWatcher } from 'vs/base/node/config'; suite('Config', () => { diff --git a/src/vs/base/test/node/port.test.ts b/src/vs/base/test/node/port.test.ts index 185501d647401..840cbf97aa0e7 100644 --- a/src/vs/base/test/node/port.test.ts +++ b/src/vs/base/test/node/port.test.ts @@ -18,7 +18,7 @@ suite('Ports', () => { // create a server to block this port const server = net.createServer(); - server.listen(initialPort, null, null, () =>  { + server.listen(initialPort, null, null, () => { // once listening, find another free port and assert that the port is different from the opened one ports.findFreePort(7000, 50, 300000, (freePort) => { diff --git a/src/vs/base/worker/defaultWorkerFactory.ts b/src/vs/base/worker/defaultWorkerFactory.ts index 612809e6ef6fc..c9ba5eadbd444 100644 --- a/src/vs/base/worker/defaultWorkerFactory.ts +++ b/src/vs/base/worker/defaultWorkerFactory.ts @@ -5,9 +5,9 @@ 'use strict'; import * as flags from 'vs/base/common/flags'; -import {logOnceWebWorkerWarning, IWorker, IWorkerCallback, IWorkerFactory} from 'vs/base/common/worker/simpleWorker'; +import { logOnceWebWorkerWarning, IWorker, IWorkerCallback, IWorkerFactory } from 'vs/base/common/worker/simpleWorker'; -function defaultGetWorkerUrl(workerId:string, label:string): string { +function defaultGetWorkerUrl(workerId: string, label: string): string { return require.toUrl('./' + workerId) + '#' + label; } var getWorkerUrl = flags.getCrossOriginWorkerScriptUrl || defaultGetWorkerUrl; @@ -19,14 +19,14 @@ var getWorkerUrl = flags.getCrossOriginWorkerScriptUrl || defaultGetWorkerUrl; */ class WebWorker implements IWorker { - private id:number; - private worker:Worker; + private id: number; + private worker: Worker; - constructor(moduleId:string, id:number, label:string, onMessageCallback:IWorkerCallback, onErrorCallback:(err:any)=>void) { + constructor(moduleId: string, id: number, label: string, onMessageCallback: IWorkerCallback, onErrorCallback: (err: any) => void) { this.id = id; this.worker = new Worker(getWorkerUrl('workerMain.js', label)); this.postMessage(moduleId); - this.worker.onmessage = function (ev:any) { + this.worker.onmessage = function (ev: any) { onMessageCallback(ev.data); }; if (typeof this.worker.addEventListener === 'function') { @@ -38,7 +38,7 @@ class WebWorker implements IWorker { return this.id; } - public postMessage(msg:string): void { + public postMessage(msg: string): void { if (this.worker) { this.worker.postMessage(msg); } @@ -55,14 +55,14 @@ export class DefaultWorkerFactory implements IWorkerFactory { private static LAST_WORKER_ID = 0; private _label: string; - private _webWorkerFailedBeforeError:any; + private _webWorkerFailedBeforeError: any; - constructor(label:string) { + constructor(label: string) { this._label = label; this._webWorkerFailedBeforeError = false; } - public create(moduleId:string, onMessageCallback:IWorkerCallback, onErrorCallback:(err:any)=>void):IWorker { + public create(moduleId: string, onMessageCallback: IWorkerCallback, onErrorCallback: (err: any) => void): IWorker { let workerId = (++DefaultWorkerFactory.LAST_WORKER_ID); if (this._webWorkerFailedBeforeError) { diff --git a/src/vs/base/worker/workerMain.ts b/src/vs/base/worker/workerMain.ts index 97dbf33fb41eb..f80f9d44e16b9 100644 --- a/src/vs/base/worker/workerMain.ts +++ b/src/vs/base/worker/workerMain.ts @@ -18,15 +18,15 @@ catchError: true }); - let loadCode = function(moduleId) { - require([moduleId], function(ws) { - setTimeout(function() { - let messageHandler = ws.create((msg:any) => { + let loadCode = function (moduleId) { + require([moduleId], function (ws) { + setTimeout(function () { + let messageHandler = ws.create((msg: any) => { (self).postMessage(msg); }, null); self.onmessage = (e) => messageHandler.onmessage(e.data); - while(beforeReadyMessages.length > 0) { + while (beforeReadyMessages.length > 0) { self.onmessage(beforeReadyMessages.shift()); } }, 0); @@ -34,7 +34,7 @@ }; let isFirstMessage = true; - let beforeReadyMessages:MessageEvent[] = []; + let beforeReadyMessages: MessageEvent[] = []; self.onmessage = (message) => { if (!isFirstMessage) { beforeReadyMessages.push(message); diff --git a/src/vs/code/common/windows.ts b/src/vs/code/common/windows.ts index 7e268b1945c25..70133a7223369 100644 --- a/src/vs/code/common/windows.ts +++ b/src/vs/code/common/windows.ts @@ -21,7 +21,7 @@ export class ActiveWindowManager implements IDisposable { private disposables: IDisposable[] = []; private _activeWindowId: number; - constructor(@IWindowEventService private windowService: IWindowEventService) { + constructor( @IWindowEventService private windowService: IWindowEventService) { this.disposables.push(this.windowService.onNewWindowOpen(windowId => this.setActiveWindow(windowId))); this.disposables.push(this.windowService.onWindowFocus(windowId => this.setActiveWindow(windowId))); } @@ -31,7 +31,7 @@ export class ActiveWindowManager implements IDisposable { } public get activeClientId(): string { - return `window:${ this._activeWindowId }`; + return `window:${this._activeWindowId}`; } public dispose() { diff --git a/src/vs/code/electron-main/launch.ts b/src/vs/code/electron-main/launch.ts index 185cd639486e0..ac17f0d6e6600 100644 --- a/src/vs/code/electron-main/launch.ts +++ b/src/vs/code/electron-main/launch.ts @@ -65,7 +65,7 @@ export class LaunchService implements ILaunchService { @ILogService private logService: ILogService, @IWindowsService private windowsService: IWindowsService, @IURLService private urlService: IURLService - ) {} + ) { } start(args: ParsedArgs, userEnv: IProcessEnvironment): TPromise { this.logService.log('Received data from other instance: ', args, userEnv); diff --git a/src/vs/code/electron-main/lifecycle.ts b/src/vs/code/electron-main/lifecycle.ts index ec6bbb747023e..cc2b48a12ff34 100644 --- a/src/vs/code/electron-main/lifecycle.ts +++ b/src/vs/code/electron-main/lifecycle.ts @@ -7,7 +7,7 @@ import { EventEmitter } from 'events'; import { ipcMain as ipc, app } from 'electron'; -import { TPromise, TValueCallback } from 'vs/base/common/winjs.base'; +import { TPromise, TValueCallback } from 'vs/base/common/winjs.base'; import { ReadyState, VSCodeWindow } from 'vs/code/electron-main/window'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; diff --git a/src/vs/code/electron-main/log.ts b/src/vs/code/electron-main/log.ts index 27285dccdd3d5..caa630d6ad2e5 100644 --- a/src/vs/code/electron-main/log.ts +++ b/src/vs/code/electron-main/log.ts @@ -19,7 +19,7 @@ export class MainLogService implements ILogService { _serviceBrand: any; - constructor(@IEnvironmentService private environmentService: IEnvironmentService) { + constructor( @IEnvironmentService private environmentService: IEnvironmentService) { } log(...args: any[]): void { diff --git a/src/vs/code/electron-main/main.ts b/src/vs/code/electron-main/main.ts index fd59d59862400..b08da75351fb0 100644 --- a/src/vs/code/electron-main/main.ts +++ b/src/vs/code/electron-main/main.ts @@ -273,7 +273,7 @@ function setupIPC(accessor: ServicesAccessor): TPromise { promise = service.getMainProcessId() .then(processId => { logService.log('Sending some foreground love to the running instance:', processId); - + try { const { allowSetForegroundWindow } = require.__$__nodeRequire('windows-foreground-love'); allowSetForegroundWindow(processId); diff --git a/src/vs/code/electron-main/storage.ts b/src/vs/code/electron-main/storage.ts index 3f337a5495d23..d3f1351b6cca4 100644 --- a/src/vs/code/electron-main/storage.ts +++ b/src/vs/code/electron-main/storage.ts @@ -26,7 +26,7 @@ export class StorageService implements IStorageService { private dbPath: string; private database: any = null; - constructor(@IEnvironmentService private environmentService: IEnvironmentService) { + constructor( @IEnvironmentService private environmentService: IEnvironmentService) { this.dbPath = path.join(environmentService.userDataPath, 'storage.json'); } diff --git a/src/vs/code/electron-main/update-manager.ts b/src/vs/code/electron-main/update-manager.ts index 36cb3fa03e7ab..d84105e84b7cb 100644 --- a/src/vs/code/electron-main/update-manager.ts +++ b/src/vs/code/electron-main/update-manager.ts @@ -251,6 +251,6 @@ export class UpdateManager extends EventEmitter implements IUpdateService { const platform = process.platform === 'linux' ? `linux-${process.arch}` : process.platform; - return `${ product.updateUrl }/api/update/${ platform }/${ channel }/${ product.commit }`; + return `${product.updateUrl}/api/update/${platform}/${channel}/${product.commit}`; } } diff --git a/src/vs/code/electron-main/windows.ts b/src/vs/code/electron-main/windows.ts index d4a9327154ff1..8cdb060be3256 100644 --- a/src/vs/code/electron-main/windows.ts +++ b/src/vs/code/electron-main/windows.ts @@ -24,7 +24,7 @@ import { IConfigurationService } from 'vs/platform/configuration/common/configur import { IUpdateService, IUpdate } from 'vs/code/electron-main/update-manager'; import { ILogService } from 'vs/code/electron-main/log'; import { IWindowEventService } from 'vs/code/common/windows'; -import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; +import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import CommonEvent, { Emitter } from 'vs/base/common/event'; import product from 'vs/platform/product'; import { ParsedArgs } from 'vs/platform/environment/node/argv'; @@ -126,7 +126,7 @@ export class WindowEventService implements IWindowEventService { _serviceBrand: any; - constructor(@IWindowsService private windowsService: IWindowsService) { } + constructor( @IWindowsService private windowsService: IWindowsService) { } public get onWindowFocus(): CommonEvent { return this.windowsService.onWindowFocus; @@ -465,7 +465,7 @@ export class WindowsManager implements IWindowsService { const windows = this.getWindows(); const window = this.getWindowById(windowId); window.send('vscode:switchWindow', windows.map(w => { - return {path: w.openedWorkspacePath, title: w.win.getTitle(), id: w.id}; + return { path: w.openedWorkspacePath, title: w.win.getTitle(), id: w.id }; })); }); diff --git a/src/vs/code/node/cli.ts b/src/vs/code/node/cli.ts index 7097b5db30ed5..0ed40237eacd6 100644 --- a/src/vs/code/node/cli.ts +++ b/src/vs/code/node/cli.ts @@ -31,7 +31,7 @@ export function main(argv: string[]): TPromise { if (args.help) { console.log(buildHelpMessage(product.nameLong, product.applicationName, pkg.version)); } else if (args.version) { - console.log(`${ pkg.version }\n${ product.commit }`); + console.log(`${pkg.version}\n${product.commit}`); } else if (shouldSpawnCliProcess(args)) { const mainCli = new TPromise(c => require(['vs/code/node/cliProcessMain'], c)); return mainCli.then(cli => cli.main(args)); diff --git a/src/vs/code/node/cliProcessMain.ts b/src/vs/code/node/cliProcessMain.ts index 7893453743dca..866122eba7271 100644 --- a/src/vs/code/node/cliProcessMain.ts +++ b/src/vs/code/node/cliProcessMain.ts @@ -30,24 +30,24 @@ import { RequestService } from 'vs/platform/request/node/requestService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ConfigurationService } from 'vs/platform/configuration/node/configurationService'; import { AppInsightsAppender } from 'vs/platform/telemetry/node/appInsightsAppender'; -import {mkdirp} from 'vs/base/node/pfs'; +import { mkdirp } from 'vs/base/node/pfs'; const notFound = id => localize('notFound', "Extension '{0}' not found.", id); const notInstalled = id => localize('notInstalled', "Extension '{0}' is not installed.", id); const useId = localize('useId', "Make sure you use the full extension ID, including the publisher, eg: {0}", 'ms-vscode.csharp'); function getId(manifest: IExtensionManifest): string { - return `${ manifest.publisher }.${ manifest.name }`; + return `${manifest.publisher}.${manifest.name}`; } -type Task = { ():TPromise }; +type Task = { (): TPromise }; class Main { constructor( @IExtensionManagementService private extensionManagementService: IExtensionManagementService, @IExtensionGalleryService private extensionGalleryService: IExtensionGalleryService - ) {} + ) { } run(argv: ParsedArgs): TPromise { // TODO@joao - make this contributable @@ -110,7 +110,7 @@ class Main { const [extension] = result.firstPage; if (!extension) { - return TPromise.wrapError(`${ notFound(id) }\n${ useId }`); + return TPromise.wrapError(`${notFound(id)}\n${useId}`); } console.log(localize('foundExtension', "Found '{0}' in the marketplace.", id)); @@ -131,7 +131,7 @@ class Main { const [extension] = installed.filter(e => getId(e.manifest) === id); if (!extension) { - return TPromise.wrapError(`${ notInstalled(id) }\n${ useId }`); + return TPromise.wrapError(`${notInstalled(id)}\n${useId}`); } console.log(localize('uninstalling', "Uninstalling {0}...", id)); diff --git a/src/vs/code/node/sharedProcessMain.ts b/src/vs/code/node/sharedProcessMain.ts index 6e873db4c3958..86313446bfd94 100644 --- a/src/vs/code/node/sharedProcessMain.ts +++ b/src/vs/code/node/sharedProcessMain.ts @@ -30,8 +30,8 @@ import { TelemetryAppenderChannel } from 'vs/platform/telemetry/common/telemetry import { TelemetryService, ITelemetryServiceConfig } from 'vs/platform/telemetry/common/telemetryService'; import { AppInsightsAppender } from 'vs/platform/telemetry/node/appInsightsAppender'; import { ISharedProcessInitData } from './sharedProcess'; -import {IChoiceService} from 'vs/platform/message/common/message'; -import {ChoiceChannelClient} from 'vs/platform/message/common/messageIpc'; +import { IChoiceService } from 'vs/platform/message/common/message'; +import { ChoiceChannelClient } from 'vs/platform/message/common/messageIpc'; import { WindowEventChannelClient } from 'vs/code/common/windowsIpc'; import { IWindowEventService, ActiveWindowManager } from 'vs/code/common/windows'; @@ -66,7 +66,7 @@ function main(server: Server, initData: ISharedProcessInitData): void { services.set(IConfigurationService, new SyncDescriptor(ConfigurationService)); services.set(IRequestService, new SyncDescriptor(RequestService)); - const windowEventService:IWindowEventService = new WindowEventChannelClient(server.getChannel('windowEvent', { + const windowEventService: IWindowEventService = new WindowEventChannelClient(server.getChannel('windowEvent', { routeCall: (command: any, arg: any) => { return 'main'; } diff --git a/src/vs/code/test/node/argv.test.ts b/src/vs/code/test/node/argv.test.ts index dec7e806bddd2..c322fc5f96f8a 100644 --- a/src/vs/code/test/node/argv.test.ts +++ b/src/vs/code/test/node/argv.test.ts @@ -5,11 +5,11 @@ 'use strict'; import assert = require('assert'); -import {formatOptions} from 'vs/platform/environment/node/argv'; +import { formatOptions } from 'vs/platform/environment/node/argv'; suite('formatOptions', () => { test('Text should display small columns correctly', () => { - assert.equal(formatOptions({'foo': 'bar'}, 80), ' foo bar'); + assert.equal(formatOptions({ 'foo': 'bar' }, 80), ' foo bar'); assert.equal( formatOptions({ 'f': 'bar', diff --git a/src/vs/css.d.ts b/src/vs/css.d.ts index 4a064bb321eb4..11a10ed5950c1 100644 --- a/src/vs/css.d.ts +++ b/src/vs/css.d.ts @@ -2,4 +2,4 @@ * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ - + diff --git a/src/vs/editor/browser/codeEditor.ts b/src/vs/editor/browser/codeEditor.ts index 9374587ae6cd4..21b25e366e9fc 100644 --- a/src/vs/editor/browser/codeEditor.ts +++ b/src/vs/editor/browser/codeEditor.ts @@ -4,21 +4,21 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; -import {ICommandService} from 'vs/platform/commands/common/commands'; -import {IContextKeyService} from 'vs/platform/contextkey/common/contextkey'; -import {IEditorOptions} from 'vs/editor/common/editorCommon'; -import {IEditorContributionCtor} from 'vs/editor/browser/editorBrowser'; -import {ICodeEditorService} from 'vs/editor/common/services/codeEditorService'; -import {CodeEditorWidget} from 'vs/editor/browser/widget/codeEditorWidget'; -import {EditorAction, CommonEditorRegistry} from 'vs/editor/common/editorCommonExtensions'; -import {EditorBrowserRegistry} from 'vs/editor/browser/editorBrowserExtensions'; +import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; +import { ICommandService } from 'vs/platform/commands/common/commands'; +import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; +import { IEditorOptions } from 'vs/editor/common/editorCommon'; +import { IEditorContributionCtor } from 'vs/editor/browser/editorBrowser'; +import { ICodeEditorService } from 'vs/editor/common/services/codeEditorService'; +import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget'; +import { EditorAction, CommonEditorRegistry } from 'vs/editor/common/editorCommonExtensions'; +import { EditorBrowserRegistry } from 'vs/editor/browser/editorBrowserExtensions'; export class CodeEditor extends CodeEditorWidget { constructor( - domElement:HTMLElement, - options:IEditorOptions, + domElement: HTMLElement, + options: IEditorOptions, @IInstantiationService instantiationService: IInstantiationService, @ICodeEditorService codeEditorService: ICodeEditorService, @ICommandService commandService: ICommandService, diff --git a/src/vs/editor/browser/config/configuration.ts b/src/vs/editor/browser/config/configuration.ts index 56cbb755aa4f0..bfafc275e52e0 100644 --- a/src/vs/editor/browser/config/configuration.ts +++ b/src/vs/editor/browser/config/configuration.ts @@ -4,14 +4,14 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import Event, {Emitter} from 'vs/base/common/event'; -import {Disposable} from 'vs/base/common/lifecycle'; +import Event, { Emitter } from 'vs/base/common/event'; +import { Disposable } from 'vs/base/common/lifecycle'; import * as platform from 'vs/base/common/platform'; import * as browser from 'vs/base/browser/browser'; -import {CommonEditorConfiguration} from 'vs/editor/common/config/commonEditorConfig'; -import {IDimension, FontInfo, BareFontInfo} from 'vs/editor/common/editorCommon'; -import {ElementSizeObserver} from 'vs/editor/browser/config/elementSizeObserver'; -import {FastDomNode} from 'vs/base/browser/styleMutator'; +import { CommonEditorConfiguration } from 'vs/editor/common/config/commonEditorConfig'; +import { IDimension, FontInfo, BareFontInfo } from 'vs/editor/common/editorCommon'; +import { ElementSizeObserver } from 'vs/editor/browser/config/elementSizeObserver'; +import { FastDomNode } from 'vs/base/browser/styleMutator'; class CSSBasedConfigurationCache { @@ -48,12 +48,12 @@ class CharWidthReader { public get width(): number { return this._width; } - constructor(chr:string) { + constructor(chr: string) { this._chr = chr; this._width = 0; } - public render(out:HTMLSpanElement): void { + public render(out: HTMLSpanElement): void { if (this._chr === ' ') { let htmlString = ' '; // Repeat character 256 (2^8) times @@ -71,7 +71,7 @@ class CharWidthReader { } } - public read(out:HTMLSpanElement): void { + public read(out: HTMLSpanElement): void { this._width = out.offsetWidth / 256; } } @@ -148,11 +148,11 @@ class CSSBasedConfiguration extends Disposable { } } - private static _testElementId(index:number): string { + private static _testElementId(index: number): string { return 'editorSizeProvider' + index; } - private static _createTestElements(bareFontInfo: BareFontInfo, readers:CharWidthReader[]): HTMLElement { + private static _createTestElements(bareFontInfo: BareFontInfo, readers: CharWidthReader[]): HTMLElement { let container = document.createElement('div'); Configuration.applyFontInfoSlow(container, bareFontInfo); container.style.position = 'absolute'; @@ -174,13 +174,13 @@ class CSSBasedConfiguration extends Disposable { return container; } - private static _readFromTestElements(readers:CharWidthReader[]): void { + private static _readFromTestElements(readers: CharWidthReader[]): void { for (let i = 0, len = readers.length; i < len; i++) { readers[i].read(document.getElementById(this._testElementId(i))); } } - private static _runReaders(bareFontInfo: BareFontInfo, readers:CharWidthReader[]): void { + private static _runReaders(bareFontInfo: BareFontInfo, readers: CharWidthReader[]): void { // Create a test container with all these test elements let testContainer = this._createTestElements(bareFontInfo, readers); @@ -236,7 +236,7 @@ export class Configuration extends CommonEditorConfiguration { domNode.setLineHeight(fontInfo.lineHeight); } - constructor(options:any, referenceDomElement:HTMLElement = null) { + constructor(options: any, referenceDomElement: HTMLElement = null) { super(options, new ElementSizeObserver(referenceDomElement, () => this._onReferenceDomElementSizeChanged())); this._register(CSSBasedConfiguration.INSTANCE.onDidChange(() => () => this._onCSSBasedConfigurationChanged())); @@ -256,7 +256,7 @@ export class Configuration extends CommonEditorConfiguration { this._recomputeOptions(); } - public observeReferenceElement(dimension?:IDimension): void { + public observeReferenceElement(dimension?: IDimension): void { this._elementSizeObserver.observe(dimension); } @@ -265,7 +265,7 @@ export class Configuration extends CommonEditorConfiguration { super.dispose(); } - protected _getEditorClassName(theme:string, fontLigatures:boolean): string { + protected _getEditorClassName(theme: string, fontLigatures: boolean): string { let extra = ''; if (browser.isIE11orEarlier) { extra += 'ie '; @@ -298,7 +298,7 @@ export class Configuration extends CommonEditorConfiguration { return browser.canUseTranslate3d && browser.getZoomLevel() === 0; } - protected readConfiguration(bareFontInfo:BareFontInfo): FontInfo { + protected readConfiguration(bareFontInfo: BareFontInfo): FontInfo { return CSSBasedConfiguration.INSTANCE.readConfiguration(bareFontInfo); } } diff --git a/src/vs/editor/browser/config/elementSizeObserver.ts b/src/vs/editor/browser/config/elementSizeObserver.ts index f7e25066845d5..2860d2caca9c0 100644 --- a/src/vs/editor/browser/config/elementSizeObserver.ts +++ b/src/vs/editor/browser/config/elementSizeObserver.ts @@ -4,19 +4,19 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {Disposable} from 'vs/base/common/lifecycle'; -import {IDimension} from 'vs/editor/common/editorCommon'; -import {IElementSizeObserver} from 'vs/editor/common/config/commonEditorConfig'; +import { Disposable } from 'vs/base/common/lifecycle'; +import { IDimension } from 'vs/editor/common/editorCommon'; +import { IElementSizeObserver } from 'vs/editor/common/config/commonEditorConfig'; export class ElementSizeObserver extends Disposable implements IElementSizeObserver { - private referenceDomElement:HTMLElement; - private measureReferenceDomElementToken:number; - private changeCallback:()=>void; - private width:number; - private height:number; + private referenceDomElement: HTMLElement; + private measureReferenceDomElementToken: number; + private changeCallback: () => void; + private width: number; + private height: number; - constructor(referenceDomElement:HTMLElement, changeCallback:()=>void) { + constructor(referenceDomElement: HTMLElement, changeCallback: () => void) { super(); this.referenceDomElement = referenceDomElement; this.changeCallback = changeCallback; @@ -52,11 +52,11 @@ export class ElementSizeObserver extends Disposable implements IElementSizeObser } } - public observe(dimension?:IDimension): void { + public observe(dimension?: IDimension): void { this.measureReferenceDomElement(true, dimension); } - private measureReferenceDomElement(callChangeCallback:boolean, dimension?:IDimension): void { + private measureReferenceDomElement(callChangeCallback: boolean, dimension?: IDimension): void { var observedWidth = 0; var observedHeight = 0; if (dimension) { diff --git a/src/vs/editor/browser/controller/input/textAreaWrapper.ts b/src/vs/editor/browser/controller/input/textAreaWrapper.ts index 3037fc23a0da9..86c22c5d88a6f 100644 --- a/src/vs/editor/browser/controller/input/textAreaWrapper.ts +++ b/src/vs/editor/browser/controller/input/textAreaWrapper.ts @@ -4,18 +4,18 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import Event, {Emitter} from 'vs/base/common/event'; -import {Disposable} from 'vs/base/common/lifecycle'; +import Event, { Emitter } from 'vs/base/common/event'; +import { Disposable } from 'vs/base/common/lifecycle'; import * as browser from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; -import {IKeyboardEvent} from 'vs/base/browser/keyboardEvent'; -import {IClipboardEvent, ICompositionEvent, IKeyboardEventWrapper, ITextAreaWrapper} from 'vs/editor/common/controller/textAreaState'; +import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; +import { IClipboardEvent, ICompositionEvent, IKeyboardEventWrapper, ITextAreaWrapper } from 'vs/editor/common/controller/textAreaState'; class ClipboardEventWrapper implements IClipboardEvent { - private _event:ClipboardEvent; + private _event: ClipboardEvent; - constructor(event:ClipboardEvent) { + constructor(event: ClipboardEvent) { this._event = event; } @@ -29,7 +29,7 @@ class ClipboardEventWrapper implements IClipboardEvent { return false; } - public setTextData(text:string): void { + public setTextData(text: string): void { if (this._event.clipboardData) { this._event.clipboardData.setData('text/plain', text); this._event.preventDefault(); @@ -64,11 +64,11 @@ class KeyboardEventWrapper implements IKeyboardEventWrapper { public _actual: IKeyboardEvent; - constructor(actual:IKeyboardEvent) { + constructor(actual: IKeyboardEvent) { this._actual = actual; } - public equals(keybinding:number): boolean { + public equals(keybinding: number): boolean { return this._actual.equals(keybinding); } @@ -129,9 +129,9 @@ export class TextAreaWrapper extends Disposable implements ITextAreaWrapper { this._register(dom.addDisposableListener(this._textArea, 'compositionupdate', (e) => this._onCompositionUpdate.fire(e))); this._register(dom.addDisposableListener(this._textArea, 'compositionend', (e) => this._onCompositionEnd.fire(e))); this._register(dom.addDisposableListener(this._textArea, 'input', (e) => this._onInput.fire())); - this._register(dom.addDisposableListener(this._textArea, 'cut', (e:ClipboardEvent) => this._onCut.fire(new ClipboardEventWrapper(e)))); - this._register(dom.addDisposableListener(this._textArea, 'copy', (e:ClipboardEvent) => this._onCopy.fire(new ClipboardEventWrapper(e)))); - this._register(dom.addDisposableListener(this._textArea, 'paste', (e:ClipboardEvent) => this._onPaste.fire(new ClipboardEventWrapper(e)))); + this._register(dom.addDisposableListener(this._textArea, 'cut', (e: ClipboardEvent) => this._onCut.fire(new ClipboardEventWrapper(e)))); + this._register(dom.addDisposableListener(this._textArea, 'copy', (e: ClipboardEvent) => this._onCopy.fire(new ClipboardEventWrapper(e)))); + this._register(dom.addDisposableListener(this._textArea, 'paste', (e: ClipboardEvent) => this._onPaste.fire(new ClipboardEventWrapper(e)))); } public get actual(): HTMLTextAreaElement { @@ -143,7 +143,7 @@ export class TextAreaWrapper extends Disposable implements ITextAreaWrapper { return this._textArea.value; } - public setValue(reason:string, value:string): void { + public setValue(reason: string, value: string): void { // console.log('reason: ' + reason + ', current value: ' + this._textArea.value + ' => new value: ' + value); this._textArea.value = value; } @@ -156,7 +156,7 @@ export class TextAreaWrapper extends Disposable implements ITextAreaWrapper { return this._textArea.selectionEnd; } - public setSelectionRange(selectionStart:number, selectionEnd:number): void { + public setSelectionRange(selectionStart: number, selectionEnd: number): void { let activeElement = document.activeElement; if (activeElement === this._textArea) { this._textArea.setSelectionRange(selectionStart, selectionEnd); @@ -165,13 +165,13 @@ export class TextAreaWrapper extends Disposable implements ITextAreaWrapper { } } - private _setSelectionRangeJumpy(selectionStart:number, selectionEnd:number): void { + private _setSelectionRangeJumpy(selectionStart: number, selectionEnd: number): void { try { let scrollState = dom.saveParentsScrollTop(this._textArea); this._textArea.focus(); this._textArea.setSelectionRange(selectionStart, selectionEnd); dom.restoreParentsScrollTop(this._textArea, scrollState); - } catch(e) { + } catch (e) { // Sometimes IE throws when setting selection (e.g. textarea is off-DOM) console.log('an error has been thrown!'); } diff --git a/src/vs/editor/browser/controller/keyboardHandler.ts b/src/vs/editor/browser/controller/keyboardHandler.ts index a8040a835af69..070e69cb887ac 100644 --- a/src/vs/editor/browser/controller/keyboardHandler.ts +++ b/src/vs/editor/browser/controller/keyboardHandler.ts @@ -4,46 +4,46 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {IDisposable, dispose} from 'vs/base/common/lifecycle'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import * as browser from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; -import {IKeyboardEvent} from 'vs/base/browser/keyboardEvent'; -import {StyleMutator} from 'vs/base/browser/styleMutator'; -import {GlobalScreenReaderNVDA} from 'vs/editor/common/config/commonEditorConfig'; -import {TextAreaHandler} from 'vs/editor/common/controller/textAreaHandler'; -import {TextAreaStrategy} from 'vs/editor/common/controller/textAreaState'; -import {Range} from 'vs/editor/common/core/range'; +import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; +import { StyleMutator } from 'vs/base/browser/styleMutator'; +import { GlobalScreenReaderNVDA } from 'vs/editor/common/config/commonEditorConfig'; +import { TextAreaHandler } from 'vs/editor/common/controller/textAreaHandler'; +import { TextAreaStrategy } from 'vs/editor/common/controller/textAreaState'; +import { Range } from 'vs/editor/common/core/range'; import * as editorCommon from 'vs/editor/common/editorCommon'; -import {ViewEventHandler} from 'vs/editor/common/viewModel/viewEventHandler'; -import {IViewController} from 'vs/editor/browser/editorBrowser'; -import {Configuration} from 'vs/editor/browser/config/configuration'; -import {ViewContext} from 'vs/editor/common/view/viewContext'; -import {VisibleRange} from 'vs/editor/common/view/renderingContext'; -import {TextAreaWrapper} from 'vs/editor/browser/controller/input/textAreaWrapper'; +import { ViewEventHandler } from 'vs/editor/common/viewModel/viewEventHandler'; +import { IViewController } from 'vs/editor/browser/editorBrowser'; +import { Configuration } from 'vs/editor/browser/config/configuration'; +import { ViewContext } from 'vs/editor/common/view/viewContext'; +import { VisibleRange } from 'vs/editor/common/view/renderingContext'; +import { TextAreaWrapper } from 'vs/editor/browser/controller/input/textAreaWrapper'; export interface IKeyboardHandlerHelper { - viewDomNode:HTMLElement; - textArea:HTMLTextAreaElement; - visibleRangeForPositionRelativeToEditor(lineNumber:number, column:number): VisibleRange; + viewDomNode: HTMLElement; + textArea: HTMLTextAreaElement; + visibleRangeForPositionRelativeToEditor(lineNumber: number, column: number): VisibleRange; flushAnyAccumulatedEvents(): void; } export class KeyboardHandler extends ViewEventHandler implements IDisposable { - private _context:ViewContext; - private viewController:IViewController; - private viewHelper:IKeyboardHandlerHelper; - private textArea:TextAreaWrapper; - private textAreaHandler:TextAreaHandler; - private _toDispose:IDisposable[]; + private _context: ViewContext; + private viewController: IViewController; + private viewHelper: IKeyboardHandlerHelper; + private textArea: TextAreaWrapper; + private textAreaHandler: TextAreaHandler; + private _toDispose: IDisposable[]; - private contentLeft:number; - private contentWidth:number; - private scrollLeft:number; + private contentLeft: number; + private contentWidth: number; + private scrollLeft: number; - private visibleRange:VisibleRange; + private visibleRange: VisibleRange; - constructor(context:ViewContext, viewController:IViewController, viewHelper:IKeyboardHandlerHelper) { + constructor(context: ViewContext, viewController: IViewController, viewHelper: IKeyboardHandlerHelper) { super(); this._context = context; @@ -74,7 +74,7 @@ export class KeyboardHandler extends ViewEventHandler implements IDisposable { let lineNumber = e.showAtLineNumber; let column = e.showAtColumn; - let revealPositionEvent:editorCommon.IViewRevealRangeEvent = { + let revealPositionEvent: editorCommon.IViewRevealRangeEvent = { range: new Range(lineNumber, column, lineNumber, column), verticalType: editorCommon.VerticalRevealType.Simple, revealHorizontal: true, @@ -171,7 +171,7 @@ export class KeyboardHandler extends ViewEventHandler implements IDisposable { return false; } - public onScrollChanged(e:editorCommon.IScrollEvent): boolean { + public onScrollChanged(e: editorCommon.IScrollEvent): boolean { this.scrollLeft = e.scrollLeft; if (this.visibleRange) { StyleMutator.setTop(this.textArea.actual, this.visibleRange.top); @@ -180,18 +180,18 @@ export class KeyboardHandler extends ViewEventHandler implements IDisposable { return false; } - public onViewFocusChanged(isFocused:boolean): boolean { + public onViewFocusChanged(isFocused: boolean): boolean { this.textAreaHandler.setHasFocus(isFocused); return false; } - private _lastCursorSelectionChanged:editorCommon.IViewCursorSelectionChangedEvent = null; - public onCursorSelectionChanged(e:editorCommon.IViewCursorSelectionChangedEvent): boolean { + private _lastCursorSelectionChanged: editorCommon.IViewCursorSelectionChangedEvent = null; + public onCursorSelectionChanged(e: editorCommon.IViewCursorSelectionChangedEvent): boolean { this._lastCursorSelectionChanged = e; return false; } - public onLayoutChanged(layoutInfo:editorCommon.EditorLayoutInfo): boolean { + public onLayoutChanged(layoutInfo: editorCommon.EditorLayoutInfo): boolean { this.contentLeft = layoutInfo.contentLeft; this.contentWidth = layoutInfo.contentWidth; return false; diff --git a/src/vs/editor/browser/controller/mouseHandler.ts b/src/vs/editor/browser/controller/mouseHandler.ts index 6b33bc0c8efc3..4816b4a61299c 100644 --- a/src/vs/editor/browser/controller/mouseHandler.ts +++ b/src/vs/editor/browser/controller/mouseHandler.ts @@ -4,29 +4,29 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {IDisposable, dispose, Disposable} from 'vs/base/common/lifecycle'; +import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle'; import * as platform from 'vs/base/common/platform'; import * as browser from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; -import {Position} from 'vs/editor/common/core/position'; -import {Selection} from 'vs/editor/common/core/selection'; +import { Position } from 'vs/editor/common/core/position'; +import { Selection } from 'vs/editor/common/core/selection'; import * as editorCommon from 'vs/editor/common/editorCommon'; -import {ViewEventHandler} from 'vs/editor/common/viewModel/viewEventHandler'; -import {MouseTargetFactory} from 'vs/editor/browser/controller/mouseTarget'; +import { ViewEventHandler } from 'vs/editor/common/viewModel/viewEventHandler'; +import { MouseTargetFactory } from 'vs/editor/browser/controller/mouseTarget'; import * as editorBrowser from 'vs/editor/browser/editorBrowser'; -import {TimeoutTimer, RunOnceScheduler} from 'vs/base/common/async'; -import {ViewContext} from 'vs/editor/common/view/viewContext'; -import {VisibleRange} from 'vs/editor/common/view/renderingContext'; -import {EditorMouseEventFactory, GlobalEditorMouseMoveMonitor, EditorMouseEvent} from 'vs/editor/browser/editorDom'; -import {StandardMouseWheelEvent} from 'vs/base/browser/mouseEvent'; -import {EditorZoom} from 'vs/editor/common/config/commonEditorConfig'; -import {IViewCursorRenderData} from 'vs/editor/browser/viewParts/viewCursors/viewCursor'; +import { TimeoutTimer, RunOnceScheduler } from 'vs/base/common/async'; +import { ViewContext } from 'vs/editor/common/view/viewContext'; +import { VisibleRange } from 'vs/editor/common/view/renderingContext'; +import { EditorMouseEventFactory, GlobalEditorMouseMoveMonitor, EditorMouseEvent } from 'vs/editor/browser/editorDom'; +import { StandardMouseWheelEvent } from 'vs/base/browser/mouseEvent'; +import { EditorZoom } from 'vs/editor/common/config/commonEditorConfig'; +import { IViewCursorRenderData } from 'vs/editor/browser/viewParts/viewCursors/viewCursor'; /** * Merges mouse events when mouse move events are throttled */ -function createMouseMoveEventMerger(mouseTargetFactory:MouseTargetFactory) { - return function(lastEvent:EditorMouseEvent, currentEvent:EditorMouseEvent): EditorMouseEvent { +function createMouseMoveEventMerger(mouseTargetFactory: MouseTargetFactory) { + return function (lastEvent: EditorMouseEvent, currentEvent: EditorMouseEvent): EditorMouseEvent { let targetIsWidget = false; if (mouseTargetFactory) { targetIsWidget = mouseTargetFactory.mouseTargetIsWidget(currentEvent); @@ -40,20 +40,20 @@ function createMouseMoveEventMerger(mouseTargetFactory:MouseTargetFactory) { class EventGateKeeper extends Disposable { - public handler: (value:T)=>void; + public handler: (value: T) => void; - private _destination: (value:T)=>void; - private _condition: ()=>boolean; + private _destination: (value: T) => void; + private _condition: () => boolean; private _retryTimer: TimeoutTimer; private _retryValue: T; - constructor(destination:(value:T)=>void, condition:()=>boolean) { + constructor(destination: (value: T) => void, condition: () => boolean) { super(); this._destination = destination; this._condition = condition; this._retryTimer = this._register(new TimeoutTimer()); - this.handler = (value:T) => this._handle(value); + this.handler = (value: T) => this._handle(value); } public dispose(): void { @@ -61,7 +61,7 @@ class EventGateKeeper extends Disposable { super.dispose(); } - private _handle(value:T): void { + private _handle(value: T): void { if (this._condition()) { this._retryTimer.cancel(); this._retryValue = null; @@ -81,15 +81,15 @@ class MousePosition { public position: Position; public mouseColumn: number; - constructor(position:Position, mouseColumn:number) { + constructor(position: Position, mouseColumn: number) { this.position = position; this.mouseColumn = mouseColumn; } } export interface IPointerHandlerHelper { - viewDomNode:HTMLElement; - linesContentDomNode:HTMLElement; + viewDomNode: HTMLElement; + linesContentDomNode: HTMLElement; focusTextArea(): void; isDirty(): boolean; @@ -97,12 +97,12 @@ export interface IPointerHandlerHelper { getScrollLeft(): number; getScrollTop(): number; - setScrollPosition(position:editorCommon.INewScrollPosition): void; + setScrollPosition(position: editorCommon.INewScrollPosition): void; - isAfterLines(verticalOffset:number): boolean; + isAfterLines(verticalOffset: number): boolean; getLineNumberAtVerticalOffset(verticalOffset: number): number; getVerticalOffsetForLineNumber(lineNumber: number): number; - getWhitespaceAtVerticalOffset(verticalOffset:number): editorCommon.IViewWhitespaceViewportData; + getWhitespaceAtVerticalOffset(verticalOffset: number): editorCommon.IViewWhitespaceViewportData; /** * Get the last rendered information of the cursors. @@ -115,30 +115,30 @@ export interface IPointerHandlerHelper { /** * Decode an Editor.IPosition from a rendered dom node */ - getPositionFromDOMInfo(spanNode:HTMLElement, offset:number): editorCommon.IPosition; + getPositionFromDOMInfo(spanNode: HTMLElement, offset: number): editorCommon.IPosition; - visibleRangeForPosition2(lineNumber:number, column:number): VisibleRange; - getLineWidth(lineNumber:number): number; + visibleRangeForPosition2(lineNumber: number, column: number): VisibleRange; + getLineWidth(lineNumber: number): number; } export class MouseHandler extends ViewEventHandler implements IDisposable { static MOUSE_MOVE_MINIMUM_TIME = 100; // ms - protected _context:ViewContext; - protected viewController:editorBrowser.IViewController; - protected viewHelper:IPointerHandlerHelper; + protected _context: ViewContext; + protected viewController: editorBrowser.IViewController; + protected viewHelper: IPointerHandlerHelper; protected mouseTargetFactory: MouseTargetFactory; - protected listenersToRemove:IDisposable[]; - private toDispose:IDisposable[]; + protected listenersToRemove: IDisposable[]; + private toDispose: IDisposable[]; private _asyncFocus: RunOnceScheduler; private _mouseDownOperation: MouseDownOperation; - private lastMouseLeaveTime:number; + private lastMouseLeaveTime: number; private _mouseMoveEventHandler: EventGateKeeper; - constructor(context:ViewContext, viewController:editorBrowser.IViewController, viewHelper:IPointerHandlerHelper) { + constructor(context: ViewContext, viewController: editorBrowser.IViewController, viewHelper: IPointerHandlerHelper) { super(); this._context = context; @@ -183,7 +183,7 @@ export class MouseHandler extends ViewEventHandler implements IDisposable { } let e = new StandardMouseWheelEvent(browserEvent); if (e.browserEvent.ctrlKey || e.browserEvent.metaKey) { - let zoomLevel:number = EditorZoom.getZoomLevel(); + let zoomLevel: number = EditorZoom.getZoomLevel(); let delta = e.deltaY > 0 ? 1 : -1; EditorZoom.setZoomLevel(zoomLevel + delta); e.preventDefault(); @@ -204,36 +204,36 @@ export class MouseHandler extends ViewEventHandler implements IDisposable { } // --- begin event handlers - _layoutInfo:editorCommon.EditorLayoutInfo; - public onLayoutChanged(layoutInfo:editorCommon.EditorLayoutInfo): boolean { + _layoutInfo: editorCommon.EditorLayoutInfo; + public onLayoutChanged(layoutInfo: editorCommon.EditorLayoutInfo): boolean { this._layoutInfo = layoutInfo; return false; } - public onScrollChanged(e:editorCommon.IScrollEvent): boolean { + public onScrollChanged(e: editorCommon.IScrollEvent): boolean { this._mouseDownOperation.onScrollChanged(); return false; } - public onCursorSelectionChanged(e:editorCommon.IViewCursorSelectionChangedEvent): boolean { + public onCursorSelectionChanged(e: editorCommon.IViewCursorSelectionChangedEvent): boolean { this._mouseDownOperation.onCursorSelectionChanged(e); return false; } private _isFocused = false; - public onViewFocusChanged(isFocused:boolean): boolean { + public onViewFocusChanged(isFocused: boolean): boolean { this._isFocused = isFocused; return false; } // --- end event handlers - protected _createMouseTarget(e:EditorMouseEvent, testEventTarget:boolean): editorBrowser.IMouseTarget { + protected _createMouseTarget(e: EditorMouseEvent, testEventTarget: boolean): editorBrowser.IMouseTarget { let lastViewCursorsRenderData = this.viewHelper.getLastViewCursorsRenderData(); return this.mouseTargetFactory.createMouseTarget(this._layoutInfo, lastViewCursorsRenderData, e, testEventTarget); } - private _getMouseColumn(e:EditorMouseEvent): number { + private _getMouseColumn(e: EditorMouseEvent): number { return this.mouseTargetFactory.getMouseColumn(this._layoutInfo, e); } - protected _onContextMenu(e: EditorMouseEvent, testEventTarget:boolean): void { + protected _onContextMenu(e: EditorMouseEvent, testEventTarget: boolean): void { this.viewController.emitContextMenu({ event: e, target: this._createMouseTarget(e, testEventTarget) @@ -327,11 +327,11 @@ export class MouseHandler extends ViewEventHandler implements IDisposable { class MouseDownOperation extends Disposable { - private _context:ViewContext; - private _viewController:editorBrowser.IViewController; - private _viewHelper:IPointerHandlerHelper; - private _createMouseTarget:(e:EditorMouseEvent, testEventTarget:boolean)=>editorBrowser.IMouseTarget; - private _getMouseColumn:(e:EditorMouseEvent)=>number; + private _context: ViewContext; + private _viewController: editorBrowser.IViewController; + private _viewHelper: IPointerHandlerHelper; + private _createMouseTarget: (e: EditorMouseEvent, testEventTarget: boolean) => editorBrowser.IMouseTarget; + private _getMouseColumn: (e: EditorMouseEvent) => number; private _mouseMoveMonitor: GlobalEditorMouseMoveMonitor; private _mouseDownThenMoveEventHandler: EventGateKeeper; @@ -345,11 +345,11 @@ class MouseDownOperation extends Disposable { private _lastMouseEvent: EditorMouseEvent; constructor( - context:ViewContext, - viewController:editorBrowser.IViewController, - viewHelper:IPointerHandlerHelper, - createMouseTarget:(e:EditorMouseEvent, testEventTarget:boolean)=>editorBrowser.IMouseTarget, - getMouseColumn:(e:EditorMouseEvent)=>number + context: ViewContext, + viewController: editorBrowser.IViewController, + viewHelper: IPointerHandlerHelper, + createMouseTarget: (e: EditorMouseEvent, testEventTarget: boolean) => editorBrowser.IMouseTarget, + getMouseColumn: (e: EditorMouseEvent) => number ) { super(); this._context = context; @@ -383,7 +383,7 @@ class MouseDownOperation extends Disposable { return this._isActive; } - private _onMouseDownThenMove(e:EditorMouseEvent): void { + private _onMouseDownThenMove(e: EditorMouseEvent): void { this._lastMouseEvent = e; this._mouseState.setModifiers(e); @@ -396,7 +396,7 @@ class MouseDownOperation extends Disposable { this._dispatchMouse(position, true); } - public start(targetType:editorCommon.MouseTargetType, e:EditorMouseEvent): void { + public start(targetType: editorCommon.MouseTargetType, e: EditorMouseEvent): void { this._lastMouseEvent = e; this._mouseState.setStartedOnLineNumbers(targetType === editorCommon.MouseTargetType.GUTTER_LINE_NUMBERS); @@ -444,11 +444,11 @@ class MouseDownOperation extends Disposable { }, 10); } - public onCursorSelectionChanged(e:editorCommon.IViewCursorSelectionChangedEvent): void { + public onCursorSelectionChanged(e: editorCommon.IViewCursorSelectionChangedEvent): void { this._currentSelection = e.selection; } - private _getPositionOutsideEditor(e:EditorMouseEvent): MousePosition { + private _getPositionOutsideEditor(e: EditorMouseEvent): MousePosition { const editorContent = e.editorPos; let mouseColumn = this._getMouseColumn(e); @@ -476,7 +476,7 @@ class MouseDownOperation extends Disposable { return null; } - private _findMousePosition(e:EditorMouseEvent, testEventTarget:boolean): MousePosition { + private _findMousePosition(e: EditorMouseEvent, testEventTarget: boolean): MousePosition { let positionOutsideEditor = this._getPositionOutsideEditor(e); if (positionOutsideEditor) { return positionOutsideEditor; @@ -507,7 +507,7 @@ class MouseDownOperation extends Disposable { return new MousePosition(hintedPosition, t.mouseColumn); } - private _dispatchMouse(position: MousePosition, inSelectionMode:boolean): void { + private _dispatchMouse(position: MousePosition, inSelectionMode: boolean): void { this._viewController.dispatchMouse({ position: position.position, mouseColumn: position.mouseColumn, @@ -563,18 +563,18 @@ class MouseDownState { return this._lastMouseDownCount; } - public setModifiers(source:EditorMouseEvent) { + public setModifiers(source: EditorMouseEvent) { this._altKey = source.altKey; this._ctrlKey = source.ctrlKey; this._metaKey = source.metaKey; this._shiftKey = source.shiftKey; } - public setStartedOnLineNumbers(startedOnLineNumbers:boolean): void { + public setStartedOnLineNumbers(startedOnLineNumbers: boolean): void { this._startedOnLineNumbers = startedOnLineNumbers; } - public trySetCount(setMouseDownCount:number, newMouseDownPosition:Position): void { + public trySetCount(setMouseDownCount: number, newMouseDownPosition: Position): void { // a. Invalidate multiple clicking if too much time has passed (will be hit by IE because the detail field of mouse events contains garbage in IE10) let currentTime = (new Date()).getTime(); if (currentTime - this._lastSetMouseDownCountTime > MouseDownState.CLEAR_MOUSE_DOWN_COUNT_TIME) { diff --git a/src/vs/editor/browser/controller/mouseTarget.ts b/src/vs/editor/browser/controller/mouseTarget.ts index ba5376fde9963..19e3592479482 100644 --- a/src/vs/editor/browser/controller/mouseTarget.ts +++ b/src/vs/editor/browser/controller/mouseTarget.ts @@ -4,16 +4,16 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {Position} from 'vs/editor/common/core/position'; -import {Range as EditorRange} from 'vs/editor/common/core/range'; -import {EditorLayoutInfo, IPosition, MouseTargetType} from 'vs/editor/common/editorCommon'; -import {ClassNames, IMouseTarget, IViewZoneData} from 'vs/editor/browser/editorBrowser'; -import {ViewContext} from 'vs/editor/common/view/viewContext'; -import {IPointerHandlerHelper} from 'vs/editor/browser/controller/mouseHandler'; -import {EditorMouseEvent} from 'vs/editor/browser/editorDom'; +import { Position } from 'vs/editor/common/core/position'; +import { Range as EditorRange } from 'vs/editor/common/core/range'; +import { EditorLayoutInfo, IPosition, MouseTargetType } from 'vs/editor/common/editorCommon'; +import { ClassNames, IMouseTarget, IViewZoneData } from 'vs/editor/browser/editorBrowser'; +import { ViewContext } from 'vs/editor/common/view/viewContext'; +import { IPointerHandlerHelper } from 'vs/editor/browser/controller/mouseHandler'; +import { EditorMouseEvent } from 'vs/editor/browser/editorDom'; import * as dom from 'vs/base/browser/dom'; import * as browser from 'vs/base/browser/browser'; -import {IViewCursorRenderData} from 'vs/editor/browser/viewParts/viewCursors/viewCursor'; +import { IViewCursorRenderData } from 'vs/editor/browser/viewParts/viewCursors/viewCursor'; interface IETextRange { boundingHeight: number; @@ -57,7 +57,7 @@ interface IETextRange { declare var IETextRange: { prototype: IETextRange; - new(): IETextRange; + new (): IETextRange; }; interface IHitTestResult { @@ -74,7 +74,7 @@ class MouseTarget implements IMouseTarget { public range: EditorRange; public 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, range: EditorRange = null, detail: any = null) { this.element = element; this.type = type; this.mouseColumn = mouseColumn; @@ -136,9 +136,9 @@ class MouseTarget implements IMouseTarget { // - overflow-guard/monaco-scrollable-element editor-scrollable vs/lines-content/view-lines/view-line // - overflow-guard/monaco-scrollable-element editor-scrollable vs/lines-content/view-lines/view-line/token comment js // etc. -let REGEX = (function() { +let REGEX = (function () { - function nodeWithClass(className:string): string { + function nodeWithClass(className: string): string { return '[^/]*' + className + '[^/]*'; } @@ -148,7 +148,7 @@ let REGEX = (function() { let ANCHOR = '^' + ClassNames.OVERFLOW_GUARD + '\\/'; - function createRegExp(...pieces:string[]): RegExp { + function createRegExp(...pieces: string[]): RegExp { let forceEndMatch = false; if (pieces[pieces.length - 1] === '$') { forceEndMatch = true; @@ -177,13 +177,13 @@ export class MouseTargetFactory { private _context: ViewContext; private _viewHelper: IPointerHandlerHelper; - constructor(context:ViewContext, viewHelper:IPointerHandlerHelper) { + constructor(context: ViewContext, viewHelper: IPointerHandlerHelper) { this._context = context; this._viewHelper = viewHelper; } - private getClassNamePathTo(child:Node, stopAt:Node): string { - let path:string[] = [], + private getClassNamePathTo(child: Node, stopAt: Node): string { + let path: string[] = [], className: string; while (child && child !== document.body) { @@ -202,7 +202,7 @@ export class MouseTargetFactory { return path.join('/'); } - public mouseTargetIsWidget(e:EditorMouseEvent): boolean { + public mouseTargetIsWidget(e: EditorMouseEvent): boolean { let t = e.target; let path = this.getClassNamePathTo(t, this._viewHelper.viewDomNode); @@ -219,7 +219,7 @@ export class MouseTargetFactory { return false; } - public createMouseTarget(layoutInfo:EditorLayoutInfo, lastViewCursorsRenderData:IViewCursorRenderData[], e:EditorMouseEvent, testEventTarget:boolean): IMouseTarget { + public createMouseTarget(layoutInfo: EditorLayoutInfo, lastViewCursorsRenderData: IViewCursorRenderData[], e: EditorMouseEvent, testEventTarget: boolean): IMouseTarget { try { let r = this._unsafeCreateMouseTarget(layoutInfo, lastViewCursorsRenderData, e, testEventTarget); return r; @@ -228,7 +228,7 @@ export class MouseTargetFactory { } } - private _unsafeCreateMouseTarget(layoutInfo:EditorLayoutInfo, lastViewCursorsRenderData:IViewCursorRenderData[], e:EditorMouseEvent, testEventTarget:boolean): IMouseTarget { + private _unsafeCreateMouseTarget(layoutInfo: EditorLayoutInfo, lastViewCursorsRenderData: IViewCursorRenderData[], e: EditorMouseEvent, testEventTarget: boolean): IMouseTarget { let mouseVerticalOffset = Math.max(0, this._viewHelper.getScrollTop() + (e.posy - e.editorPos.top)); let mouseContentHorizontalOffset = this._viewHelper.getScrollLeft() + (e.posx - e.editorPos.left) - layoutInfo.contentLeft; let mouseColumn = this._getMouseColumn(mouseContentHorizontalOffset); @@ -383,7 +383,7 @@ export class MouseTargetFactory { return this.createMouseTargetFromUnknownTarget(t); } - private _isChild(testChild:Node, testAncestor:Node, stopAt:Node): boolean { + private _isChild(testChild: Node, testAncestor: Node, stopAt: Node): boolean { while (testChild && testChild !== document.body) { if (testChild === testAncestor) { return true; @@ -396,7 +396,7 @@ export class MouseTargetFactory { return false; } - private _findAttribute(element:Element, attr:string, stopAt:Element): string { + private _findAttribute(element: Element, attr: string, stopAt: Element): string { while (element && element !== document.body) { if (element.hasAttribute && element.hasAttribute(attr)) { return element.getAttribute(attr); @@ -437,9 +437,9 @@ export class MouseTargetFactory { return this._actualDoHitTestWithCaretRangeFromPoint(e.viewportx, e.viewporty); } - private _actualDoHitTestWithCaretRangeFromPoint(hitx:number, hity:number): IHitTestResult { + private _actualDoHitTestWithCaretRangeFromPoint(hitx: number, hity: number): IHitTestResult { - let range:Range = (document).caretRangeFromPoint(hitx, hity); + let range: Range = (document).caretRangeFromPoint(hitx, hity); if (!range || !range.startContainer) { return { @@ -495,7 +495,7 @@ export class MouseTargetFactory { * Most probably Gecko */ private _doHitTestWithCaretPositionFromPoint(e: EditorMouseEvent): IHitTestResult { - let hitResult:{ offsetNode: Node; offset: number; } = (document).caretPositionFromPoint(e.viewportx, e.viewporty); + let hitResult: { offsetNode: Node; offset: number; } = (document).caretPositionFromPoint(e.viewportx, e.viewporty); let range = document.createRange(); range.setStart(hitResult.offsetNode, hitResult.offset); @@ -559,7 +559,7 @@ export class MouseTargetFactory { }; } - private _doHitTest(e:EditorMouseEvent, mouseVerticalOffset: number): IHitTestResult { + private _doHitTest(e: EditorMouseEvent, mouseVerticalOffset: number): IHitTestResult { // State of the art (18.10.2012): // The spec says browsers should support document.caretPositionFromPoint, but nobody implemented it (http://dev.w3.org/csswg/cssom-view/) // Gecko: @@ -657,12 +657,12 @@ export class MouseTargetFactory { }; } - public getMouseColumn(layoutInfo:EditorLayoutInfo, e:EditorMouseEvent): number { + public getMouseColumn(layoutInfo: EditorLayoutInfo, e: EditorMouseEvent): number { let mouseContentHorizontalOffset = this._viewHelper.getScrollLeft() + (e.posx - e.editorPos.left) - layoutInfo.contentLeft; return this._getMouseColumn(mouseContentHorizontalOffset); } - private _getMouseColumn(mouseContentHorizontalOffset:number): number { + private _getMouseColumn(mouseContentHorizontalOffset: number): number { if (mouseContentHorizontalOffset < 0) { return 1; } @@ -671,18 +671,18 @@ export class MouseTargetFactory { return (chars + 1); } - private createMouseTargetFromViewCursor(target:Element, lineNumber: number, column: number, mouseColumn:number): MouseTarget { + private createMouseTargetFromViewCursor(target: Element, lineNumber: number, column: number, mouseColumn: number): MouseTarget { return new MouseTarget(target, MouseTargetType.CONTENT_TEXT, mouseColumn, new Position(lineNumber, column)); } - private createMouseTargetFromViewLines(target:Element, mouseVerticalOffset: number, mouseColumn:number): MouseTarget { + private createMouseTargetFromViewLines(target: Element, mouseVerticalOffset: number, mouseColumn: number): MouseTarget { // This most likely indicates it happened after the last view-line let lineCount = this._context.model.getLineCount(); let maxLineColumn = this._context.model.getLineMaxColumn(lineCount); return new MouseTarget(target, MouseTargetType.CONTENT_EMPTY, mouseColumn, new Position(lineCount, maxLineColumn)); } - private createMouseTargetFromHitTestPosition(target:Element, lineNumber: number, column: number, mouseHorizontalOffset: number, mouseColumn:number): MouseTarget { + private createMouseTargetFromHitTestPosition(target: Element, lineNumber: number, column: number, mouseHorizontalOffset: number, mouseColumn: number): MouseTarget { let pos = new Position(lineNumber, column); let lineWidth = this._viewHelper.getLineWidth(lineNumber); @@ -737,7 +737,7 @@ export class MouseTargetFactory { return new MouseTarget(target, MouseTargetType.CONTENT_TEXT, mouseColumn, pos); } - private createMouseTargetFromContentWidgetsChild(target: Element, mouseColumn:number): MouseTarget { + private createMouseTargetFromContentWidgetsChild(target: Element, mouseColumn: number): MouseTarget { let widgetId = this._findAttribute(target, 'widgetId', this._viewHelper.viewDomNode); if (widgetId) { @@ -747,7 +747,7 @@ export class MouseTargetFactory { } } - private createMouseTargetFromOverlayWidgetsChild(target: Element, mouseColumn:number): MouseTarget { + private createMouseTargetFromOverlayWidgetsChild(target: Element, mouseColumn: number): MouseTarget { let widgetId = this._findAttribute(target, 'widgetId', this._viewHelper.viewDomNode); if (widgetId) { @@ -757,7 +757,7 @@ export class MouseTargetFactory { } } - private createMouseTargetFromLinesDecorationsChild(target: Element, mouseVerticalOffset: number, mouseColumn:number): MouseTarget { + private createMouseTargetFromLinesDecorationsChild(target: Element, mouseVerticalOffset: number, mouseColumn: number): MouseTarget { let viewZoneData = this._getZoneAtCoord(mouseVerticalOffset); if (viewZoneData) { return new MouseTarget(target, MouseTargetType.GUTTER_VIEW_ZONE, mouseColumn, viewZoneData.position, null, viewZoneData); @@ -767,7 +767,7 @@ export class MouseTargetFactory { return new MouseTarget(target, MouseTargetType.GUTTER_LINE_DECORATIONS, mouseColumn, new Position(res.range.startLineNumber, res.range.startColumn), res.range, res.isAfterLines); } - private createMouseTargetFromLineNumbers(target: Element, mouseVerticalOffset: number, mouseColumn:number): MouseTarget { + private createMouseTargetFromLineNumbers(target: Element, mouseVerticalOffset: number, mouseColumn: number): MouseTarget { let viewZoneData = this._getZoneAtCoord(mouseVerticalOffset); if (viewZoneData) { return new MouseTarget(target, MouseTargetType.GUTTER_VIEW_ZONE, mouseColumn, viewZoneData.position, null, viewZoneData); @@ -777,7 +777,7 @@ export class MouseTargetFactory { return new MouseTarget(target, MouseTargetType.GUTTER_LINE_NUMBERS, mouseColumn, new Position(res.range.startLineNumber, res.range.startColumn), res.range, res.isAfterLines); } - private createMouseTargetFromGlyphMargin(target: Element, mouseVerticalOffset: number, mouseColumn:number): MouseTarget { + private createMouseTargetFromGlyphMargin(target: Element, mouseVerticalOffset: number, mouseColumn: number): MouseTarget { let viewZoneData = this._getZoneAtCoord(mouseVerticalOffset); if (viewZoneData) { return new MouseTarget(target, MouseTargetType.GUTTER_VIEW_ZONE, mouseColumn, viewZoneData.position, null, viewZoneData); @@ -787,7 +787,7 @@ export class MouseTargetFactory { return new MouseTarget(target, MouseTargetType.GUTTER_GLYPH_MARGIN, mouseColumn, new Position(res.range.startLineNumber, res.range.startColumn), res.range, res.isAfterLines); } - private createMouseTargetFromScrollbar(target: Element, mouseVerticalOffset: number, mouseColumn:number): MouseTarget { + private createMouseTargetFromScrollbar(target: Element, mouseVerticalOffset: number, mouseColumn: number): MouseTarget { let possibleLineNumber = this._viewHelper.getLineNumberAtVerticalOffset(mouseVerticalOffset); let maxColumn = this._context.model.getLineMaxColumn(possibleLineNumber); return new MouseTarget(target, MouseTargetType.SCROLLBAR, mouseColumn, new Position(possibleLineNumber, maxColumn)); diff --git a/src/vs/editor/browser/controller/pointerHandler.ts b/src/vs/editor/browser/controller/pointerHandler.ts index fb673bcedf6ce..7af7007e0c407 100644 --- a/src/vs/editor/browser/controller/pointerHandler.ts +++ b/src/vs/editor/browser/controller/pointerHandler.ts @@ -4,21 +4,21 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {IDisposable} from 'vs/base/common/lifecycle'; +import { IDisposable } from 'vs/base/common/lifecycle'; import * as dom from 'vs/base/browser/dom'; -import {EventType, Gesture, GestureEvent} from 'vs/base/browser/touch'; -import {IScrollEvent} from 'vs/editor/common/editorCommon'; -import {MouseHandler, IPointerHandlerHelper} from 'vs/editor/browser/controller/mouseHandler'; -import {IViewController} from 'vs/editor/browser/editorBrowser'; -import {ViewContext} from 'vs/editor/common/view/viewContext'; -import {EditorMouseEvent} from 'vs/editor/browser/editorDom'; +import { EventType, Gesture, GestureEvent } from 'vs/base/browser/touch'; +import { IScrollEvent } from 'vs/editor/common/editorCommon'; +import { MouseHandler, IPointerHandlerHelper } from 'vs/editor/browser/controller/mouseHandler'; +import { IViewController } from 'vs/editor/browser/editorBrowser'; +import { ViewContext } from 'vs/editor/common/view/viewContext'; +import { EditorMouseEvent } from 'vs/editor/browser/editorDom'; interface IThrottledGestureEvent { translationX: number; translationY: number; } -var gestureChangeEventMerger = (lastEvent:IThrottledGestureEvent, currentEvent:MSGestureEvent): IThrottledGestureEvent => { +var gestureChangeEventMerger = (lastEvent: IThrottledGestureEvent, currentEvent: MSGestureEvent): IThrottledGestureEvent => { var r = { translationY: currentEvent.translationY, translationX: currentEvent.translationX @@ -38,7 +38,7 @@ class MsPointerHandler extends MouseHandler implements IDisposable { private _lastPointerType: string; private _installGestureHandlerTimeout: number; - constructor(context:ViewContext, viewController:IViewController, viewHelper:IPointerHandlerHelper) { + constructor(context: ViewContext, viewController: IViewController, viewHelper: IPointerHandlerHelper) { super(context, viewController, viewHelper); this.viewHelper.linesContentDomNode.style.msTouchAction = 'none'; @@ -48,12 +48,12 @@ class MsPointerHandler extends MouseHandler implements IDisposable { // This handler should be added when the dom node is in the dom tree this._installGestureHandlerTimeout = window.setTimeout(() => { this._installGestureHandlerTimeout = -1; - if((window).MSGesture) { + if ((window).MSGesture) { var touchGesture = new MSGesture(); var penGesture = new MSGesture(); touchGesture.target = this.viewHelper.linesContentDomNode; penGesture.target = this.viewHelper.linesContentDomNode; - this.viewHelper.linesContentDomNode.addEventListener('MSPointerDown', (e:MSPointerEvent) => { + this.viewHelper.linesContentDomNode.addEventListener('MSPointerDown', (e: MSPointerEvent) => { // Circumvent IE11 breaking change in e.pointerType & TypeScript's stale definitions var pointerType = e.pointerType; if (pointerType === ((e).MSPOINTER_TYPE_MOUSE || 'mouse')) { @@ -74,7 +74,7 @@ class MsPointerHandler extends MouseHandler implements IDisposable { this._lastPointerType = 'mouse'; } - public _onMouseDown(e:EditorMouseEvent): void { + public _onMouseDown(e: EditorMouseEvent): void { if (this._lastPointerType === 'mouse') { super._onMouseDown(e); } @@ -98,7 +98,7 @@ class MsPointerHandler extends MouseHandler implements IDisposable { } } - private _onGestureChange(e:IThrottledGestureEvent): void { + private _onGestureChange(e: IThrottledGestureEvent): void { this.viewHelper.setScrollPosition({ scrollLeft: this.viewHelper.getScrollLeft() - e.translationX, scrollTop: this.viewHelper.getScrollTop() - e.translationY, @@ -119,7 +119,7 @@ class StandardPointerHandler extends MouseHandler implements IDisposable { private _lastPointerType: string; private _installGestureHandlerTimeout: number; - constructor(context:ViewContext, viewController:IViewController, viewHelper:IPointerHandlerHelper) { + constructor(context: ViewContext, viewController: IViewController, viewHelper: IPointerHandlerHelper) { super(context, viewController, viewHelper); this.viewHelper.linesContentDomNode.style.touchAction = 'none'; @@ -130,12 +130,12 @@ class StandardPointerHandler extends MouseHandler implements IDisposable { this._installGestureHandlerTimeout = -1; // TODO@Alex: replace the usage of MSGesture here with something that works across all browsers - if((window).MSGesture) { + if ((window).MSGesture) { var touchGesture = new MSGesture(); var penGesture = new MSGesture(); touchGesture.target = this.viewHelper.linesContentDomNode; penGesture.target = this.viewHelper.linesContentDomNode; - this.viewHelper.linesContentDomNode.addEventListener('pointerdown', (e:MSPointerEvent) => { + this.viewHelper.linesContentDomNode.addEventListener('pointerdown', (e: MSPointerEvent) => { var pointerType = e.pointerType; if (pointerType === 'mouse') { this._lastPointerType = 'mouse'; @@ -155,7 +155,7 @@ class StandardPointerHandler extends MouseHandler implements IDisposable { this._lastPointerType = 'mouse'; } - public _onMouseDown(e:EditorMouseEvent): void { + public _onMouseDown(e: EditorMouseEvent): void { if (this._lastPointerType === 'mouse') { super._onMouseDown(e); } @@ -179,7 +179,7 @@ class StandardPointerHandler extends MouseHandler implements IDisposable { } } - private _onGestureChange(e:IThrottledGestureEvent): void { + private _onGestureChange(e: IThrottledGestureEvent): void { this.viewHelper.setScrollPosition({ scrollLeft: this.viewHelper.getScrollLeft() - e.translationX, scrollTop: this.viewHelper.getScrollTop() - e.translationY, @@ -194,9 +194,9 @@ class StandardPointerHandler extends MouseHandler implements IDisposable { class TouchHandler extends MouseHandler { - private gesture:Gesture; + private gesture: Gesture; - constructor(context:ViewContext, viewController:IViewController, viewHelper:IPointerHandlerHelper) { + constructor(context: ViewContext, viewController: IViewController, viewHelper: IPointerHandlerHelper) { super(context, viewController, viewHelper); this.gesture = new Gesture(this.viewHelper.linesContentDomNode); @@ -212,7 +212,7 @@ class TouchHandler extends MouseHandler { super.dispose(); } - private onTap(event:GestureEvent): void { + private onTap(event: GestureEvent): void { event.preventDefault(); this.viewHelper.focusTextArea(); @@ -224,7 +224,7 @@ class TouchHandler extends MouseHandler { } } - private onChange(e:GestureEvent): void { + private onChange(e: GestureEvent): void { this.viewHelper.setScrollPosition({ scrollLeft: this.viewHelper.getScrollLeft() - e.translationX, scrollTop: this.viewHelper.getScrollTop() - e.translationY, @@ -233,12 +233,12 @@ class TouchHandler extends MouseHandler { } export class PointerHandler implements IDisposable { - private handler:MouseHandler; + private handler: MouseHandler; - constructor(context:ViewContext, viewController:IViewController, viewHelper:IPointerHandlerHelper) { + constructor(context: ViewContext, viewController: IViewController, viewHelper: IPointerHandlerHelper) { if (window.navigator.msPointerEnabled) { this.handler = new MsPointerHandler(context, viewController, viewHelper); - } else if(( window).TouchEvent) { + } else if ((window).TouchEvent) { this.handler = new TouchHandler(context, viewController, viewHelper); } else if (window.navigator.pointerEnabled) { this.handler = new StandardPointerHandler(context, viewController, viewHelper); @@ -247,7 +247,7 @@ export class PointerHandler implements IDisposable { } } - public onScrollChanged(e:IScrollEvent): void { + public onScrollChanged(e: IScrollEvent): void { this.handler.onScrollChanged(e); } diff --git a/src/vs/editor/browser/editorBrowser.ts b/src/vs/editor/browser/editorBrowser.ts index 00448c5ba4e48..9d1ab7984fb62 100644 --- a/src/vs/editor/browser/editorBrowser.ts +++ b/src/vs/editor/browser/editorBrowser.ts @@ -4,14 +4,14 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {IEventEmitter} from 'vs/base/common/eventEmitter'; -import {IDisposable} from 'vs/base/common/lifecycle'; -import {IKeyboardEvent} from 'vs/base/browser/keyboardEvent'; -import {IMouseEvent} from 'vs/base/browser/mouseEvent'; -import {IConstructorSignature1} from 'vs/platform/instantiation/common/instantiation'; +import { IEventEmitter } from 'vs/base/common/eventEmitter'; +import { IDisposable } from 'vs/base/common/lifecycle'; +import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; +import { IMouseEvent } from 'vs/base/browser/mouseEvent'; +import { IConstructorSignature1 } from 'vs/platform/instantiation/common/instantiation'; import * as editorCommon from 'vs/editor/common/editorCommon'; -import {Position} from 'vs/editor/common/core/position'; -import {Range} from 'vs/editor/common/core/range'; +import { Position } from 'vs/editor/common/core/position'; +import { Range } from 'vs/editor/common/core/range'; /** * @internal @@ -39,11 +39,11 @@ export interface ICodeEditorHelper { getScrollHeight(): number; getScrollTop(): number; - setScrollPosition(position:editorCommon.INewScrollPosition): void; + setScrollPosition(position: editorCommon.INewScrollPosition): void; - getVerticalOffsetForPosition(lineNumber:number, column:number): number; - delegateVerticalScrollbarMouseDown(browserEvent:MouseEvent): void; - getOffsetForColumn(lineNumber:number, column:number): number; + getVerticalOffsetForPosition(lineNumber: number, column: number): number; + delegateVerticalScrollbarMouseDown(browserEvent: MouseEvent): void; + getOffsetForColumn(lineNumber: number, column: number): number; } /** @@ -54,7 +54,7 @@ export interface IView extends IDisposable { getInternalEventBus(): IEventEmitter; - createOverviewRuler(cssClassName:string, minimumHeight:number, maximumHeight:number): IOverviewRuler; + createOverviewRuler(cssClassName: string, minimumHeight: number, maximumHeight: number): IOverviewRuler; getCodeEditorHelper(): ICodeEditorHelper; getCenteredRangeInViewport(): Range; @@ -63,18 +63,18 @@ export interface IView extends IDisposable { */ getCompletelyVisibleLinesRangeInViewport(): Range; - change(callback:(changeAccessor:IViewZoneChangeAccessor) => any): boolean; + change(callback: (changeAccessor: IViewZoneChangeAccessor) => any): boolean; getWhitespaces(): editorCommon.IEditorWhitespace[]; - renderOnce(callback:() => any): any; + renderOnce(callback: () => any): any; - render(now:boolean, everything:boolean): void; - setAriaActiveDescendant(id:string): void; + render(now: boolean, everything: boolean): void; + setAriaActiveDescendant(id: string): void; focus(): void; isFocused(): boolean; saveState(): editorCommon.IViewState; - restoreState(state:editorCommon.IViewState): void; + restoreState(state: editorCommon.IViewState): void; addContentWidget(widgetData: IContentWidgetData): void; layoutContentWidget(widgetData: IContentWidgetData): void; @@ -90,8 +90,8 @@ export interface IView extends IDisposable { */ export interface IViewZoneData { viewZoneId: number; - positionBefore:Position; - positionAfter:Position; + positionBefore: Position; + positionAfter: Position; position: Position; afterLineNumber: number; } @@ -119,24 +119,24 @@ export interface IMouseDispatchData { * @internal */ export interface IViewController { - dispatchMouse(data:IMouseDispatchData); + dispatchMouse(data: IMouseDispatchData); - moveTo(source:string, position:Position): void; + moveTo(source: string, position: Position): void; - paste(source:string, text:string, pasteOnNewLine:boolean): void; + paste(source: string, text: string, pasteOnNewLine: boolean): void; type(source: string, text: string): void; - replacePreviousChar(source: string, text: string, replaceCharCnt:number): void; + replacePreviousChar(source: string, text: string, replaceCharCnt: number): void; compositionStart(source: string): void; compositionEnd(source: string): void; - cut(source:string): void; - - emitKeyDown(e:IKeyboardEvent): void; - emitKeyUp(e:IKeyboardEvent): void; - emitContextMenu(e:IEditorMouseEvent): void; - emitMouseMove(e:IEditorMouseEvent): void; - emitMouseLeave(e:IEditorMouseEvent): void; - emitMouseUp(e:IEditorMouseEvent): void; - emitMouseDown(e:IEditorMouseEvent): void; + cut(source: string): void; + + emitKeyDown(e: IKeyboardEvent): void; + emitKeyUp(e: IKeyboardEvent): void; + emitContextMenu(e: IEditorMouseEvent): void; + emitMouseMove(e: IEditorMouseEvent): void; + emitMouseLeave(e: IEditorMouseEvent): void; + emitMouseUp(e: IEditorMouseEvent): void; + emitMouseDown(e: IEditorMouseEvent): void; } /** @@ -166,10 +166,10 @@ export var ClassNames = { */ export interface IViewportInfo { visibleRange: Range; - width:number; - height:number; - deltaTop:number; - deltaLeft:number; + width: number; + height: number; + deltaTop: number; + deltaLeft: number; } // --- end View Event Handlers & Parts @@ -183,24 +183,24 @@ export interface IViewZone { * The line number after which this zone should appear. * Use 0 to place a view zone before the first line number. */ - afterLineNumber:number; + afterLineNumber: number; /** * The column after which this zone should appear. * If not set, the maxLineColumn of `afterLineNumber` will be used. */ - afterColumn?:number; + afterColumn?: number; /** * Suppress mouse down events. * If set, the editor will attach a mouse down listener to the view zone and .preventDefault on it. * Defaults to false */ - suppressMouseDown?:boolean; + suppressMouseDown?: boolean; /** * The height in lines of the view zone. * If specified, `heightInPx` will be used instead of this. * If neither `heightInPx` nor `heightInLines` is specified, a default of `heightInLines` = 1 will be chosen. */ - heightInLines?:number; + heightInLines?: number; /** * The height in px of the view zone. * If this is set, the editor will give preference to it rather than `heightInLines` above. @@ -210,15 +210,15 @@ export interface IViewZone { /** * The dom node of the view zone */ - domNode:HTMLElement; + domNode: HTMLElement; /** * Callback which gives the relative top of the view zone as it appears (taking scrolling into account). */ - onDomNodeTop?:(top: number) =>void; + onDomNodeTop?: (top: number) => void; /** * Callback which gives the height in pixels of the view zone. */ - onComputedHeight?:(height: number) =>void; + onComputedHeight?: (height: number) => void; } /** * An accessor that allows for zones to be added or removed. @@ -394,8 +394,8 @@ export type IEditorContributionCtor = IConstructorSignature1void): IDisposable; + onMouseUp(listener: (e: IEditorMouseEvent) => void): IDisposable; /** * An event emitted on a "mousedown". */ - onMouseDown(listener: (e:IEditorMouseEvent)=>void): IDisposable; + onMouseDown(listener: (e: IEditorMouseEvent) => void): IDisposable; /** * An event emitted on a "contextmenu". */ - onContextMenu(listener: (e:IEditorMouseEvent)=>void): IDisposable; + onContextMenu(listener: (e: IEditorMouseEvent) => void): IDisposable; /** * An event emitted on a "mousemove". */ - onMouseMove(listener: (e:IEditorMouseEvent)=>void): IDisposable; + onMouseMove(listener: (e: IEditorMouseEvent) => void): IDisposable; /** * An event emitted on a "mouseleave". */ - onMouseLeave(listener: (e:IEditorMouseEvent)=>void): IDisposable; + onMouseLeave(listener: (e: IEditorMouseEvent) => void): IDisposable; /** * An event emitted on a "keyup". */ - onKeyUp(listener: (e:IKeyboardEvent)=>void): IDisposable; + onKeyUp(listener: (e: IKeyboardEvent) => void): IDisposable; /** * An event emitted on a "keydown". */ - onKeyDown(listener: (e:IKeyboardEvent)=>void): IDisposable; + onKeyDown(listener: (e: IKeyboardEvent) => void): IDisposable; /** * An event emitted when the layout of the editor has changed. */ - onDidLayoutChange(listener: (e:editorCommon.EditorLayoutInfo)=>void): IDisposable; + onDidLayoutChange(listener: (e: editorCommon.EditorLayoutInfo) => void): IDisposable; /** * An event emitted when the scroll in the editor has changed. */ - onDidScrollChange(listener: (e:editorCommon.IScrollEvent)=>void): IDisposable; + onDidScrollChange(listener: (e: editorCommon.IScrollEvent) => void): IDisposable; /** * Returns the editor's dom node @@ -522,17 +522,17 @@ export interface ICodeEditor extends editorCommon.ICommonCodeEditor { * Set the model ranges that will be hidden in the view. * @internal */ - setHiddenAreas(ranges:editorCommon.IRange[]): void; + setHiddenAreas(ranges: editorCommon.IRange[]): void; /** * @internal */ - setAriaActiveDescendant(id:string): void; + setAriaActiveDescendant(id: string): void; /** * Apply the same font settings as the editor to `target`. */ - applyFontInfo(target:HTMLElement): void; + applyFontInfo(target: HTMLElement): void; } /** diff --git a/src/vs/editor/browser/editorBrowserExtensions.ts b/src/vs/editor/browser/editorBrowserExtensions.ts index 6e07a20e0057c..ea76aeaa64454 100644 --- a/src/vs/editor/browser/editorBrowserExtensions.ts +++ b/src/vs/editor/browser/editorBrowserExtensions.ts @@ -4,10 +4,10 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {Registry} from 'vs/platform/platform'; -import {IEditorContributionCtor} from 'vs/editor/browser/editorBrowser'; +import { Registry } from 'vs/platform/platform'; +import { IEditorContributionCtor } from 'vs/editor/browser/editorBrowser'; -export function editorContribution(ctor:IEditorContributionCtor): void { +export function editorContribution(ctor: IEditorContributionCtor): void { EditorContributionRegistry.INSTANCE.registerEditorBrowserContribution(ctor); } @@ -31,7 +31,7 @@ class EditorContributionRegistry { this.editorContributions = []; } - public registerEditorBrowserContribution(ctor:IEditorContributionCtor): void { + public registerEditorBrowserContribution(ctor: IEditorContributionCtor): void { this.editorContributions.push(ctor); } diff --git a/src/vs/editor/browser/editorDom.ts b/src/vs/editor/browser/editorDom.ts index e11178b99434b..2a227addb95c8 100644 --- a/src/vs/editor/browser/editorDom.ts +++ b/src/vs/editor/browser/editorDom.ts @@ -4,10 +4,10 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {IDisposable, Disposable} from 'vs/base/common/lifecycle'; -import {StandardMouseEvent} from 'vs/base/browser/mouseEvent'; +import { IDisposable, Disposable } from 'vs/base/common/lifecycle'; +import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import * as dom from 'vs/base/browser/dom'; -import {GlobalMouseMoveMonitor} from 'vs/base/browser/globalMouseMoveMonitor'; +import { GlobalMouseMoveMonitor } from 'vs/base/browser/globalMouseMoveMonitor'; export class EditorMouseEvent extends StandardMouseEvent { _editorMouseEventBrand: void; @@ -24,7 +24,7 @@ export class EditorMouseEvent extends StandardMouseEvent { */ viewporty: number; - constructor(e:MouseEvent, editorViewDomNode: HTMLElement) { + constructor(e: MouseEvent, editorViewDomNode: HTMLElement) { super(e); this.editorPos = dom.getDomNodePagePosition(editorViewDomNode); @@ -34,7 +34,7 @@ export class EditorMouseEvent extends StandardMouseEvent { } export interface EditorMouseEventMerger { - (lastEvent:EditorMouseEvent, currentEvent:EditorMouseEvent): EditorMouseEvent; + (lastEvent: EditorMouseEvent, currentEvent: EditorMouseEvent): EditorMouseEvent; } export class EditorMouseEventFactory { @@ -45,36 +45,36 @@ export class EditorMouseEventFactory { this._editorViewDomNode = editorViewDomNode; } - private _create(e:MouseEvent): EditorMouseEvent { + private _create(e: MouseEvent): EditorMouseEvent { return new EditorMouseEvent(e, this._editorViewDomNode); } - public onContextMenu(target:HTMLElement, callback:(e:EditorMouseEvent)=>void): IDisposable { - return dom.addDisposableListener(target, 'contextmenu', (e:MouseEvent) => { + public onContextMenu(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { + return dom.addDisposableListener(target, 'contextmenu', (e: MouseEvent) => { callback(this._create(e)); }); } - public onMouseUp(target:HTMLElement, callback:(e:EditorMouseEvent)=>void): IDisposable { - return dom.addDisposableListener(target, 'mouseup', (e:MouseEvent) => { + public onMouseUp(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { + return dom.addDisposableListener(target, 'mouseup', (e: MouseEvent) => { callback(this._create(e)); }); } - public onMouseDown(target:HTMLElement, callback:(e:EditorMouseEvent)=>void): IDisposable { - return dom.addDisposableListener(target, 'mousedown', (e:MouseEvent) => { + public onMouseDown(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { + return dom.addDisposableListener(target, 'mousedown', (e: MouseEvent) => { callback(this._create(e)); }); } - public onMouseLeave(target:HTMLElement, callback:(e:EditorMouseEvent)=>void): IDisposable { - return dom.addDisposableNonBubblingMouseOutListener(target, (e:MouseEvent) => { + public onMouseLeave(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { + return dom.addDisposableNonBubblingMouseOutListener(target, (e: MouseEvent) => { callback(this._create(e)); }); } - public onMouseMoveThrottled(target:HTMLElement, callback:(e:EditorMouseEvent)=>void, merger:EditorMouseEventMerger, minimumTimeMs:number): IDisposable { - let myMerger: dom.IEventMerger = (lastEvent:EditorMouseEvent, currentEvent:MouseEvent): EditorMouseEvent => { + public onMouseMoveThrottled(target: HTMLElement, callback: (e: EditorMouseEvent) => void, merger: EditorMouseEventMerger, minimumTimeMs: number): IDisposable { + let myMerger: dom.IEventMerger = (lastEvent: EditorMouseEvent, currentEvent: MouseEvent): EditorMouseEvent => { return merger(lastEvent, this._create(currentEvent)); }; return dom.addDisposableThrottledListener(target, 'mousemove', callback, myMerger, minimumTimeMs); @@ -92,8 +92,8 @@ export class GlobalEditorMouseMoveMonitor extends Disposable { this._globalMouseMoveMonitor = this._register(new GlobalMouseMoveMonitor()); } - public startMonitoring(merger:EditorMouseEventMerger, mouseMoveCallback:(e:EditorMouseEvent)=>void, onStopCallback:()=>void): void { - let myMerger: dom.IEventMerger = (lastEvent:EditorMouseEvent, currentEvent:MouseEvent): EditorMouseEvent => { + public startMonitoring(merger: EditorMouseEventMerger, mouseMoveCallback: (e: EditorMouseEvent) => void, onStopCallback: () => void): void { + let myMerger: dom.IEventMerger = (lastEvent: EditorMouseEvent, currentEvent: MouseEvent): EditorMouseEvent => { return merger(lastEvent, new EditorMouseEvent(currentEvent, this._editorViewDomNode)); }; this._globalMouseMoveMonitor.startMonitoring(myMerger, mouseMoveCallback, onStopCallback); diff --git a/src/vs/editor/browser/services/codeEditorServiceImpl.ts b/src/vs/editor/browser/services/codeEditorServiceImpl.ts index 8de809ec75816..9784da84372e2 100644 --- a/src/vs/editor/browser/services/codeEditorServiceImpl.ts +++ b/src/vs/editor/browser/services/codeEditorServiceImpl.ts @@ -9,15 +9,17 @@ import { parse, stringify } from 'vs/base/common/marshalling'; import * as strings from 'vs/base/common/strings'; import URI from 'vs/base/common/uri'; import * as dom from 'vs/base/browser/dom'; -import {IDecorationRenderOptions, IModelDecorationOptions, IModelDecorationOverviewRulerOptions, IThemeDecorationRenderOptions, - IContentDecorationRenderOptions, OverviewRulerLane, TrackedRangeStickiness} from 'vs/editor/common/editorCommon'; -import {AbstractCodeEditorService} from 'vs/editor/common/services/abstractCodeEditorService'; -import {IDisposable, toDisposable} from 'vs/base/common/lifecycle'; +import { + IDecorationRenderOptions, IModelDecorationOptions, IModelDecorationOverviewRulerOptions, IThemeDecorationRenderOptions, + IContentDecorationRenderOptions, OverviewRulerLane, TrackedRangeStickiness +} from 'vs/editor/common/editorCommon'; +import { AbstractCodeEditorService } from 'vs/editor/common/services/abstractCodeEditorService'; +import { IDisposable, toDisposable } from 'vs/base/common/lifecycle'; export class CodeEditorServiceImpl extends AbstractCodeEditorService { private _styleSheet: HTMLStyleElement; - private _decorationOptionProviders: {[key:string]:IModelDecorationOptionsProvider}; + private _decorationOptionProviders: { [key: string]: IModelDecorationOptionsProvider }; constructor(styleSheet = dom.createStyleSheet()) { super(); @@ -25,7 +27,7 @@ export class CodeEditorServiceImpl extends AbstractCodeEditorService { this._decorationOptionProviders = Object.create(null); } - public registerDecorationType(key:string, options: IDecorationRenderOptions, parentTypeKey?: string): void { + public registerDecorationType(key: string, options: IDecorationRenderOptions, parentTypeKey?: string): void { let provider = this._decorationOptionProviders[key]; if (!provider) { if (!parentTypeKey) { @@ -38,7 +40,7 @@ export class CodeEditorServiceImpl extends AbstractCodeEditorService { provider.refCount++; } - public removeDecorationType(key:string): void { + public removeDecorationType(key: string): void { let provider = this._decorationOptionProviders[key]; if (provider) { provider.refCount--; @@ -50,7 +52,7 @@ export class CodeEditorServiceImpl extends AbstractCodeEditorService { } } - public resolveDecorationOptions(decorationTypeKey:string, writable: boolean): IModelDecorationOptions { + public resolveDecorationOptions(decorationTypeKey: string, writable: boolean): IModelDecorationOptions { let provider = this._decorationOptionProviders[decorationTypeKey]; if (!provider) { throw new Error('Unknown decoration type key: ' + decorationTypeKey); @@ -74,7 +76,7 @@ class DecorationSubTypeOptionsProvider implements IModelDecorationOptionsProvide private _beforeContentClassName: string; private _afterContentClassName: string; - constructor(styleSheet: HTMLStyleElement, key: string, parentTypeKey: string, options:IDecorationRenderOptions) { + constructor(styleSheet: HTMLStyleElement, key: string, parentTypeKey: string, options: IDecorationRenderOptions) { this._parentTypeKey = parentTypeKey; this.refCount = 0; @@ -137,11 +139,11 @@ class DecorationTypeOptionsProvider implements IModelDecorationOptionsProvider { public beforeContentClassName: string; public afterContentClassName: string; public glyphMarginClassName: string; - public isWholeLine:boolean; - public overviewRuler:IModelDecorationOverviewRulerOptions; + public isWholeLine: boolean; + public overviewRuler: IModelDecorationOverviewRulerOptions; public stickiness: TrackedRangeStickiness; - constructor(styleSheet: HTMLStyleElement, key:string, options:IDecorationRenderOptions) { + constructor(styleSheet: HTMLStyleElement, key: string, options: IDecorationRenderOptions) { this.refCount = 0; var themedOpts = getThemedRenderOptions(options); @@ -277,7 +279,7 @@ class DecorationRenderHelper { /** * Build the CSS for decorations styled via `className`. */ - public static getCSSTextForModelDecorationClassName(opts:IThemeDecorationRenderOptions): string { + public static getCSSTextForModelDecorationClassName(opts: IThemeDecorationRenderOptions): string { let cssTextArr = []; DecorationRenderHelper.collectCSSText(opts, ['backgroundColor', 'outline', 'outlineColor', 'outlineStyle', 'outlineWidth'], cssTextArr); DecorationRenderHelper.collectBorderSettingsCSSText(opts, cssTextArr); @@ -288,7 +290,7 @@ class DecorationRenderHelper { /** * Build the CSS for decorations styled via `inlineClassName`. */ - public static getCSSTextForModelDecorationInlineClassName(opts:IThemeDecorationRenderOptions): string { + public static getCSSTextForModelDecorationInlineClassName(opts: IThemeDecorationRenderOptions): string { let cssTextArr = []; DecorationRenderHelper.collectCSSText(opts, ['textDecoration', 'cursor', 'color', 'letterSpacing'], cssTextArr); return cssTextArr.join(''); @@ -297,7 +299,7 @@ class DecorationRenderHelper { /** * Build the CSS for decorations styled before or after content. */ - public static getCSSTextForModelDecorationContentClassName(opts:IContentDecorationRenderOptions): string { + public static getCSSTextForModelDecorationContentClassName(opts: IContentDecorationRenderOptions): string { let cssTextArr = []; if (typeof opts !== 'undefined') { @@ -323,7 +325,7 @@ class DecorationRenderHelper { /** * Build the CSS for decorations styled via `glpyhMarginClassName`. */ - public static getCSSTextForModelDecorationGlyphMarginClassName(opts:IThemeDecorationRenderOptions): string { + public static getCSSTextForModelDecorationGlyphMarginClassName(opts: IThemeDecorationRenderOptions): string { let cssTextArr = []; if (typeof opts.gutterIconPath !== 'undefined') { @@ -342,7 +344,7 @@ class DecorationRenderHelper { private static border_rules = ['border', 'borderColor', 'borderColor', 'borderSpacing', 'borderStyle', 'borderWidth']; - public static collectBorderSettingsCSSText(opts: any, cssTextArr: string[]) : boolean { + public static collectBorderSettingsCSSText(opts: any, cssTextArr: string[]): boolean { if (DecorationRenderHelper.collectCSSText(opts, DecorationRenderHelper.border_rules, cssTextArr)) { cssTextArr.push(strings.format('box-sizing: border-box;')); return true; @@ -350,7 +352,7 @@ class DecorationRenderHelper { return false; } - private static collectCSSText(opts: any, properties: string[], cssTextArr: string[]) : boolean { + private static collectCSSText(opts: any, properties: string[], cssTextArr: string[]): boolean { let lenBefore = cssTextArr.length; for (let property of properties) { if (typeof opts[property] !== 'undefined') { @@ -363,8 +365,8 @@ class DecorationRenderHelper { /** * Create CSS rules for `cssTexts` with the generated class names from `ruleType` */ - public static createCSSRules(styleSheet: HTMLStyleElement, key:string, parentKey: string, ruleType:ModelDecorationCSSRuleType, cssTexts: {light:string, dark:string}): string { - function createCSSSelector(themeType:ThemeType, cssText:string) { + public static createCSSRules(styleSheet: HTMLStyleElement, key: string, parentKey: string, ruleType: ModelDecorationCSSRuleType, cssTexts: { light: string, dark: string }): string { + function createCSSSelector(themeType: ThemeType, cssText: string) { let selector = CSSNameHelper.getSelector(themeType, key, parentKey, ruleType); dom.createCSSRule(selector, cssText, styleSheet); } @@ -405,7 +407,7 @@ const enum ModelDecorationCSSRuleType { class CSSNameHelper { - private static _getSelectorPrefixOf(theme:ThemeType): string { + private static _getSelectorPrefixOf(theme: ThemeType): string { if (theme === ThemeType.Light) { return '.monaco-editor.vs'; } @@ -415,11 +417,11 @@ class CSSNameHelper { return '.monaco-editor.hc-black'; } - public static getClassName(key:string, type:ModelDecorationCSSRuleType): string { + public static getClassName(key: string, type: ModelDecorationCSSRuleType): string { return 'ced-' + key + '-' + type; } - public static getSelector(themeType:ThemeType, key:string, parentKey: string, ruleType:ModelDecorationCSSRuleType): string { + public static getSelector(themeType: ThemeType, key: string, parentKey: string, ruleType: ModelDecorationCSSRuleType): string { let selector = this._getSelectorPrefixOf(themeType) + ' .' + this.getClassName(key, ruleType); if (parentKey) { selector = selector + '.' + this.getClassName(parentKey, ruleType); @@ -432,7 +434,7 @@ class CSSNameHelper { return selector; } - public static getDeletionSubstring(key:string): string { + public static getDeletionSubstring(key: string): string { return '.ced-' + key + '-'; } } diff --git a/src/vs/editor/browser/standalone/colorizer.ts b/src/vs/editor/browser/standalone/colorizer.ts index bd1691a5e1ba9..2d9d291325f96 100644 --- a/src/vs/editor/browser/standalone/colorizer.ts +++ b/src/vs/editor/browser/standalone/colorizer.ts @@ -4,13 +4,13 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {IDisposable} from 'vs/base/common/lifecycle'; -import {TPromise} from 'vs/base/common/winjs.base'; -import {IModel} from 'vs/editor/common/editorCommon'; -import {TokenizationRegistry, ITokenizationSupport} from 'vs/editor/common/modes'; -import {IModeService} from 'vs/editor/common/services/modeService'; -import {renderLine, RenderLineInput} from 'vs/editor/common/viewLayout/viewLineRenderer'; -import {ViewLineToken} from 'vs/editor/common/core/viewLineToken'; +import { IDisposable } from 'vs/base/common/lifecycle'; +import { TPromise } from 'vs/base/common/winjs.base'; +import { IModel } from 'vs/editor/common/editorCommon'; +import { TokenizationRegistry, ITokenizationSupport } from 'vs/editor/common/modes'; +import { IModeService } from 'vs/editor/common/services/modeService'; +import { renderLine, RenderLineInput } from 'vs/editor/common/viewLayout/viewLineRenderer'; +import { ViewLineToken } from 'vs/editor/common/core/viewLineToken'; export interface IColorizerOptions { tabSize?: number; @@ -23,7 +23,7 @@ export interface IColorizerElementOptions extends IColorizerOptions { export class Colorizer { - public static colorizeElement(modeService:IModeService, domNode:HTMLElement, options:IColorizerElementOptions): TPromise { + public static colorizeElement(modeService: IModeService, domNode: HTMLElement, options: IColorizerElementOptions): TPromise { options = options || {}; let theme = options.theme || 'vs'; let mimeType = options.mimeType || domNode.getAttribute('lang') || domNode.getAttribute('data-lang'); @@ -33,13 +33,13 @@ export class Colorizer { } let text = domNode.firstChild.nodeValue; domNode.className += 'monaco-editor ' + theme; - let render = (str:string) => { + let render = (str: string) => { domNode.innerHTML = str; }; return this.colorize(modeService, text, mimeType, options).then(render, (err) => console.error(err), render); } - private static _tokenizationSupportChangedPromise(languageId:string): TPromise { + private static _tokenizationSupportChangedPromise(languageId: string): TPromise { let listener: IDisposable = null; let stopListening = () => { if (listener) { @@ -58,7 +58,7 @@ export class Colorizer { }, stopListening); } - public static colorize(modeService:IModeService, text:string, mimeType:string, options:IColorizerOptions): TPromise { + public static colorize(modeService: IModeService, text: string, mimeType: string, options: IColorizerOptions): TPromise { let lines = text.split('\n'); let languageId = modeService.getModeId(mimeType); @@ -85,7 +85,7 @@ export class Colorizer { }); } - public static colorizeLine(line:string, tokens:ViewLineToken[], tabSize:number = 4): string { + public static colorizeLine(line: string, tokens: ViewLineToken[], tabSize: number = 4): string { let renderResult = renderLine(new RenderLineInput( line, tabSize, @@ -98,7 +98,7 @@ export class Colorizer { return renderResult.output; } - public static colorizeModelLine(model:IModel, lineNumber:number, tabSize:number = 4): string { + public static colorizeModelLine(model: IModel, lineNumber: number, tabSize: number = 4): string { let content = model.getLineContent(lineNumber); let tokens = model.getLineTokens(lineNumber, false); let inflatedTokens = tokens.inflate(); @@ -106,12 +106,12 @@ export class Colorizer { } } -function _colorize(lines:string[], tabSize:number, tokenizationSupport: ITokenizationSupport): string { +function _colorize(lines: string[], tabSize: number, tokenizationSupport: ITokenizationSupport): string { return _actualColorize(lines, tabSize, tokenizationSupport); } -function _fakeColorize(lines:string[], tabSize:number): string { - let html:string[] = []; +function _fakeColorize(lines: string[], tabSize: number): string { + let html: string[] = []; for (let i = 0, length = lines.length; i < length; i++) { let line = lines[i]; @@ -133,8 +133,8 @@ function _fakeColorize(lines:string[], tabSize:number): string { return html.join(''); } -function _actualColorize(lines:string[], tabSize:number, tokenizationSupport: ITokenizationSupport): string { - let html:string[] = []; +function _actualColorize(lines: string[], tabSize: number, tokenizationSupport: ITokenizationSupport): string { + let html: string[] = []; let state = tokenizationSupport.getInitialState(); for (let i = 0, length = lines.length; i < length; i++) { diff --git a/src/vs/editor/browser/standalone/simpleServices.ts b/src/vs/editor/browser/standalone/simpleServices.ts index 567e3b097d29d..09e5a301b1cc9 100644 --- a/src/vs/editor/browser/standalone/simpleServices.ts +++ b/src/vs/editor/browser/standalone/simpleServices.ts @@ -4,47 +4,47 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {Schemas} from 'vs/base/common/network'; +import { Schemas } from 'vs/base/common/network'; import Severity from 'vs/base/common/severity'; -import {TPromise} from 'vs/base/common/winjs.base'; -import {IConfigurationService, IConfigurationServiceEvent, IConfigurationValue, getConfigurationValue} from 'vs/platform/configuration/common/configuration'; -import {IEditor, IEditorInput, IEditorOptions, IEditorService, IResourceInput, ITextEditorModel, Position} from 'vs/platform/editor/common/editor'; -import {AbstractExtensionService, ActivatedExtension} from 'vs/platform/extensions/common/abstractExtensionService'; -import {IExtensionDescription, IExtensionService} from 'vs/platform/extensions/common/extensions'; -import {ICommandService, ICommand, ICommandHandler} from 'vs/platform/commands/common/commands'; -import {KeybindingService} from 'vs/platform/keybinding/browser/keybindingServiceImpl'; -import {IOSupport} from 'vs/platform/keybinding/common/keybindingResolver'; -import {IKeybindingItem} from 'vs/platform/keybinding/common/keybinding'; -import {IContextKeyService} from 'vs/platform/contextkey/common/contextkey'; -import {IConfirmation, IMessageService} from 'vs/platform/message/common/message'; +import { TPromise } from 'vs/base/common/winjs.base'; +import { IConfigurationService, IConfigurationServiceEvent, IConfigurationValue, getConfigurationValue } from 'vs/platform/configuration/common/configuration'; +import { IEditor, IEditorInput, IEditorOptions, IEditorService, IResourceInput, ITextEditorModel, Position } from 'vs/platform/editor/common/editor'; +import { AbstractExtensionService, ActivatedExtension } from 'vs/platform/extensions/common/abstractExtensionService'; +import { IExtensionDescription, IExtensionService } from 'vs/platform/extensions/common/extensions'; +import { ICommandService, ICommand, ICommandHandler } from 'vs/platform/commands/common/commands'; +import { KeybindingService } from 'vs/platform/keybinding/browser/keybindingServiceImpl'; +import { IOSupport } from 'vs/platform/keybinding/common/keybindingResolver'; +import { IKeybindingItem } from 'vs/platform/keybinding/common/keybinding'; +import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; +import { IConfirmation, IMessageService } from 'vs/platform/message/common/message'; import * as editorCommon from 'vs/editor/common/editorCommon'; -import {ICodeEditor, IDiffEditor} from 'vs/editor/browser/editorBrowser'; -import {Selection} from 'vs/editor/common/core/selection'; -import Event, {Emitter} from 'vs/base/common/event'; -import {getDefaultValues as getDefaultConfiguration} from 'vs/platform/configuration/common/model'; -import {CommandService} from 'vs/platform/commands/common/commandService'; -import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; -import {IProgressService, IProgressRunner} from 'vs/platform/progress/common/progress'; +import { ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; +import { Selection } from 'vs/editor/common/core/selection'; +import Event, { Emitter } from 'vs/base/common/event'; +import { getDefaultValues as getDefaultConfiguration } from 'vs/platform/configuration/common/model'; +import { CommandService } from 'vs/platform/commands/common/commandService'; +import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; +import { IProgressService, IProgressRunner } from 'vs/platform/progress/common/progress'; export class SimpleEditor implements IEditor { - public input:IEditorInput; - public options:IEditorOptions; - public position:Position; + public input: IEditorInput; + public options: IEditorOptions; + public position: Position; - public _widget:editorCommon.IEditor; + public _widget: editorCommon.IEditor; - constructor(editor:editorCommon.IEditor) { + constructor(editor: editorCommon.IEditor) { this._widget = editor; } - public getId():string { return 'editor'; } - public getControl():editorCommon.IEditor { return this._widget; } - public getSelection():Selection { return this._widget.getSelection(); } - public focus():void { this._widget.focus(); } - public isVisible():boolean { return true; } + public getId(): string { return 'editor'; } + public getControl(): editorCommon.IEditor { return this._widget; } + public getSelection(): Selection { return this._widget.getSelection(); } + public focus(): void { this._widget.focus(); } + public isVisible(): boolean { return true; } - public withTypedEditor(codeEditorCallback:(editor:ICodeEditor)=>T, diffEditorCallback:(editor:IDiffEditor)=>T): T { + public withTypedEditor(codeEditorCallback: (editor: ICodeEditor) => T, diffEditorCallback: (editor: IDiffEditor) => T): T { if (this._widget.getEditorType() === editorCommon.EditorType.ICodeEditor) { // Single Editor return codeEditorCallback(this._widget); @@ -55,12 +55,12 @@ export class SimpleEditor implements IEditor { } } -export class SimpleModel implements ITextEditorModel { +export class SimpleModel implements ITextEditorModel { - private model:editorCommon.IModel; + private model: editorCommon.IModel; private _onDispose: Emitter; - constructor(model:editorCommon.IModel) { + constructor(model: editorCommon.IModel) { this.model = model; this._onDispose = new Emitter(); } @@ -73,7 +73,7 @@ export class SimpleModel implements ITextEditorModel { return TPromise.as(this); } - public get textEditorModel():editorCommon.IModel { + public get textEditorModel(): editorCommon.IModel { return this.model; } @@ -83,28 +83,28 @@ export class SimpleModel implements ITextEditorModel { } export interface IOpenEditorDelegate { - (url:string): boolean; + (url: string): boolean; } export class SimpleEditorService implements IEditorService { public _serviceBrand: any; - private editor:SimpleEditor; - private openEditorDelegate:IOpenEditorDelegate; + private editor: SimpleEditor; + private openEditorDelegate: IOpenEditorDelegate; constructor() { this.openEditorDelegate = null; } - public setEditor(editor:editorCommon.IEditor): void { + public setEditor(editor: editorCommon.IEditor): void { this.editor = new SimpleEditor(editor); } - public setOpenEditorDelegate(openEditorDelegate:IOpenEditorDelegate): void { + public setOpenEditorDelegate(openEditorDelegate: IOpenEditorDelegate): void { this.openEditorDelegate = openEditorDelegate; } - public openEditor(typedData:IResourceInput, sideBySide?:boolean): TPromise { + public openEditor(typedData: IResourceInput, sideBySide?: boolean): TPromise { return TPromise.as(this.editor.withTypedEditor( (editor) => this.doOpenEditor(editor, typedData), (diffEditor) => ( @@ -114,7 +114,7 @@ export class SimpleEditorService implements IEditorService { )); } - private doOpenEditor(editor:editorCommon.ICommonCodeEditor, data:IResourceInput): IEditor { + private doOpenEditor(editor: editorCommon.ICommonCodeEditor, data: IResourceInput): IEditor { var model = this.findModel(editor, data); if (!model) { if (data.resource) { @@ -152,9 +152,9 @@ export class SimpleEditorService implements IEditorService { return this.editor; } - private findModel(editor:editorCommon.ICommonCodeEditor, data:IResourceInput): editorCommon.IModel { + private findModel(editor: editorCommon.ICommonCodeEditor, data: IResourceInput): editorCommon.IModel { var model = editor.getModel(); - if(model.uri.toString() !== data.resource.toString()) { + if (model.uri.toString() !== data.resource.toString()) { return null; } @@ -180,10 +180,10 @@ export class SimpleEditorService implements IEditorService { export class SimpleProgressService implements IProgressService { _serviceBrand: any; - private static NULL_PROGRESS_RUNNER:IProgressRunner = { - done: () => {}, - total: () => {}, - worked: () => {} + private static NULL_PROGRESS_RUNNER: IProgressRunner = { + done: () => { }, + total: () => { }, + worked: () => { } }; show(infinite: boolean, delay?: number): IProgressRunner; @@ -200,11 +200,11 @@ export class SimpleProgressService implements IProgressService { export class SimpleMessageService implements IMessageService { public _serviceBrand: any; - private static Empty = function() { /* nothing */}; + private static Empty = function () { /* nothing */ }; - public show(sev:Severity, message:any):()=>void { + public show(sev: Severity, message: any): () => void { - switch(sev) { + switch (sev) { case Severity.Error: console.error(message); break; @@ -219,11 +219,11 @@ export class SimpleMessageService implements IMessageService { return SimpleMessageService.Empty; } - public hideAll():void { + public hideAll(): void { // No-op } - public confirm(confirmation:IConfirmation):boolean { + public confirm(confirmation: IConfirmation): boolean { var messageText = confirmation.message; if (confirmation.detail) { messageText = messageText + '\n\n' + confirmation.detail; @@ -246,11 +246,11 @@ export class StandaloneCommandService extends CommandService { this._dynamicCommands = Object.create(null); } - public addCommand(id:string, command:ICommand): void { + public addCommand(id: string, command: ICommand): void { this._dynamicCommands[id] = command; } - protected _getCommand(id:string): ICommand { + protected _getCommand(id: string): ICommand { return super._getCommand(id) || this._dynamicCommands[id]; } } @@ -273,7 +273,7 @@ export class StandaloneKeybindingService extends KeybindingService { this._beginListening(domNode); } - public addDynamicKeybinding(keybinding: number, handler:ICommandHandler, when:string, commandId:string = null): string { + public addDynamicKeybinding(keybinding: number, handler: ICommandHandler, when: string, commandId: string = null): string { if (commandId === null) { commandId = 'DYNAMIC_' + (++StandaloneKeybindingService.LAST_GENERATED_ID); } @@ -298,7 +298,7 @@ export class StandaloneKeybindingService extends KeybindingService { return commandId; } - protected _getExtraKeybindings(isFirstTime:boolean): IKeybindingItem[] { + protected _getExtraKeybindings(isFirstTime: boolean): IKeybindingItem[] { return this._dynamicKeybindings; } } @@ -309,7 +309,7 @@ export class SimpleExtensionService extends AbstractExtensionService(key: string, defaultValue: T): IContextKey; - addAction(descriptor:IActionDescriptor): void; + addAction(descriptor: IActionDescriptor): void; } export interface IStandaloneDiffEditor extends IDiffEditor { - addCommand(keybinding:number, handler:ICommandHandler, context:string): string; + addCommand(keybinding: number, handler: ICommandHandler, context: string): string; createContextKey(key: string, defaultValue: T): IContextKey; - addAction(descriptor:IActionDescriptor): void; + addAction(descriptor: IActionDescriptor): void; } export class StandaloneEditor extends CodeEditor implements IStandaloneCodeEditor { private _standaloneKeybindingService: StandaloneKeybindingService; - private _contextViewService:IEditorContextViewService; - private _ownsModel:boolean; + private _contextViewService: IEditorContextViewService; + private _ownsModel: boolean; private _toDispose2: IDisposable[]; constructor( - domElement:HTMLElement, - options:IEditorConstructionOptions, + domElement: HTMLElement, + options: IEditorConstructionOptions, toDispose: IDisposable, @IInstantiationService instantiationService: IInstantiationService, @ICodeEditorService codeEditorService: ICodeEditorService, @@ -112,7 +112,7 @@ export class StandaloneEditor extends CodeEditor implements IStandaloneCodeEdito this.dispose(); } - public addCommand(keybinding:number, handler:ICommandHandler, context:string): string { + public addCommand(keybinding: number, handler: ICommandHandler, context: string): string { if (!this._standaloneKeybindingService) { console.warn('Cannot add command because the editor is configured with an unrecognized KeybindingService'); return null; @@ -128,7 +128,7 @@ export class StandaloneEditor extends CodeEditor implements IStandaloneCodeEdito return this._contextKeyService.createKey(key, defaultValue); } - public addAction(descriptor:IActionDescriptor): void { + public addAction(descriptor: IActionDescriptor): void { super.addAction(descriptor); if (!this._standaloneKeybindingService) { console.warn('Cannot add keybinding because the editor is configured with an unrecognized KeybindingService'); @@ -144,14 +144,14 @@ export class StandaloneEditor extends CodeEditor implements IStandaloneCodeEdito } } - _attachModel(model:IModel):void { + _attachModel(model: IModel): void { super._attachModel(model); if (this._view) { this._contextViewService.setContainer(this._view.domNode); } } - _postDetachModelCleanup(detachedModel:IModel): void { + _postDetachModelCleanup(detachedModel: IModel): void { super._postDetachModelCleanup(detachedModel); if (detachedModel && this._ownsModel) { detachedModel.dispose(); @@ -162,13 +162,13 @@ export class StandaloneEditor extends CodeEditor implements IStandaloneCodeEdito export class StandaloneDiffEditor extends DiffEditorWidget implements IStandaloneDiffEditor { - private _contextViewService:IEditorContextViewService; + private _contextViewService: IEditorContextViewService; private _standaloneKeybindingService: StandaloneKeybindingService; private _toDispose2: IDisposable[]; constructor( - domElement:HTMLElement, - options:IDiffEditorConstructionOptions, + domElement: HTMLElement, + options: IDiffEditorConstructionOptions, toDispose: IDisposable, @IInstantiationService instantiationService: IInstantiationService, @IContextKeyService contextKeyService: IContextKeyService, @@ -198,7 +198,7 @@ export class StandaloneDiffEditor extends DiffEditorWidget implements IStandalon this.dispose(); } - public addCommand(keybinding:number, handler:ICommandHandler, context:string): string { + public addCommand(keybinding: number, handler: ICommandHandler, context: string): string { if (!this._standaloneKeybindingService) { console.warn('Cannot add command because the editor is configured with an unrecognized KeybindingService'); return null; @@ -214,14 +214,14 @@ export class StandaloneDiffEditor extends DiffEditorWidget implements IStandalon return this._contextKeyService.createKey(key, defaultValue); } - public addAction(descriptor:IActionDescriptor): void { + public addAction(descriptor: IActionDescriptor): void { super.addAction(descriptor); if (!this._standaloneKeybindingService) { console.warn('Cannot add keybinding because the editor is configured with an unrecognized KeybindingService'); return null; } if (Array.isArray(descriptor.keybindings)) { - var handler:ICommandHandler = (ctx) => { + var handler: ICommandHandler = (ctx) => { return this.trigger('keyboard', descriptor.id, null); }; descriptor.keybindings.forEach((kb) => { diff --git a/src/vs/editor/browser/standalone/standaloneEditor.ts b/src/vs/editor/browser/standalone/standaloneEditor.ts index 4c7a386de96ec..6f44f8f92dbcf 100644 --- a/src/vs/editor/browser/standalone/standaloneEditor.ts +++ b/src/vs/editor/browser/standalone/standaloneEditor.ts @@ -6,30 +6,30 @@ import 'vs/css!./media/standalone-tokens'; import * as editorCommon from 'vs/editor/common/editorCommon'; -import {ContentWidgetPositionPreference, OverlayWidgetPositionPreference} from 'vs/editor/browser/editorBrowser'; -import {StandaloneEditor, IStandaloneCodeEditor, StandaloneDiffEditor, IStandaloneDiffEditor, IEditorConstructionOptions, IDiffEditorConstructionOptions} from 'vs/editor/browser/standalone/standaloneCodeEditor'; -import {ScrollbarVisibility} from 'vs/base/common/scrollable'; -import {IEditorOverrideServices, DynamicStandaloneServices, StaticServices} from 'vs/editor/browser/standalone/standaloneServices'; -import {IDisposable} from 'vs/base/common/lifecycle'; +import { ContentWidgetPositionPreference, OverlayWidgetPositionPreference } from 'vs/editor/browser/editorBrowser'; +import { StandaloneEditor, IStandaloneCodeEditor, StandaloneDiffEditor, IStandaloneDiffEditor, IEditorConstructionOptions, IDiffEditorConstructionOptions } from 'vs/editor/browser/standalone/standaloneCodeEditor'; +import { ScrollbarVisibility } from 'vs/base/common/scrollable'; +import { IEditorOverrideServices, DynamicStandaloneServices, StaticServices } from 'vs/editor/browser/standalone/standaloneServices'; +import { IDisposable } from 'vs/base/common/lifecycle'; import URI from 'vs/base/common/uri'; -import {TPromise} from 'vs/base/common/winjs.base'; -import {OpenerService} from 'vs/platform/opener/browser/openerService'; -import {IOpenerService} from 'vs/platform/opener/common/opener'; -import {IModel} from 'vs/editor/common/editorCommon'; -import {Colorizer, IColorizerElementOptions, IColorizerOptions} from 'vs/editor/browser/standalone/colorizer'; -import {SimpleEditorService} from 'vs/editor/browser/standalone/simpleServices'; +import { TPromise } from 'vs/base/common/winjs.base'; +import { OpenerService } from 'vs/platform/opener/browser/openerService'; +import { IOpenerService } from 'vs/platform/opener/common/opener'; +import { IModel } from 'vs/editor/common/editorCommon'; +import { Colorizer, IColorizerElementOptions, IColorizerOptions } from 'vs/editor/browser/standalone/colorizer'; +import { SimpleEditorService } from 'vs/editor/browser/standalone/simpleServices'; import * as modes from 'vs/editor/common/modes'; -import {IWebWorkerOptions, MonacoWebWorker, createWebWorker as actualCreateWebWorker} from 'vs/editor/common/services/webWorker'; -import {IMarkerData} from 'vs/platform/markers/common/markers'; -import {DiffNavigator} from 'vs/editor/contrib/diffNavigator/common/diffNavigator'; -import {IEditorService} from 'vs/platform/editor/common/editor'; -import {ICommandService} from 'vs/platform/commands/common/commands'; -import {IContextViewService} from 'vs/platform/contextview/browser/contextView'; -import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; -import {IKeybindingService} from 'vs/platform/keybinding/common/keybinding'; -import {IContextKeyService} from 'vs/platform/contextkey/common/contextkey'; -import {ICodeEditorService} from 'vs/editor/common/services/codeEditorService'; -import {IEditorWorkerService} from 'vs/editor/common/services/editorWorkerService'; +import { IWebWorkerOptions, MonacoWebWorker, createWebWorker as actualCreateWebWorker } from 'vs/editor/common/services/webWorker'; +import { IMarkerData } from 'vs/platform/markers/common/markers'; +import { DiffNavigator } from 'vs/editor/contrib/diffNavigator/common/diffNavigator'; +import { IEditorService } from 'vs/platform/editor/common/editor'; +import { ICommandService } from 'vs/platform/commands/common/commands'; +import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; +import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; +import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; +import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; +import { ICodeEditorService } from 'vs/editor/common/services/codeEditorService'; +import { IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService'; /** * @internal @@ -38,7 +38,7 @@ export function setupServices(overrides: IEditorOverrideServices): any { return StaticServices.init(overrides); } -function withAllStandaloneServices(domElement:HTMLElement, override:IEditorOverrideServices, callback:(services:DynamicStandaloneServices)=>T): T { +function withAllStandaloneServices(domElement: HTMLElement, override: IEditorOverrideServices, callback: (services: DynamicStandaloneServices) => T): T { let services = new DynamicStandaloneServices(domElement, override); // The editorService is a lovely beast. It needs to point back to the code editor instance... @@ -66,7 +66,7 @@ function withAllStandaloneServices(domElement:HT * `domElement` should be empty (not contain other dom nodes). * The editor will read the size of `domElement`. */ -export function create(domElement:HTMLElement, options?:IEditorConstructionOptions, override?:IEditorOverrideServices):IStandaloneCodeEditor { +export function create(domElement: HTMLElement, options?: IEditorConstructionOptions, override?: IEditorOverrideServices): IStandaloneCodeEditor { return withAllStandaloneServices(domElement, override, (services) => { return new StandaloneEditor( domElement, @@ -87,7 +87,7 @@ export function create(domElement:HTMLElement, options?:IEditorConstructionOptio * `domElement` should be empty (not contain other dom nodes). * The editor will read the size of `domElement`. */ -export function createDiffEditor(domElement:HTMLElement, options?:IDiffEditorConstructionOptions, override?: IEditorOverrideServices):IStandaloneDiffEditor { +export function createDiffEditor(domElement: HTMLElement, options?: IDiffEditorConstructionOptions, override?: IEditorOverrideServices): IStandaloneDiffEditor { return withAllStandaloneServices(domElement, override, (services) => { return new StandaloneDiffEditor( domElement, @@ -103,23 +103,23 @@ export function createDiffEditor(domElement:HTMLElement, options?:IDiffEditorCon } export interface IDiffNavigator { - canNavigate():boolean; - next():void; - previous():void; - dispose():void; + canNavigate(): boolean; + next(): void; + previous(): void; + dispose(): void; } export interface IDiffNavigatorOptions { - followsCaret?:boolean; - ignoreCharChanges?:boolean; - alwaysRevealFirst?:boolean; + followsCaret?: boolean; + ignoreCharChanges?: boolean; + alwaysRevealFirst?: boolean; } -export function createDiffNavigator(diffEditor:IStandaloneDiffEditor, opts?:IDiffNavigatorOptions): IDiffNavigator { +export function createDiffNavigator(diffEditor: IStandaloneDiffEditor, opts?: IDiffNavigatorOptions): IDiffNavigator { return new DiffNavigator(diffEditor, opts); } -function doCreateModel(value:string, mode:TPromise, uri?:URI): IModel { +function doCreateModel(value: string, mode: TPromise, uri?: URI): IModel { return StaticServices.modelService.get().createModel(value, mode, uri); } @@ -127,7 +127,7 @@ function doCreateModel(value:string, mode:TPromise, uri?:URI): IMod * Create a new editor model. * You can specify the language that should be set for this model or let the language be inferred from the `uri`. */ -export function createModel(value:string, language?:string, uri?:URI): IModel { +export function createModel(value: string, language?: string, uri?: URI): IModel { value = value || ''; if (!language) { @@ -147,14 +147,14 @@ export function createModel(value:string, language?:string, uri?:URI): IModel { /** * Change the language for a model. */ -export function setModelLanguage(model:IModel, language:string): void { +export function setModelLanguage(model: IModel, language: string): void { StaticServices.modelService.get().setMode(model, StaticServices.modeService.get().getOrCreateMode(language)); } /** * Set the markers for a model. */ -export function setModelMarkers(model:IModel, owner:string, markers: IMarkerData[]): void { +export function setModelMarkers(model: IModel, owner: string, markers: IMarkerData[]): void { StaticServices.markerService.get().changeOne(owner, model.uri, markers); } @@ -175,21 +175,21 @@ export function getModels(): IModel[] { /** * Emitted when a model is created. */ -export function onDidCreateModel(listener:(model:IModel)=>void): IDisposable { +export function onDidCreateModel(listener: (model: IModel) => void): IDisposable { return StaticServices.modelService.get().onModelAdded(listener); } /** * Emitted right before a model is disposed. */ -export function onWillDisposeModel(listener:(model:IModel)=>void): IDisposable { +export function onWillDisposeModel(listener: (model: IModel) => void): IDisposable { return StaticServices.modelService.get().onModelRemoved(listener); } /** * Emitted when a different language is set to a model. */ -export function onDidChangeModelLanguage(listener:(e:{ model: IModel; oldLanguage: string; })=>void): IDisposable { +export function onDidChangeModelLanguage(listener: (e: { model: IModel; oldLanguage: string; }) => void): IDisposable { return StaticServices.modelService.get().onModelModeChanged((e) => { listener({ model: e.model, @@ -202,7 +202,7 @@ export function onDidChangeModelLanguage(listener:(e:{ model: IModel; oldLanguag /** * @internal */ -export function getOrCreateMode(modeId: string):TPromise { +export function getOrCreateMode(modeId: string): TPromise { return StaticServices.modeService.get().getOrCreateMode(modeId); } @@ -212,28 +212,28 @@ export function getOrCreateMode(modeId: string):TPromise { * Create a new web worker that has model syncing capabilities built in. * Specify an AMD module to load that will `create` an object that will be proxied. */ -export function createWebWorker(opts:IWebWorkerOptions): MonacoWebWorker { +export function createWebWorker(opts: IWebWorkerOptions): MonacoWebWorker { return actualCreateWebWorker(StaticServices.modelService.get(), opts); } /** * Colorize the contents of `domNode` using attribute `data-lang`. */ -export function colorizeElement(domNode:HTMLElement, options:IColorizerElementOptions): TPromise { +export function colorizeElement(domNode: HTMLElement, options: IColorizerElementOptions): TPromise { return Colorizer.colorizeElement(StaticServices.modeService.get(), domNode, options); } /** * Colorize `text` using language `languageId`. */ -export function colorize(text:string, languageId:string, options:IColorizerOptions): TPromise { +export function colorize(text: string, languageId: string, options: IColorizerOptions): TPromise { return Colorizer.colorize(StaticServices.modeService.get(), text, languageId, options); } /** * Colorize a line in a model. */ -export function colorizeModelLine(model:IModel, lineNumber:number, tabSize:number = 4): string { +export function colorizeModelLine(model: IModel, lineNumber: number, tabSize: number = 4): string { return Colorizer.colorizeModelLine(model, lineNumber, tabSize); } diff --git a/src/vs/editor/browser/standalone/standaloneLanguages.ts b/src/vs/editor/browser/standalone/standaloneLanguages.ts index 088dd6d553101..808d6df14cf3a 100644 --- a/src/vs/editor/browser/standalone/standaloneLanguages.ts +++ b/src/vs/editor/browser/standalone/standaloneLanguages.ts @@ -5,29 +5,29 @@ 'use strict'; -import {TPromise} from 'vs/base/common/winjs.base'; -import {IDisposable} from 'vs/base/common/lifecycle'; -import {ExtensionsRegistry} from 'vs/platform/extensions/common/extensionsRegistry'; -import {ModesRegistry} from 'vs/editor/common/modes/modesRegistry'; -import {IMonarchLanguage} from 'vs/editor/common/modes/monarch/monarchTypes'; -import {ILanguageExtensionPoint} from 'vs/editor/common/services/modeService'; -import {StaticServices} from 'vs/editor/browser/standalone/standaloneServices'; +import { TPromise } from 'vs/base/common/winjs.base'; +import { IDisposable } from 'vs/base/common/lifecycle'; +import { ExtensionsRegistry } from 'vs/platform/extensions/common/extensionsRegistry'; +import { ModesRegistry } from 'vs/editor/common/modes/modesRegistry'; +import { IMonarchLanguage } from 'vs/editor/common/modes/monarch/monarchTypes'; +import { ILanguageExtensionPoint } from 'vs/editor/common/services/modeService'; +import { StaticServices } from 'vs/editor/browser/standalone/standaloneServices'; import * as modes from 'vs/editor/common/modes'; -import {LanguageConfiguration} from 'vs/editor/common/modes/languageConfigurationRegistry'; +import { LanguageConfiguration } from 'vs/editor/common/modes/languageConfigurationRegistry'; import * as editorCommon from 'vs/editor/common/editorCommon'; -import {Position} from 'vs/editor/common/core/position'; -import {Range} from 'vs/editor/common/core/range'; -import {CancellationToken} from 'vs/base/common/cancellation'; -import {toThenable} from 'vs/base/common/async'; -import {compile} from 'vs/editor/common/modes/monarch/monarchCompile'; -import {createTokenizationSupport} from 'vs/editor/common/modes/monarch/monarchLexer'; -import {LanguageConfigurationRegistry} from 'vs/editor/common/modes/languageConfigurationRegistry'; -import {IMarkerData} from 'vs/platform/markers/common/markers'; -import {TokenizationSupport2Adapter} from 'vs/editor/common/services/modeServiceImpl'; +import { Position } from 'vs/editor/common/core/position'; +import { Range } from 'vs/editor/common/core/range'; +import { CancellationToken } from 'vs/base/common/cancellation'; +import { toThenable } from 'vs/base/common/async'; +import { compile } from 'vs/editor/common/modes/monarch/monarchCompile'; +import { createTokenizationSupport } from 'vs/editor/common/modes/monarch/monarchLexer'; +import { LanguageConfigurationRegistry } from 'vs/editor/common/modes/languageConfigurationRegistry'; +import { IMarkerData } from 'vs/platform/markers/common/markers'; +import { TokenizationSupport2Adapter } from 'vs/editor/common/services/modeServiceImpl'; /** * Register information about a new language. */ -export function register(language:ILanguageExtensionPoint): void { +export function register(language: ILanguageExtensionPoint): void { ModesRegistry.registerLanguage(language); } @@ -35,7 +35,7 @@ export function register(language:ILanguageExtensionPoint): void { * Get the information of all the registered languages. */ export function getLanguages(): ILanguageExtensionPoint[] { - let result:ILanguageExtensionPoint[] = []; + let result: ILanguageExtensionPoint[] = []; result = result.concat(ModesRegistry.getLanguages()); return result; } @@ -43,7 +43,7 @@ export function getLanguages(): ILanguageExtensionPoint[] { /** * An event emitted when a language is first time needed (e.g. a model has it set). */ -export function onLanguage(languageId:string, callback:()=>void): IDisposable { +export function onLanguage(languageId: string, callback: () => void): IDisposable { let isDisposed = false; ExtensionsRegistry.registerOneTimeActivationEventListener('onLanguage:' + languageId, () => { if (!isDisposed) { @@ -58,14 +58,14 @@ export function onLanguage(languageId:string, callback:()=>void): IDisposable { /** * Set the editing configuration for a language. */ -export function setLanguageConfiguration(languageId:string, configuration:LanguageConfiguration): IDisposable { +export function setLanguageConfiguration(languageId: string, configuration: LanguageConfiguration): IDisposable { return LanguageConfigurationRegistry.register(languageId, configuration); } /** * Set the tokens provider for a language (manual implementation). */ -export function setTokensProvider(languageId:string, provider:modes.TokensProvider): IDisposable { +export function setTokensProvider(languageId: string, provider: modes.TokensProvider): IDisposable { let adapter = new TokenizationSupport2Adapter(languageId, provider); return modes.TokenizationRegistry.register(languageId, adapter); } @@ -73,7 +73,7 @@ export function setTokensProvider(languageId:string, provider:modes.TokensProvid /** * Set the tokens provider for a language (monarch implementation). */ -export function setMonarchTokensProvider(languageId:string, languageDef:IMonarchLanguage): IDisposable { +export function setMonarchTokensProvider(languageId: string, languageDef: IMonarchLanguage): IDisposable { let lexer = compile(languageId, languageDef); let adapter = createTokenizationSupport(StaticServices.modeService.get(), languageId, lexer); return modes.TokenizationRegistry.register(languageId, adapter); @@ -82,30 +82,30 @@ export function setMonarchTokensProvider(languageId:string, languageDef:IMonarch /** * Register a reference provider (used by e.g. reference search). */ -export function registerReferenceProvider(languageId:string, provider:modes.ReferenceProvider): IDisposable { +export function registerReferenceProvider(languageId: string, provider: modes.ReferenceProvider): IDisposable { return modes.ReferenceProviderRegistry.register(languageId, provider); } /** * Register a rename provider (used by e.g. rename symbol). */ -export function registerRenameProvider(languageId:string, provider:modes.RenameProvider): IDisposable { +export function registerRenameProvider(languageId: string, provider: modes.RenameProvider): IDisposable { return modes.RenameProviderRegistry.register(languageId, provider); } /** * Register a signature help provider (used by e.g. paremeter hints). */ -export function registerSignatureHelpProvider(languageId:string, provider:modes.SignatureHelpProvider): IDisposable { +export function registerSignatureHelpProvider(languageId: string, provider: modes.SignatureHelpProvider): IDisposable { return modes.SignatureHelpProviderRegistry.register(languageId, provider); } /** * Register a hover provider (used by e.g. editor hover). */ -export function registerHoverProvider(languageId:string, provider:modes.HoverProvider): IDisposable { +export function registerHoverProvider(languageId: string, provider: modes.HoverProvider): IDisposable { return modes.HoverProviderRegistry.register(languageId, { - provideHover: (model:editorCommon.IReadOnlyModel, position:Position, token:CancellationToken): Thenable => { + provideHover: (model: editorCommon.IReadOnlyModel, position: Position, token: CancellationToken): Thenable => { let word = model.getWordAtPosition(position); return toThenable(provider.provideHover(model, position, token)).then((value) => { @@ -127,38 +127,38 @@ export function registerHoverProvider(languageId:string, provider:modes.HoverPro /** * Register a document symbol provider (used by e.g. outline). */ -export function registerDocumentSymbolProvider(languageId:string, provider:modes.DocumentSymbolProvider): IDisposable { +export function registerDocumentSymbolProvider(languageId: string, provider: modes.DocumentSymbolProvider): IDisposable { return modes.DocumentSymbolProviderRegistry.register(languageId, provider); } /** * Register a document highlight provider (used by e.g. highlight occurences). */ -export function registerDocumentHighlightProvider(languageId:string, provider:modes.DocumentHighlightProvider): IDisposable { +export function registerDocumentHighlightProvider(languageId: string, provider: modes.DocumentHighlightProvider): IDisposable { return modes.DocumentHighlightProviderRegistry.register(languageId, provider); } /** * Register a definition provider (used by e.g. go to definition). */ -export function registerDefinitionProvider(languageId:string, provider:modes.DefinitionProvider): IDisposable { +export function registerDefinitionProvider(languageId: string, provider: modes.DefinitionProvider): IDisposable { return modes.DefinitionProviderRegistry.register(languageId, provider); } /** * Register a code lens provider (used by e.g. inline code lenses). */ -export function registerCodeLensProvider(languageId:string, provider:modes.CodeLensProvider): IDisposable { +export function registerCodeLensProvider(languageId: string, provider: modes.CodeLensProvider): IDisposable { return modes.CodeLensProviderRegistry.register(languageId, provider); } /** * Register a code action provider (used by e.g. quick fix). */ -export function registerCodeActionProvider(languageId:string, provider:CodeActionProvider): IDisposable { +export function registerCodeActionProvider(languageId: string, provider: CodeActionProvider): IDisposable { return modes.CodeActionProviderRegistry.register(languageId, { - provideCodeActions: (model:editorCommon.IReadOnlyModel, range:Range, token: CancellationToken): modes.CodeAction[] | Thenable => { - let markers = StaticServices.markerService.get().read({resource: model.uri }).filter(m => { + provideCodeActions: (model: editorCommon.IReadOnlyModel, range: Range, token: CancellationToken): modes.CodeAction[] | Thenable => { + let markers = StaticServices.markerService.get().read({ resource: model.uri }).filter(m => { return Range.areIntersectingOrTouching(m, range); }); return provider.provideCodeActions(model, range, { markers }, token); @@ -169,42 +169,42 @@ export function registerCodeActionProvider(languageId:string, provider:CodeActio /** * Register a formatter that can handle only entire models. */ -export function registerDocumentFormattingEditProvider(languageId:string, provider:modes.DocumentFormattingEditProvider): IDisposable { +export function registerDocumentFormattingEditProvider(languageId: string, provider: modes.DocumentFormattingEditProvider): IDisposable { return modes.DocumentFormattingEditProviderRegistry.register(languageId, provider); } /** * Register a formatter that can handle a range inside a model. */ -export function registerDocumentRangeFormattingEditProvider(languageId:string, provider:modes.DocumentRangeFormattingEditProvider): IDisposable { +export function registerDocumentRangeFormattingEditProvider(languageId: string, provider: modes.DocumentRangeFormattingEditProvider): IDisposable { return modes.DocumentRangeFormattingEditProviderRegistry.register(languageId, provider); } /** * Register a formatter than can do formatting as the user types. */ -export function registerOnTypeFormattingEditProvider(languageId:string, provider:modes.OnTypeFormattingEditProvider): IDisposable { +export function registerOnTypeFormattingEditProvider(languageId: string, provider: modes.OnTypeFormattingEditProvider): IDisposable { return modes.OnTypeFormattingEditProviderRegistry.register(languageId, provider); } /** * Register a link provider that can find links in text. */ -export function registerLinkProvider(languageId:string, provider:modes.LinkProvider): IDisposable { +export function registerLinkProvider(languageId: string, provider: modes.LinkProvider): IDisposable { return modes.LinkProviderRegistry.register(languageId, provider); } /** * Register a completion item provider (use by e.g. suggestions). */ -export function registerCompletionItemProvider(languageId:string, provider:CompletionItemProvider): IDisposable { +export function registerCompletionItemProvider(languageId: string, provider: CompletionItemProvider): IDisposable { let adapter = new SuggestAdapter(provider); return modes.SuggestRegistry.register(languageId, { triggerCharacters: provider.triggerCharacters, - provideCompletionItems: (model:editorCommon.IReadOnlyModel, position:Position, token:CancellationToken): Thenable => { + provideCompletionItems: (model: editorCommon.IReadOnlyModel, position: Position, token: CancellationToken): Thenable => { return adapter.provideCompletionItems(model, position, token); }, - resolveCompletionItem: (model:editorCommon.IReadOnlyModel, position:Position, suggestion: modes.ISuggestion, token: CancellationToken): Thenable => { + resolveCompletionItem: (model: editorCommon.IReadOnlyModel, position: Position, suggestion: modes.ISuggestion, token: CancellationToken): Thenable => { return adapter.resolveCompletionItem(model, position, suggestion, token); } }); @@ -232,7 +232,7 @@ export interface CodeActionProvider { /** * Provide commands for the given document and range. */ - provideCodeActions(model:editorCommon.IReadOnlyModel, range:Range, context: CodeActionContext, token: CancellationToken): modes.CodeAction[] | Thenable; + provideCodeActions(model: editorCommon.IReadOnlyModel, range: Range, context: CodeActionContext, token: CancellationToken): modes.CodeAction[] | Thenable; } /** @@ -386,7 +386,7 @@ class SuggestAdapter { this._provider = provider; } - private static from(item:CompletionItem): ISuggestion2 { + private static from(item: CompletionItem): ISuggestion2 { return { _actual: item, label: item.label, @@ -399,9 +399,9 @@ class SuggestAdapter { }; } - provideCompletionItems(model:editorCommon.IReadOnlyModel, position:Position, token:CancellationToken): Thenable { + provideCompletionItems(model: editorCommon.IReadOnlyModel, position: Position, token: CancellationToken): Thenable { - return toThenable(this._provider.provideCompletionItems(model, position, token)).then(value => { + return toThenable(this._provider.provideCompletionItems(model, position, token)).then(value => { const result: modes.ISuggestResult = { suggestions: [], currentWord: '', @@ -463,7 +463,7 @@ class SuggestAdapter { }); } - resolveCompletionItem(model:editorCommon.IReadOnlyModel, position:Position, suggestion: modes.ISuggestion, token: CancellationToken): Thenable { + resolveCompletionItem(model: editorCommon.IReadOnlyModel, position: Position, suggestion: modes.ISuggestion, token: CancellationToken): Thenable { if (typeof this._provider.resolveCompletionItem !== 'function') { return TPromise.as(suggestion); } diff --git a/src/vs/editor/browser/standalone/standaloneServices.ts b/src/vs/editor/browser/standalone/standaloneServices.ts index 3d6289b98c0d9..99fe19a0d73ad 100644 --- a/src/vs/editor/browser/standalone/standaloneServices.ts +++ b/src/vs/editor/browser/standalone/standaloneServices.ts @@ -4,47 +4,47 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {Disposable} from 'vs/base/common/lifecycle'; +import { Disposable } from 'vs/base/common/lifecycle'; import URI from 'vs/base/common/uri'; -import {IConfigurationService} from 'vs/platform/configuration/common/configuration'; -import {ContextMenuService} from 'vs/platform/contextview/browser/contextMenuService'; -import {IContextMenuService, IContextViewService} from 'vs/platform/contextview/browser/contextView'; -import {ContextViewService} from 'vs/platform/contextview/browser/contextViewService'; -import {IEventService} from 'vs/platform/event/common/event'; -import {EventService} from 'vs/platform/event/common/eventService'; -import {IExtensionService} from 'vs/platform/extensions/common/extensions'; -import {createDecorator, IInstantiationService, ServiceIdentifier} from 'vs/platform/instantiation/common/instantiation'; -import {InstantiationService} from 'vs/platform/instantiation/common/instantiationService'; -import {ServiceCollection} from 'vs/platform/instantiation/common/serviceCollection'; -import {ICommandService} from 'vs/platform/commands/common/commands'; -import {IKeybindingService} from 'vs/platform/keybinding/common/keybinding'; -import {IContextKeyService} from 'vs/platform/contextkey/common/contextkey'; -import {MarkerService} from 'vs/platform/markers/common/markerService'; -import {IMarkerService} from 'vs/platform/markers/common/markers'; -import {IMessageService} from 'vs/platform/message/common/message'; -import {IProgressService} from 'vs/platform/progress/common/progress'; -import {IStorageService, NullStorageService} from 'vs/platform/storage/common/storage'; -import {ITelemetryService, NullTelemetryService} from 'vs/platform/telemetry/common/telemetry'; -import {IWorkspaceContextService, WorkspaceContextService} from 'vs/platform/workspace/common/workspace'; -import {ICodeEditorService} from 'vs/editor/common/services/codeEditorService'; -import {IEditorWorkerService} from 'vs/editor/common/services/editorWorkerService'; -import {EditorWorkerServiceImpl} from 'vs/editor/common/services/editorWorkerServiceImpl'; -import {IModeService} from 'vs/editor/common/services/modeService'; -import {MainThreadModeServiceImpl} from 'vs/editor/common/services/modeServiceImpl'; -import {IModelService} from 'vs/editor/common/services/modelService'; -import {ModelServiceImpl} from 'vs/editor/common/services/modelServiceImpl'; -import {CodeEditorServiceImpl} from 'vs/editor/browser/services/codeEditorServiceImpl'; +import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; +import { ContextMenuService } from 'vs/platform/contextview/browser/contextMenuService'; +import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView'; +import { ContextViewService } from 'vs/platform/contextview/browser/contextViewService'; +import { IEventService } from 'vs/platform/event/common/event'; +import { EventService } from 'vs/platform/event/common/eventService'; +import { IExtensionService } from 'vs/platform/extensions/common/extensions'; +import { createDecorator, IInstantiationService, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation'; +import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService'; +import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; +import { ICommandService } from 'vs/platform/commands/common/commands'; +import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; +import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; +import { MarkerService } from 'vs/platform/markers/common/markerService'; +import { IMarkerService } from 'vs/platform/markers/common/markers'; +import { IMessageService } from 'vs/platform/message/common/message'; +import { IProgressService } from 'vs/platform/progress/common/progress'; +import { IStorageService, NullStorageService } from 'vs/platform/storage/common/storage'; +import { ITelemetryService, NullTelemetryService } from 'vs/platform/telemetry/common/telemetry'; +import { IWorkspaceContextService, WorkspaceContextService } from 'vs/platform/workspace/common/workspace'; +import { ICodeEditorService } from 'vs/editor/common/services/codeEditorService'; +import { IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService'; +import { EditorWorkerServiceImpl } from 'vs/editor/common/services/editorWorkerServiceImpl'; +import { IModeService } from 'vs/editor/common/services/modeService'; +import { MainThreadModeServiceImpl } from 'vs/editor/common/services/modeServiceImpl'; +import { IModelService } from 'vs/editor/common/services/modelService'; +import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl'; +import { CodeEditorServiceImpl } from 'vs/editor/browser/services/codeEditorServiceImpl'; import { SimpleConfigurationService, SimpleMessageService, SimpleExtensionService, StandaloneKeybindingService, StandaloneCommandService, SimpleProgressService } from 'vs/editor/browser/standalone/simpleServices'; -import {ContextKeyService} from 'vs/platform/contextkey/browser/contextKeyService'; -import {IMenuService} from 'vs/platform/actions/common/actions'; -import {MenuService} from 'vs/platform/actions/common/menuService'; +import { ContextKeyService } from 'vs/platform/contextkey/browser/contextKeyService'; +import { IMenuService } from 'vs/platform/actions/common/actions'; +import { MenuService } from 'vs/platform/actions/common/menuService'; export interface IEditorContextViewService extends IContextViewService { dispose(): void; - setContainer(domNode:HTMLElement): void; + setContainer(domNode: HTMLElement): void; } export interface IEditorOverrideServices { @@ -61,7 +61,7 @@ export module StaticServices { public get id() { return this._serviceId; } - constructor(serviceId:ServiceIdentifier, factory:(overrides: IEditorOverrideServices) => T) { + constructor(serviceId: ServiceIdentifier, factory: (overrides: IEditorOverrideServices) => T) { this._serviceId = serviceId; this._factory = factory; this._value = null; @@ -86,7 +86,7 @@ export module StaticServices { let _all: LazyStaticService[] = []; - function define(serviceId:ServiceIdentifier, factory:(overrides: IEditorOverrideServices) => T): LazyStaticService { + function define(serviceId: ServiceIdentifier, factory: (overrides: IEditorOverrideServices) => T): LazyStaticService { let r = new LazyStaticService(serviceId, factory); _all.push(r); return r; @@ -149,7 +149,7 @@ export class DynamicStandaloneServices extends Disposable { private _serviceCollection: ServiceCollection; private _instantiationService: IInstantiationService; - constructor(domElement:HTMLElement, overrides: IEditorOverrideServices) { + constructor(domElement: HTMLElement, overrides: IEditorOverrideServices) { super(); const [_serviceCollection, _instantiationService] = StaticServices.init(overrides); @@ -161,8 +161,8 @@ export class DynamicStandaloneServices extends Disposable { const messageService = this.get(IMessageService); const telemetryService = this.get(ITelemetryService); - let ensure = (serviceId:ServiceIdentifier, factory:() => T): T => { - let value:T = null; + let ensure = (serviceId: ServiceIdentifier, factory: () => T): T => { + let value: T = null; if (overrides) { value = overrides[serviceId.toString()]; } @@ -186,7 +186,7 @@ export class DynamicStandaloneServices extends Disposable { ensure(IMenuService, () => new MenuService(extensionService, commandService)); } - public get(serviceId:ServiceIdentifier): T { + public get(serviceId: ServiceIdentifier): T { let r = this._serviceCollection.get(serviceId); if (!r) { throw new Error('Missing service ' + serviceId); @@ -194,11 +194,11 @@ export class DynamicStandaloneServices extends Disposable { return r; } - public set(serviceId:ServiceIdentifier, instance: T): void { + public set(serviceId: ServiceIdentifier, instance: T): void { this._serviceCollection.set(serviceId, instance); } - public has(serviceId:ServiceIdentifier): boolean { + public has(serviceId: ServiceIdentifier): boolean { return this._serviceCollection.has(serviceId); } } diff --git a/src/vs/editor/browser/view/dynamicViewOverlay.ts b/src/vs/editor/browser/view/dynamicViewOverlay.ts index f9cd506723773..40c085f9e1ec1 100644 --- a/src/vs/editor/browser/view/dynamicViewOverlay.ts +++ b/src/vs/editor/browser/view/dynamicViewOverlay.ts @@ -5,15 +5,15 @@ 'use strict'; -import {ViewEventHandler} from 'vs/editor/common/viewModel/viewEventHandler'; -import {IRenderingContext} from 'vs/editor/common/view/renderingContext'; +import { ViewEventHandler } from 'vs/editor/common/viewModel/viewEventHandler'; +import { IRenderingContext } from 'vs/editor/common/view/renderingContext'; export abstract class DynamicViewOverlay extends ViewEventHandler { public abstract dispose(): void; - public abstract prepareRender(ctx:IRenderingContext): void; + public abstract prepareRender(ctx: IRenderingContext): void; - public abstract render(startLineNumber:number, lineNumber:number): string; + public abstract render(startLineNumber: number, lineNumber: number): string; } diff --git a/src/vs/editor/browser/view/viewController.ts b/src/vs/editor/browser/view/viewController.ts index d826e5e78454f..3a9b95b0a1af8 100644 --- a/src/vs/editor/browser/view/viewController.ts +++ b/src/vs/editor/browser/view/viewController.ts @@ -4,31 +4,31 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {EventEmitter} from 'vs/base/common/eventEmitter'; -import {IKeyboardEvent} from 'vs/base/browser/keyboardEvent'; -import {Position} from 'vs/editor/common/core/position'; +import { EventEmitter } from 'vs/base/common/eventEmitter'; +import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; +import { Position } from 'vs/editor/common/core/position'; import * as editorCommon from 'vs/editor/common/editorCommon'; -import {IEditorMouseEvent, IViewController, IMouseDispatchData} from 'vs/editor/browser/editorBrowser'; -import {ICommandService} from 'vs/platform/commands/common/commands'; -import {IViewModel} from 'vs/editor/common/viewModel/viewModel'; -import {Range} from 'vs/editor/common/core/range'; +import { IEditorMouseEvent, IViewController, IMouseDispatchData } from 'vs/editor/browser/editorBrowser'; +import { ICommandService } from 'vs/platform/commands/common/commands'; +import { IViewModel } from 'vs/editor/common/viewModel/viewModel'; +import { Range } from 'vs/editor/common/core/range'; export interface TriggerCursorHandler { - (source:string, handlerId:string, payload:any): void; + (source: string, handlerId: string, payload: any): void; } export class ViewController implements IViewController { - private viewModel:IViewModel; - private triggerCursorHandler:TriggerCursorHandler; - private outgoingEventBus:EventEmitter; - private commandService:ICommandService; + private viewModel: IViewModel; + private triggerCursorHandler: TriggerCursorHandler; + private outgoingEventBus: EventEmitter; + private commandService: ICommandService; constructor( - viewModel:IViewModel, - triggerCursorHandler:TriggerCursorHandler, - outgoingEventBus:EventEmitter, - commandService:ICommandService + viewModel: IViewModel, + triggerCursorHandler: TriggerCursorHandler, + outgoingEventBus: EventEmitter, + commandService: ICommandService ) { this.viewModel = viewModel; this.triggerCursorHandler = triggerCursorHandler; @@ -36,20 +36,20 @@ export class ViewController implements IViewController { this.commandService = commandService; } - public paste(source:string, text:string, pasteOnNewLine:boolean): void { + public paste(source: string, text: string, pasteOnNewLine: boolean): void { this.commandService.executeCommand(editorCommon.Handler.Paste, { text: text, pasteOnNewLine: pasteOnNewLine, }); } - public type(source:string, text:string): void { + public type(source: string, text: string): void { this.commandService.executeCommand(editorCommon.Handler.Type, { text: text }); } - public replacePreviousChar(source: string, text: string, replaceCharCnt:number): void { + public replacePreviousChar(source: string, text: string, replaceCharCnt: number): void { this.commandService.executeCommand(editorCommon.Handler.ReplacePreviousChar, { text: text, replaceCharCnt: replaceCharCnt @@ -64,11 +64,11 @@ export class ViewController implements IViewController { this.commandService.executeCommand(editorCommon.Handler.CompositionEnd, {}); } - public cut(source:string): void { + public cut(source: string): void { this.commandService.executeCommand(editorCommon.Handler.Cut, {}); } - private _validateViewColumn(viewPosition:Position): Position { + private _validateViewColumn(viewPosition: Position): Position { var minColumn = this.viewModel.getLineMinColumn(viewPosition.lineNumber); if (viewPosition.column < minColumn) { return new Position(viewPosition.lineNumber, minColumn); @@ -76,7 +76,7 @@ export class ViewController implements IViewController { return viewPosition; } - public dispatchMouse(data:IMouseDispatchData): void { + public dispatchMouse(data: IMouseDispatchData): void { if (data.startedOnLineNumbers) { // If the dragging started on the gutter, then have operations work on the entire line if (data.altKey) { @@ -142,7 +142,7 @@ export class ViewController implements IViewController { } } - public moveTo(source:string, viewPosition:Position): void { + public moveTo(source: string, viewPosition: Position): void { viewPosition = this._validateViewColumn(viewPosition); this.triggerCursorHandler(source, editorCommon.Handler.MoveTo, { position: this.convertViewToModelPosition(viewPosition), @@ -150,7 +150,7 @@ export class ViewController implements IViewController { }); } - private moveToSelect(source:string, viewPosition:Position): void { + private moveToSelect(source: string, viewPosition: Position): void { viewPosition = this._validateViewColumn(viewPosition); this.triggerCursorHandler(source, editorCommon.Handler.MoveToSelect, { position: this.convertViewToModelPosition(viewPosition), @@ -158,7 +158,7 @@ export class ViewController implements IViewController { }); } - private columnSelect(source:string, viewPosition:Position, mouseColumn:number): void { + private columnSelect(source: string, viewPosition: Position, mouseColumn: number): void { viewPosition = this._validateViewColumn(viewPosition); this.triggerCursorHandler(source, editorCommon.Handler.ColumnSelect, { position: this.convertViewToModelPosition(viewPosition), @@ -167,7 +167,7 @@ export class ViewController implements IViewController { }); } - private createCursor(source:string, viewPosition:Position, wholeLine:boolean): void { + private createCursor(source: string, viewPosition: Position, wholeLine: boolean): void { viewPosition = this._validateViewColumn(viewPosition); this.triggerCursorHandler(source, editorCommon.Handler.CreateCursor, { position: this.convertViewToModelPosition(viewPosition), @@ -176,7 +176,7 @@ export class ViewController implements IViewController { }); } - private lastCursorMoveToSelect(source:string, viewPosition:Position): void { + private lastCursorMoveToSelect(source: string, viewPosition: Position): void { viewPosition = this._validateViewColumn(viewPosition); this.triggerCursorHandler(source, editorCommon.Handler.LastCursorMoveToSelect, { position: this.convertViewToModelPosition(viewPosition), @@ -184,28 +184,28 @@ export class ViewController implements IViewController { }); } - private wordSelect(source:string, viewPosition:Position): void { + private wordSelect(source: string, viewPosition: Position): void { viewPosition = this._validateViewColumn(viewPosition); this.triggerCursorHandler(source, editorCommon.Handler.WordSelect, { position: this.convertViewToModelPosition(viewPosition) }); } - private wordSelectDrag(source:string, viewPosition:Position): void { + private wordSelectDrag(source: string, viewPosition: Position): void { viewPosition = this._validateViewColumn(viewPosition); this.triggerCursorHandler(source, editorCommon.Handler.WordSelectDrag, { position: this.convertViewToModelPosition(viewPosition) }); } - private lastCursorWordSelect(source:string, viewPosition:Position): void { + private lastCursorWordSelect(source: string, viewPosition: Position): void { viewPosition = this._validateViewColumn(viewPosition); this.triggerCursorHandler(source, editorCommon.Handler.LastCursorWordSelect, { position: this.convertViewToModelPosition(viewPosition) }); } - private lineSelect(source:string, viewPosition:Position): void { + private lineSelect(source: string, viewPosition: Position): void { viewPosition = this._validateViewColumn(viewPosition); this.triggerCursorHandler(source, editorCommon.Handler.LineSelect, { position: this.convertViewToModelPosition(viewPosition), @@ -213,7 +213,7 @@ export class ViewController implements IViewController { }); } - private lineSelectDrag(source:string, viewPosition:Position): void { + private lineSelectDrag(source: string, viewPosition: Position): void { viewPosition = this._validateViewColumn(viewPosition); this.triggerCursorHandler(source, editorCommon.Handler.LineSelectDrag, { position: this.convertViewToModelPosition(viewPosition), @@ -221,7 +221,7 @@ export class ViewController implements IViewController { }); } - private lastCursorLineSelect(source:string, viewPosition:Position): void { + private lastCursorLineSelect(source: string, viewPosition: Position): void { viewPosition = this._validateViewColumn(viewPosition); this.triggerCursorHandler(source, editorCommon.Handler.LastCursorLineSelect, { position: this.convertViewToModelPosition(viewPosition), @@ -229,7 +229,7 @@ export class ViewController implements IViewController { }); } - private lastCursorLineSelectDrag(source:string, viewPosition:Position): void { + private lastCursorLineSelectDrag(source: string, viewPosition: Position): void { viewPosition = this._validateViewColumn(viewPosition); this.triggerCursorHandler(source, editorCommon.Handler.LastCursorLineSelectDrag, { position: this.convertViewToModelPosition(viewPosition), @@ -237,21 +237,21 @@ export class ViewController implements IViewController { }); } - private selectAll(source:string): void { + private selectAll(source: string): void { this.triggerCursorHandler(source, editorCommon.Handler.SelectAll, null); } // ---------------------- - private convertViewToModelPosition(viewPosition:Position): Position { + private convertViewToModelPosition(viewPosition: Position): Position { return this.viewModel.convertViewPositionToModelPosition(viewPosition.lineNumber, viewPosition.column); } - private convertViewToModelRange(viewRange:editorCommon.IRange): Range { + private convertViewToModelRange(viewRange: editorCommon.IRange): Range { return this.viewModel.convertViewRangeToModelRange(viewRange); } - private convertViewToModelMouseEvent(e:IEditorMouseEvent): void { + private convertViewToModelMouseEvent(e: IEditorMouseEvent): void { if (e.target) { if (e.target.position) { e.target.position = this.convertViewToModelPosition(e.target.position); @@ -262,35 +262,35 @@ export class ViewController implements IViewController { } } - public emitKeyDown(e:IKeyboardEvent): void { + public emitKeyDown(e: IKeyboardEvent): void { this.outgoingEventBus.emit(editorCommon.EventType.KeyDown, e); } - public emitKeyUp(e:IKeyboardEvent): void { + public emitKeyUp(e: IKeyboardEvent): void { this.outgoingEventBus.emit(editorCommon.EventType.KeyUp, e); } - public emitContextMenu(e:IEditorMouseEvent): void { + public emitContextMenu(e: IEditorMouseEvent): void { this.convertViewToModelMouseEvent(e); this.outgoingEventBus.emit(editorCommon.EventType.ContextMenu, e); } - public emitMouseMove(e:IEditorMouseEvent): void { + public emitMouseMove(e: IEditorMouseEvent): void { this.convertViewToModelMouseEvent(e); this.outgoingEventBus.emit(editorCommon.EventType.MouseMove, e); } - public emitMouseLeave(e:IEditorMouseEvent): void { + public emitMouseLeave(e: IEditorMouseEvent): void { this.convertViewToModelMouseEvent(e); this.outgoingEventBus.emit(editorCommon.EventType.MouseLeave, e); } - public emitMouseUp(e:IEditorMouseEvent): void { + public emitMouseUp(e: IEditorMouseEvent): void { this.convertViewToModelMouseEvent(e); this.outgoingEventBus.emit(editorCommon.EventType.MouseUp, e); } - public emitMouseDown(e:IEditorMouseEvent): void { + public emitMouseDown(e: IEditorMouseEvent): void { this.convertViewToModelMouseEvent(e); this.outgoingEventBus.emit(editorCommon.EventType.MouseDown, e); } diff --git a/src/vs/editor/browser/view/viewEventDispatcher.ts b/src/vs/editor/browser/view/viewEventDispatcher.ts index bf20e901f1d3f..702d3fd53149b 100644 --- a/src/vs/editor/browser/view/viewEventDispatcher.ts +++ b/src/vs/editor/browser/view/viewEventDispatcher.ts @@ -4,17 +4,17 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {EmitterEvent} from 'vs/base/common/eventEmitter'; -import {IViewEventBus, IViewEventHandler} from 'vs/editor/common/view/viewContext'; +import { EmitterEvent } from 'vs/base/common/eventEmitter'; +import { IViewEventBus, IViewEventHandler } from 'vs/editor/common/view/viewContext'; export class ViewEventDispatcher implements IViewEventBus { - private _eventHandlerGateKeeper:(callback:()=>void)=>void; - private _eventHandlers:IViewEventHandler[]; - private _eventQueue:EmitterEvent[]; - private _isConsumingQueue:boolean; + private _eventHandlerGateKeeper: (callback: () => void) => void; + private _eventHandlers: IViewEventHandler[]; + private _eventQueue: EmitterEvent[]; + private _isConsumingQueue: boolean; - constructor(eventHandlerGateKeeper:(callback:()=>void)=>void) { + constructor(eventHandlerGateKeeper: (callback: () => void) => void) { this._eventHandlerGateKeeper = eventHandlerGateKeeper; this._eventHandlers = []; this._eventQueue = null; @@ -30,7 +30,7 @@ export class ViewEventDispatcher implements IViewEventBus { this._eventHandlers.push(eventHandler); } - public removeEventHandler(eventHandler:IViewEventHandler): void { + public removeEventHandler(eventHandler: IViewEventHandler): void { for (let i = 0; i < this._eventHandlers.length; i++) { if (this._eventHandlers[i] === eventHandler) { this._eventHandlers.splice(i, 1); @@ -39,7 +39,7 @@ export class ViewEventDispatcher implements IViewEventBus { } } - public emit(eventType:string, data?:any): void { + public emit(eventType: string, data?: any): void { let event = new EmitterEvent(eventType, data); if (this._eventQueue) { @@ -53,7 +53,7 @@ export class ViewEventDispatcher implements IViewEventBus { } } - public emitMany(events:EmitterEvent[]): void { + public emitMany(events: EmitterEvent[]): void { if (this._eventQueue) { this._eventQueue = this._eventQueue.concat(events); } else { diff --git a/src/vs/editor/browser/view/viewImpl.ts b/src/vs/editor/browser/view/viewImpl.ts index 819f85f0b9e7c..906f01534dddb 100644 --- a/src/vs/editor/browser/view/viewImpl.ts +++ b/src/vs/editor/browser/view/viewImpl.ts @@ -4,54 +4,54 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {onUnexpectedError} from 'vs/base/common/errors'; -import {EventEmitter, EmitterEvent, IEventEmitter} from 'vs/base/common/eventEmitter'; -import {IDisposable, dispose} from 'vs/base/common/lifecycle'; +import { onUnexpectedError } from 'vs/base/common/errors'; +import { EventEmitter, EmitterEvent, IEventEmitter } from 'vs/base/common/eventEmitter'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import * as timer from 'vs/base/common/timer'; import * as browser from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; -import {StyleMutator} from 'vs/base/browser/styleMutator'; -import {ICommandService} from 'vs/platform/commands/common/commands'; -import {Range} from 'vs/editor/common/core/range'; +import { StyleMutator } from 'vs/base/browser/styleMutator'; +import { ICommandService } from 'vs/platform/commands/common/commands'; +import { Range } from 'vs/editor/common/core/range'; import * as editorCommon from 'vs/editor/common/editorCommon'; -import {ViewEventHandler} from 'vs/editor/common/viewModel/viewEventHandler'; -import {Configuration} from 'vs/editor/browser/config/configuration'; -import {KeyboardHandler, IKeyboardHandlerHelper} from 'vs/editor/browser/controller/keyboardHandler'; -import {PointerHandler} from 'vs/editor/browser/controller/pointerHandler'; +import { ViewEventHandler } from 'vs/editor/common/viewModel/viewEventHandler'; +import { Configuration } from 'vs/editor/browser/config/configuration'; +import { KeyboardHandler, IKeyboardHandlerHelper } from 'vs/editor/browser/controller/keyboardHandler'; +import { PointerHandler } from 'vs/editor/browser/controller/pointerHandler'; import * as editorBrowser from 'vs/editor/browser/editorBrowser'; -import {ViewController, TriggerCursorHandler} from 'vs/editor/browser/view/viewController'; -import {ViewEventDispatcher} from 'vs/editor/browser/view/viewEventDispatcher'; -import {ContentViewOverlays, MarginViewOverlays} from 'vs/editor/browser/view/viewOverlays'; -import {LayoutProvider} from 'vs/editor/browser/viewLayout/layoutProvider'; -import {ViewContentWidgets} from 'vs/editor/browser/viewParts/contentWidgets/contentWidgets'; -import {CurrentLineHighlightOverlay} from 'vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight'; -import {DecorationsOverlay} from 'vs/editor/browser/viewParts/decorations/decorations'; -import {GlyphMarginOverlay} from 'vs/editor/browser/viewParts/glyphMargin/glyphMargin'; -import {LineNumbersOverlay} from 'vs/editor/browser/viewParts/lineNumbers/lineNumbers'; -import {IndentGuidesOverlay} from 'vs/editor/browser/viewParts/indentGuides/indentGuides'; -import {ViewLines} from 'vs/editor/browser/viewParts/lines/viewLines'; -import {LinesDecorationsOverlay} from 'vs/editor/browser/viewParts/linesDecorations/linesDecorations'; -import {ViewOverlayWidgets} from 'vs/editor/browser/viewParts/overlayWidgets/overlayWidgets'; -import {DecorationsOverviewRuler} from 'vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler'; -import {OverviewRuler} from 'vs/editor/browser/viewParts/overviewRuler/overviewRuler'; -import {Rulers} from 'vs/editor/browser/viewParts/rulers/rulers'; -import {ScrollDecorationViewPart} from 'vs/editor/browser/viewParts/scrollDecoration/scrollDecoration'; -import {SelectionsOverlay} from 'vs/editor/browser/viewParts/selections/selections'; -import {ViewCursors} from 'vs/editor/browser/viewParts/viewCursors/viewCursors'; -import {ViewZones} from 'vs/editor/browser/viewParts/viewZones/viewZones'; -import {ViewPart} from 'vs/editor/browser/view/viewPart'; -import {ViewContext, IViewEventHandler} from 'vs/editor/common/view/viewContext'; -import {IViewModel} from 'vs/editor/common/viewModel/viewModel'; -import {ViewLinesViewportData} from 'vs/editor/common/viewLayout/viewLinesViewportData'; -import {IRenderingContext} from 'vs/editor/common/view/renderingContext'; -import {IPointerHandlerHelper} from 'vs/editor/browser/controller/mouseHandler'; +import { ViewController, TriggerCursorHandler } from 'vs/editor/browser/view/viewController'; +import { ViewEventDispatcher } from 'vs/editor/browser/view/viewEventDispatcher'; +import { ContentViewOverlays, MarginViewOverlays } from 'vs/editor/browser/view/viewOverlays'; +import { LayoutProvider } from 'vs/editor/browser/viewLayout/layoutProvider'; +import { ViewContentWidgets } from 'vs/editor/browser/viewParts/contentWidgets/contentWidgets'; +import { CurrentLineHighlightOverlay } from 'vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight'; +import { DecorationsOverlay } from 'vs/editor/browser/viewParts/decorations/decorations'; +import { GlyphMarginOverlay } from 'vs/editor/browser/viewParts/glyphMargin/glyphMargin'; +import { LineNumbersOverlay } from 'vs/editor/browser/viewParts/lineNumbers/lineNumbers'; +import { IndentGuidesOverlay } from 'vs/editor/browser/viewParts/indentGuides/indentGuides'; +import { ViewLines } from 'vs/editor/browser/viewParts/lines/viewLines'; +import { LinesDecorationsOverlay } from 'vs/editor/browser/viewParts/linesDecorations/linesDecorations'; +import { ViewOverlayWidgets } from 'vs/editor/browser/viewParts/overlayWidgets/overlayWidgets'; +import { DecorationsOverviewRuler } from 'vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler'; +import { OverviewRuler } from 'vs/editor/browser/viewParts/overviewRuler/overviewRuler'; +import { Rulers } from 'vs/editor/browser/viewParts/rulers/rulers'; +import { ScrollDecorationViewPart } from 'vs/editor/browser/viewParts/scrollDecoration/scrollDecoration'; +import { SelectionsOverlay } from 'vs/editor/browser/viewParts/selections/selections'; +import { ViewCursors } from 'vs/editor/browser/viewParts/viewCursors/viewCursors'; +import { ViewZones } from 'vs/editor/browser/viewParts/viewZones/viewZones'; +import { ViewPart } from 'vs/editor/browser/view/viewPart'; +import { ViewContext, IViewEventHandler } from 'vs/editor/common/view/viewContext'; +import { IViewModel } from 'vs/editor/common/viewModel/viewModel'; +import { ViewLinesViewportData } from 'vs/editor/common/viewLayout/viewLinesViewportData'; +import { IRenderingContext } from 'vs/editor/common/view/renderingContext'; +import { IPointerHandlerHelper } from 'vs/editor/browser/controller/mouseHandler'; export class View extends ViewEventHandler implements editorBrowser.IView, IDisposable { - private eventDispatcher:ViewEventDispatcher; + private eventDispatcher: ViewEventDispatcher; - private listenersToRemove:IDisposable[]; - private listenersToDispose:IDisposable[]; + private listenersToRemove: IDisposable[]; + private listenersToDispose: IDisposable[]; private layoutProvider: LayoutProvider; public _context: ViewContext; @@ -80,18 +80,18 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp private overflowGuardContainer: HTMLElement; // Actual mutable state - private hasFocus:boolean; + private hasFocus: boolean; private _isDisposed: boolean; - private handleAccumulatedModelEventsTimeout:number; + private handleAccumulatedModelEventsTimeout: number; private accumulatedModelEvents: EmitterEvent[]; private _renderAnimationFrame: IDisposable; constructor( commandService: ICommandService, - configuration:Configuration, - model:IViewModel, - private triggerCursorHandler:TriggerCursorHandler + configuration: Configuration, + model: IViewModel, + private triggerCursorHandler: TriggerCursorHandler ) { super(); this._isDisposed = false; @@ -104,7 +104,7 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp this.listenersToDispose = []; // The event dispatcher will always go through _renderOnce before dispatching any events - this.eventDispatcher = new ViewEventDispatcher((callback:()=>void) => this._renderOnce(callback)); + this.eventDispatcher = new ViewEventDispatcher((callback: () => void) => this._renderOnce(callback)); // These two dom nodes must be constructed up front, since references are needed in the layout provider (scrolling & co.) this.linesContent = document.createElement('div'); @@ -124,9 +124,9 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp // The view context is passed on to most classes (basically to reduce param. counts in ctors) this._context = new ViewContext( - configuration, model, this.eventDispatcher, - (eventHandler:IViewEventHandler) => this.eventDispatcher.addEventHandler(eventHandler), - (eventHandler:IViewEventHandler) => this.eventDispatcher.removeEventHandler(eventHandler) + configuration, model, this.eventDispatcher, + (eventHandler: IViewEventHandler) => this.eventDispatcher.addEventHandler(eventHandler), + (eventHandler: IViewEventHandler) => this.eventDispatcher.removeEventHandler(eventHandler) ); this.createTextArea(); @@ -147,7 +147,7 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp // This delayed processing of incoming model events acts as a guard against undesired/unexpected recursion. this.handleAccumulatedModelEventsTimeout = -1; this.accumulatedModelEvents = []; - this.listenersToRemove.push(model.addBulkListener2((events:EmitterEvent[]) => { + this.listenersToRemove.push(model.addBulkListener2((events: EmitterEvent[]) => { this.accumulatedModelEvents = this.accumulatedModelEvents.concat(events); if (this.handleAccumulatedModelEventsTimeout === -1) { this.handleAccumulatedModelEventsTimeout = setTimeout(() => { @@ -218,8 +218,8 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp // Decorations overview ruler var decorationsOverviewRuler = new DecorationsOverviewRuler( - this._context, this.layoutProvider.getScrollHeight(), - (lineNumber:number) => this.layoutProvider.getVerticalOffsetForLineNumber(lineNumber) + this._context, this.layoutProvider.getScrollHeight(), + (lineNumber: number) => this.layoutProvider.getVerticalOffsetForLineNumber(lineNumber) ); this.viewParts.push(decorationsOverviewRuler); @@ -315,7 +315,7 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp return this.layoutProvider.getScrollTop(); }, - setScrollPosition: (position:editorCommon.INewScrollPosition) => { + setScrollPosition: (position: editorCommon.INewScrollPosition) => { if (this._isDisposed) { throw new Error('ViewImpl.pointerHandler.setScrollPosition: View is disposed'); } @@ -416,7 +416,7 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp }; } - public setAriaActiveDescendant(id:string): void { + public setAriaActiveDescendant(id: string): void { if (id) { this.textArea.setAttribute('role', 'combobox'); if (this.textArea.getAttribute('aria-activedescendant') !== id) { @@ -432,7 +432,7 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp // --- begin event handlers - public onLayoutChanged(layoutInfo:editorCommon.EditorLayoutInfo): boolean { + public onLayoutChanged(layoutInfo: editorCommon.EditorLayoutInfo): boolean { if (browser.isChrome) { /* tslint:disable:no-unused-variable */ // Access overflowGuardContainer.clientWidth to prevent relayouting bug in Chrome @@ -465,11 +465,11 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp } return false; } - public onScrollChanged(e:editorCommon.IScrollEvent): boolean { + public onScrollChanged(e: editorCommon.IScrollEvent): boolean { this.outgoingEventBus.emit('scroll', e); return false; } - public onViewFocusChanged(isFocused:boolean): boolean { + public onViewFocusChanged(isFocused: boolean): boolean { dom.toggleClass(this.domNode, 'focused', isFocused); if (isFocused) { this.outgoingEventBus.emit(editorCommon.EventType.ViewFocusGained, {}); @@ -526,7 +526,7 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp // --- begin Code Editor APIs - private codeEditorHelper:editorBrowser.ICodeEditorHelper; + private codeEditorHelper: editorBrowser.ICodeEditorHelper; public getCodeEditorHelper(): editorBrowser.ICodeEditorHelper { if (!this.codeEditorHelper) { this.codeEditorHelper = { @@ -556,14 +556,14 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp return this.layoutProvider.getScrollTop(); }, - setScrollPosition: (position:editorCommon.INewScrollPosition) => { + setScrollPosition: (position: editorCommon.INewScrollPosition) => { if (this._isDisposed) { throw new Error('ViewImpl.codeEditorHelper.setScrollPosition: View is disposed'); } this.layoutProvider.setScrollPosition(position); }, - getVerticalOffsetForPosition: (modelLineNumber:number, modelColumn:number) => { + getVerticalOffsetForPosition: (modelLineNumber: number, modelColumn: number) => { if (this._isDisposed) { throw new Error('ViewImpl.codeEditorHelper.getVerticalOffsetForPosition: View is disposed'); } @@ -619,9 +619,9 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp return this._context.model.convertViewRangeToModelRange(completelyVisibleLinesRange); } -// public getLineInfoProvider():view.ILineInfoProvider { -// return this.viewLines; -// } + // public getLineInfoProvider():view.ILineInfoProvider { + // return this.viewLines; + // } public getInternalEventBus(): IEventEmitter { if (this._isDisposed) { @@ -667,8 +667,8 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp throw new Error('ViewImpl.createOverviewRuler: View is disposed'); } return new OverviewRuler( - this._context, cssClassName, this.layoutProvider.getScrollHeight(), minimumHeight, maximumHeight, - (lineNumber:number) => this.layoutProvider.getVerticalOffsetForLineNumber(lineNumber) + this._context, cssClassName, this.layoutProvider.getScrollHeight(), minimumHeight, maximumHeight, + (lineNumber: number) => this.layoutProvider.getVerticalOffsetForLineNumber(lineNumber) ); } @@ -680,12 +680,12 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp this._renderOnce(() => { // Handle events to avoid "adjusting" newly inserted view zones this._flushAnyAccumulatedEvents(); - var changeAccessor:editorBrowser.IViewZoneChangeAccessor = { - addZone: (zone:editorBrowser.IViewZone): number => { + var changeAccessor: editorBrowser.IViewZoneChangeAccessor = { + addZone: (zone: editorBrowser.IViewZone): number => { zonesHaveChanged = true; return this.viewZones.addZone(zone); }, - removeZone: (id:number): void => { + removeZone: (id: number): void => { zonesHaveChanged = this.viewZones.removeZone(id) || zonesHaveChanged; }, layoutZone: (id: number): void => { @@ -708,7 +708,7 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp return zonesHaveChanged; } - public getWhitespaces(): editorCommon.IEditorWhitespace[]{ + public getWhitespaces(): editorCommon.IEditorWhitespace[] { if (this._isDisposed) { throw new Error('ViewImpl.getWhitespaces: View is disposed'); } @@ -777,7 +777,7 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp }); } - public render(now:boolean, everything:boolean): void { + public render(now: boolean, everything: boolean): void { if (this._isDisposed) { throw new Error('ViewImpl.render: View is disposed'); } @@ -828,13 +828,13 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp safeInvokeNoArg(() => this._actualRender()); } - private createRenderingContext(linesViewportData:ViewLinesViewportData): IRenderingContext { + private createRenderingContext(linesViewportData: ViewLinesViewportData): IRenderingContext { var vInfo = this.layoutProvider.getCurrentViewport(); var deltaTop = linesViewportData.visibleRangesDeltaTop; - var r:IRenderingContext = { + var r: IRenderingContext = { linesViewportData: linesViewportData, scrollWidth: this.layoutProvider.getScrollWidth(), scrollHeight: this.layoutProvider.getScrollHeight(), @@ -847,11 +847,11 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp viewportLeft: vInfo.left, viewportTop: vInfo.top, - getScrolledTopFromAbsoluteTop: (absoluteTop:number) => { + getScrolledTopFromAbsoluteTop: (absoluteTop: number) => { return this.layoutProvider.getScrolledTopFromAbsoluteTop(absoluteTop); }, - getViewportVerticalOffsetForLineNumber: (lineNumber:number) => { + getViewportVerticalOffsetForLineNumber: (lineNumber: number) => { var verticalOffset = this.layoutProvider.getVerticalOffsetForLineNumber(lineNumber); var scrolledTop = this.layoutProvider.getScrolledTopFromAbsoluteTop(verticalOffset); return scrolledTop; @@ -859,11 +859,11 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp getDecorationsInViewport: () => linesViewportData.getDecorationsInViewport(), - linesVisibleRangesForRange: (range:editorCommon.IRange, includeNewLines:boolean) => { + linesVisibleRangesForRange: (range: editorCommon.IRange, includeNewLines: boolean) => { return this.viewLines.linesVisibleRangesForRange(range, includeNewLines); }, - visibleRangeForPosition: (position:editorCommon.IPosition) => { + visibleRangeForPosition: (position: editorCommon.IPosition) => { var visibleRanges = this.viewLines.visibleRangesForRange2(new Range(position.lineNumber, position.column, position.lineNumber, position.column), deltaTop); if (!visibleRanges) { return null; @@ -871,7 +871,7 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp return visibleRanges[0]; }, - lineIsVisible: (lineNumber:number) => { + lineIsVisible: (lineNumber: number) => { return linesViewportData.visibleRange.startLineNumber <= lineNumber && lineNumber <= linesViewportData.visibleRange.endLineNumber; } }; @@ -879,7 +879,7 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp } private _getViewPartsToRender(): ViewPart[] { - let result:ViewPart[] = []; + let result: ViewPart[] = []; for (let i = 0, len = this.viewParts.length; i < len; i++) { let viewPart = this.viewParts[i]; if (viewPart.shouldRender()) { @@ -938,7 +938,7 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp t.stop(); } - private _setHasFocus(newHasFocus:boolean): void { + private _setHasFocus(newHasFocus: boolean): void { if (this.hasFocus !== newHasFocus) { this.hasFocus = newHasFocus; this._context.privateViewEventBus.emit(editorCommon.EventType.ViewFocusChanged, this.hasFocus); @@ -946,18 +946,18 @@ export class View extends ViewEventHandler implements editorBrowser.IView, IDisp } } -function safeInvokeNoArg(func:Function): any { +function safeInvokeNoArg(func: Function): any { try { return func(); - } catch(e) { + } catch (e) { onUnexpectedError(e); } } -function safeInvoke1Arg(func:Function, arg1:any): any { +function safeInvoke1Arg(func: Function, arg1: any): any { try { return func(arg1); - } catch(e) { + } catch (e) { onUnexpectedError(e); } } diff --git a/src/vs/editor/browser/view/viewLayer.ts b/src/vs/editor/browser/view/viewLayer.ts index fd13c4ed92841..d46bc5a39896f 100644 --- a/src/vs/editor/browser/view/viewLayer.ts +++ b/src/vs/editor/browser/view/viewLayer.ts @@ -5,11 +5,11 @@ 'use strict'; import * as editorCommon from 'vs/editor/common/editorCommon'; -import {ViewPart} from 'vs/editor/browser/view/viewPart'; -import {FastDomNode, createFastDomNode} from 'vs/base/browser/styleMutator'; -import {ViewContext} from 'vs/editor/common/view/viewContext'; -import {ViewLinesViewportData} from 'vs/editor/common/viewLayout/viewLinesViewportData'; -import {InlineDecoration} from 'vs/editor/common/viewModel/viewModel'; +import { ViewPart } from 'vs/editor/browser/view/viewPart'; +import { FastDomNode, createFastDomNode } from 'vs/base/browser/styleMutator'; +import { ViewContext } from 'vs/editor/common/view/viewContext'; +import { ViewLinesViewportData } from 'vs/editor/common/viewLayout/viewLinesViewportData'; +import { InlineDecoration } from 'vs/editor/common/viewModel/viewModel'; export interface IVisibleLineData { getDomNode(): HTMLElement; @@ -20,13 +20,13 @@ export interface IVisibleLineData { onLinesDeletedAbove(): void; onLineChangedAbove(): void; onTokensChanged(): void; - onConfigurationChanged(e:editorCommon.IConfigurationChangedEvent): void; + onConfigurationChanged(e: editorCommon.IConfigurationChangedEvent): void; - getLineOuterHTML(out:string[], lineNumber: number, deltaTop: number): void; + getLineOuterHTML(out: string[], lineNumber: number, deltaTop: number): void; getLineInnerHTML(lineNumber: number): string; - shouldUpdateHTML(startLineNumber:number, lineNumber:number, inlineDecorations:InlineDecoration[]): boolean; - layoutLine(lineNumber: number, deltaTop:number): void; + shouldUpdateHTML(startLineNumber: number, lineNumber: number, inlineDecorations: InlineDecoration[]): boolean; + layoutLine(lineNumber: number, deltaTop: number): void; } interface IRendererContext { @@ -34,7 +34,7 @@ interface IRendererContext { rendLineNumberStart: number; lines: T[]; linesLength: number; - getInlineDecorationsForLineInViewport(lineNumber:number): InlineDecoration[]; + getInlineDecorationsForLineInViewport(lineNumber: number): InlineDecoration[]; viewportTop: number; viewportHeight: number; scrollDomNode: HTMLElement; @@ -51,21 +51,21 @@ export interface ILine { export class RenderedLinesCollection { private _lines: T[]; - private _rendLineNumberStart:number; - private _createLine:()=>T; + private _rendLineNumberStart: number; + private _createLine: () => T; - constructor(createLine:()=>T) { + constructor(createLine: () => T) { this._lines = []; this._rendLineNumberStart = 1; this._createLine = createLine; } - _set(rendLineNumberStart:number, lines:T[]): void { + _set(rendLineNumberStart: number, lines: T[]): void { this._lines = lines; this._rendLineNumberStart = rendLineNumberStart; } - _get(): { rendLineNumberStart:number; lines:T[]; } { + _get(): { rendLineNumberStart: number; lines: T[]; } { return { rendLineNumberStart: this._rendLineNumberStart, lines: this._lines @@ -90,7 +90,7 @@ export class RenderedLinesCollection { return this._lines.length; } - public getLine(lineNumber:number): T { + public getLine(lineNumber: number): T { let lineIndex = lineNumber - this._rendLineNumberStart; if (lineIndex < 0 || lineIndex >= this._lines.length) { throw new Error('Illegal value for lineNumber: ' + lineNumber); @@ -101,7 +101,7 @@ export class RenderedLinesCollection { /** * @returns Lines that were removed from this collection */ - public onModelLinesDeleted(deleteFromLineNumber:number, deleteToLineNumber:number): T[] { + public onModelLinesDeleted(deleteFromLineNumber: number, deleteToLineNumber: number): T[] { if (this.getCount() === 0) { // no lines return null; @@ -150,7 +150,7 @@ export class RenderedLinesCollection { return deleted; } - public onModelLineChanged(changedLineNumber:number): boolean { + public onModelLineChanged(changedLineNumber: number): boolean { if (this.getCount() === 0) { // no lines return false; @@ -177,7 +177,7 @@ export class RenderedLinesCollection { return notifiedSomeone; } - public onModelLinesInserted(insertFromLineNumber:number, insertToLineNumber:number): T[] { + public onModelLinesInserted(insertFromLineNumber: number, insertToLineNumber: number): T[] { if (this.getCount() === 0) { // no lines return null; @@ -228,7 +228,7 @@ export class RenderedLinesCollection { return deletedLines; } - public onModelTokensChanged(changedFromLineNumber:number, changedToLineNumber:number): boolean { + public onModelTokensChanged(changedFromLineNumber: number, changedToLineNumber: number): boolean { if (this.getCount() === 0) { // no lines return false; @@ -260,7 +260,7 @@ export abstract class ViewLayer extends ViewPart { private _scrollDomNode: HTMLElement; private _scrollDomNodeIsAbove: boolean; - constructor(context:ViewContext) { + constructor(context: ViewContext) { super(context); this.domNode = this._createDomNode(); @@ -287,7 +287,7 @@ export abstract class ViewLayer extends ViewPart { // ---- begin view event handlers - public onConfigurationChanged(e:editorCommon.IConfigurationChangedEvent): boolean { + public onConfigurationChanged(e: editorCommon.IConfigurationChangedEvent): boolean { let startLineNumber = this._linesCollection.getStartLineNumber(); let endLineNumber = this._linesCollection.getEndLineNumber(); for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { @@ -297,11 +297,11 @@ export abstract class ViewLayer extends ViewPart { return true; } - public onLayoutChanged(layoutInfo:editorCommon.EditorLayoutInfo): boolean { + public onLayoutChanged(layoutInfo: editorCommon.EditorLayoutInfo): boolean { return true; } - public onScrollChanged(e:editorCommon.IScrollEvent): boolean { + public onScrollChanged(e: editorCommon.IScrollEvent): boolean { return e.scrollTopChanged; } @@ -316,7 +316,7 @@ export abstract class ViewLayer extends ViewPart { return true; } - public onModelLinesDeleted(e:editorCommon.IViewLinesDeletedEvent): boolean { + public onModelLinesDeleted(e: editorCommon.IViewLinesDeletedEvent): boolean { let deleted = this._linesCollection.onModelLinesDeleted(e.fromLineNumber, e.toLineNumber); if (deleted) { // Remove from DOM @@ -331,11 +331,11 @@ export abstract class ViewLayer extends ViewPart { return true; } - public onModelLineChanged(e:editorCommon.IViewLineChangedEvent): boolean { + public onModelLineChanged(e: editorCommon.IViewLineChangedEvent): boolean { return this._linesCollection.onModelLineChanged(e.lineNumber); } - public onModelLinesInserted(e:editorCommon.IViewLinesInsertedEvent): boolean { + public onModelLinesInserted(e: editorCommon.IViewLinesInsertedEvent): boolean { let deleted = this._linesCollection.onModelLinesInserted(e.fromLineNumber, e.toLineNumber); if (deleted) { // Remove from DOM @@ -350,13 +350,13 @@ export abstract class ViewLayer extends ViewPart { return true; } - public onModelTokensChanged(e:editorCommon.IViewTokensChangedEvent): boolean { + public onModelTokensChanged(e: editorCommon.IViewTokensChangedEvent): boolean { return this._linesCollection.onModelTokensChanged(e.fromLineNumber, e.toLineNumber); } // ---- end view event handlers - public _renderLines(linesViewportData:ViewLinesViewportData): void { + public _renderLines(linesViewportData: ViewLinesViewportData): void { let inp = this._linesCollection._get(); @@ -365,7 +365,7 @@ export abstract class ViewLayer extends ViewPart { rendLineNumberStart: inp.rendLineNumberStart, lines: inp.lines, linesLength: inp.lines.length, - getInlineDecorationsForLineInViewport: (lineNumber:number) => linesViewportData.getInlineDecorationsForLineInViewport(lineNumber), + getInlineDecorationsForLineInViewport: (lineNumber: number) => linesViewportData.getInlineDecorationsForLineInViewport(lineNumber), viewportTop: linesViewportData.viewportTop, viewportHeight: linesViewportData.viewportHeight, scrollDomNode: this._scrollDomNode, @@ -402,11 +402,11 @@ class ViewLayerRenderer { this._extraDomNodeHTML = extraDomNodeHTML; } - public renderWithManyUpdates(ctx: IRendererContext, startLineNumber: number, stopLineNumber: number, deltaTop:number[]): IRendererContext { + public renderWithManyUpdates(ctx: IRendererContext, startLineNumber: number, stopLineNumber: number, deltaTop: number[]): IRendererContext { return this._render(ctx, startLineNumber, stopLineNumber, deltaTop); } - private _render(inContext: IRendererContext, startLineNumber: number, stopLineNumber: number, deltaTop:number[]): IRendererContext { + private _render(inContext: IRendererContext, startLineNumber: number, stopLineNumber: number, deltaTop: number[]): IRendererContext { var ctx: IRendererContext = { domNode: inContext.domNode, @@ -516,7 +516,7 @@ class ViewLayerRenderer { return ctx; } - private _renderUntouchedLines(ctx: IRendererContext, startIndex: number, endIndex: number, deltaTop:number[], deltaLN:number): void { + private _renderUntouchedLines(ctx: IRendererContext, startIndex: number, endIndex: number, deltaTop: number[], deltaLN: number): void { var i: number, lineNumber: number; @@ -529,9 +529,9 @@ class ViewLayerRenderer { } } - private _insertLinesBefore(ctx: IRendererContext, fromLineNumber: number, toLineNumber: number, deltaTop:number[], deltaLN:number): void { - var newLines:T[] = [], - line:T, + private _insertLinesBefore(ctx: IRendererContext, fromLineNumber: number, toLineNumber: number, deltaTop: number[], deltaLN: number): void { + var newLines: T[] = [], + line: T, lineNumber: number; for (lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) { @@ -587,9 +587,9 @@ class ViewLayerRenderer { ctx.lines.splice(0, removeCount); } - private _insertLinesAfter(ctx: IRendererContext, fromLineNumber: number, toLineNumber: number, deltaTop:number[], deltaLN:number): void { - var newLines:T[] = [], - line:T, + private _insertLinesAfter(ctx: IRendererContext, fromLineNumber: number, toLineNumber: number, deltaTop: number[], deltaLN: number): void { + var newLines: T[] = [], + line: T, lineNumber: number; for (lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) { @@ -621,7 +621,7 @@ class ViewLayerRenderer { return result; } - private _finishRenderingNewLines(ctx: IRendererContext, domNodeIsEmpty:boolean, newLinesHTML: string[], wasNew: boolean[]): void { + private _finishRenderingNewLines(ctx: IRendererContext, domNodeIsEmpty: boolean, newLinesHTML: string[], wasNew: boolean[]): void { var lastChild = ctx.domNode.lastChild; if (domNodeIsEmpty || !lastChild) { ctx.domNode.innerHTML = this._extraDomNodeHTML() + newLinesHTML.join(''); @@ -644,8 +644,8 @@ class ViewLayerRenderer { hugeDomNode.innerHTML = invalidLinesHTML.join(''); - var lineDomNode:HTMLElement, - source:HTMLElement; + var lineDomNode: HTMLElement, + source: HTMLElement; for (let i = 0; i < ctx.linesLength; i++) { let line = ctx.lines[i]; if (wasInvalid[i]) { @@ -657,7 +657,7 @@ class ViewLayerRenderer { } } - private _finishRendering(ctx: IRendererContext, domNodeIsEmpty:boolean, deltaTop:number[]): void { + private _finishRendering(ctx: IRendererContext, domNodeIsEmpty: boolean, deltaTop: number[]): void { let inlineDecorations = ViewLayerRenderer._resolveInlineDecorations(ctx); @@ -688,7 +688,7 @@ class ViewLayerRenderer { line.getLineOuterHTML(invalidLinesHTML, lineNumber, deltaTop[i]); wasInvalid[i] = true; hadInvalidLine = true; -// lineDomNode.innerHTML = line.getLineInnerHTML(lineNumber); + // lineDomNode.innerHTML = line.getLineInnerHTML(lineNumber); } } } diff --git a/src/vs/editor/browser/view/viewOverlays.ts b/src/vs/editor/browser/view/viewOverlays.ts index 7f85650c06dd3..d9710bc4d3536 100644 --- a/src/vs/editor/browser/view/viewOverlays.ts +++ b/src/vs/editor/browser/view/viewOverlays.ts @@ -4,24 +4,24 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {StyleMutator, FastDomNode, createFastDomNode} from 'vs/base/browser/styleMutator'; -import {IScrollEvent, IConfigurationChangedEvent, EditorLayoutInfo} from 'vs/editor/common/editorCommon'; +import { StyleMutator, FastDomNode, createFastDomNode } from 'vs/base/browser/styleMutator'; +import { IScrollEvent, IConfigurationChangedEvent, EditorLayoutInfo } from 'vs/editor/common/editorCommon'; import * as editorBrowser from 'vs/editor/browser/editorBrowser'; -import {IVisibleLineData, ViewLayer} from 'vs/editor/browser/view/viewLayer'; -import {DynamicViewOverlay} from 'vs/editor/browser/view/dynamicViewOverlay'; -import {Configuration} from 'vs/editor/browser/config/configuration'; -import {ViewContext} from 'vs/editor/common/view/viewContext'; -import {IRenderingContext, IRestrictedRenderingContext} from 'vs/editor/common/view/renderingContext'; -import {ILayoutProvider} from 'vs/editor/browser/viewLayout/layoutProvider'; -import {InlineDecoration} from 'vs/editor/common/viewModel/viewModel'; +import { IVisibleLineData, ViewLayer } from 'vs/editor/browser/view/viewLayer'; +import { DynamicViewOverlay } from 'vs/editor/browser/view/dynamicViewOverlay'; +import { Configuration } from 'vs/editor/browser/config/configuration'; +import { ViewContext } from 'vs/editor/common/view/viewContext'; +import { IRenderingContext, IRestrictedRenderingContext } from 'vs/editor/common/view/renderingContext'; +import { ILayoutProvider } from 'vs/editor/browser/viewLayout/layoutProvider'; +import { InlineDecoration } from 'vs/editor/common/viewModel/viewModel'; export class ViewOverlays extends ViewLayer { - private _dynamicOverlays:DynamicViewOverlay[]; - private _isFocused:boolean; - _layoutProvider:ILayoutProvider; + private _dynamicOverlays: DynamicViewOverlay[]; + private _isFocused: boolean; + _layoutProvider: ILayoutProvider; - constructor(context:ViewContext, layoutProvider:ILayoutProvider) { + constructor(context: ViewContext, layoutProvider: ILayoutProvider) { super(context); this._dynamicOverlays = []; @@ -61,13 +61,13 @@ export class ViewOverlays extends ViewLayer { return this.domNode.domNode; } - public addDynamicOverlay(overlay:DynamicViewOverlay): void { + public addDynamicOverlay(overlay: DynamicViewOverlay): void { this._dynamicOverlays.push(overlay); } // ----- event handlers - public onViewFocusChanged(isFocused:boolean): boolean { + public onViewFocusChanged(isFocused: boolean): boolean { this._isFocused = isFocused; return true; } @@ -80,7 +80,7 @@ export class ViewOverlays extends ViewLayer { } - public prepareRender(ctx:IRenderingContext): void { + public prepareRender(ctx: IRenderingContext): void { let toRender = this._dynamicOverlays.filter(overlay => overlay.shouldRender()); for (let i = 0, len = toRender.length; i < len; i++) { @@ -92,27 +92,27 @@ export class ViewOverlays extends ViewLayer { return null; } - public render(ctx:IRestrictedRenderingContext): void { + public render(ctx: IRestrictedRenderingContext): void { // Overwriting to bypass `shouldRender` flag this._viewOverlaysRender(ctx); this.domNode.toggleClassName('focused', this._isFocused); } - _viewOverlaysRender(ctx:IRestrictedRenderingContext): void { + _viewOverlaysRender(ctx: IRestrictedRenderingContext): void { super._renderLines(ctx.linesViewportData); } } export class ViewOverlayLine implements IVisibleLineData { - private _context:ViewContext; - private _dynamicOverlays:DynamicViewOverlay[]; + private _context: ViewContext; + private _dynamicOverlays: DynamicViewOverlay[]; private _domNode: FastDomNode; private _renderPieces: string; private _lineHeight: number; - constructor(context:ViewContext, dynamicOverlays:DynamicViewOverlay[]) { + constructor(context: ViewContext, dynamicOverlays: DynamicViewOverlay[]) { this._context = context; this._lineHeight = this._context.configuration.editor.lineHeight; this._dynamicOverlays = dynamicOverlays; @@ -127,7 +127,7 @@ export class ViewOverlayLine implements IVisibleLineData { } return this._domNode.domNode; } - public setDomNode(domNode:HTMLElement): void { + public setDomNode(domNode: HTMLElement): void { this._domNode = createFastDomNode(domNode); } @@ -146,13 +146,13 @@ export class ViewOverlayLine implements IVisibleLineData { onTokensChanged(): void { // Nothing } - onConfigurationChanged(e:IConfigurationChangedEvent): void { + onConfigurationChanged(e: IConfigurationChangedEvent): void { if (e.lineHeight) { this._lineHeight = this._context.configuration.editor.lineHeight; } } - shouldUpdateHTML(startLineNumber:number, lineNumber:number, inlineDecorations:InlineDecoration[]): boolean { + shouldUpdateHTML(startLineNumber: number, lineNumber: number, inlineDecorations: InlineDecoration[]): boolean { let newPieces = ''; for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) { let dynamicOverlay = this._dynamicOverlays[i]; @@ -168,7 +168,7 @@ export class ViewOverlayLine implements IVisibleLineData { return !piecesEqual; } - getLineOuterHTML(out:string[], lineNumber:number, deltaTop:number): void { + getLineOuterHTML(out: string[], lineNumber: number, deltaTop: number): void { out.push('
0 && visibleRanges[0].ranges[0].startStyle); let fullLineHeight = (this._lineHeight).toString(); let reducedLineHeight = (this._lineHeight - 1).toString(); @@ -380,7 +380,7 @@ export class SelectionsOverlay extends DynamicViewOverlay { } private _previousFrameVisibleRangesWithStyle: LineVisibleRangesWithStyle[][] = []; - public prepareRender(ctx:IRenderingContext): void { + public prepareRender(ctx: IRenderingContext): void { if (!this.shouldRender()) { throw new Error('I did not ask to render!'); } @@ -410,7 +410,7 @@ export class SelectionsOverlay extends DynamicViewOverlay { this._renderResult = output; } - public render(startLineNumber:number, lineNumber:number): string { + public render(startLineNumber: number, lineNumber: number): string { if (!this._renderResult) { return ''; } diff --git a/src/vs/editor/browser/viewParts/viewCursors/viewCursor.ts b/src/vs/editor/browser/viewParts/viewCursors/viewCursor.ts index 012dd312234ce..d6252a24070e5 100644 --- a/src/vs/editor/browser/viewParts/viewCursors/viewCursor.ts +++ b/src/vs/editor/browser/viewParts/viewCursors/viewCursor.ts @@ -4,11 +4,11 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {FastDomNode, createFastDomNode} from 'vs/base/browser/styleMutator'; -import {IConfigurationChangedEvent, IPosition, TextEditorCursorStyle} from 'vs/editor/common/editorCommon'; -import {Configuration} from 'vs/editor/browser/config/configuration'; -import {ViewContext} from 'vs/editor/common/view/viewContext'; -import {IRenderingContext, IRestrictedRenderingContext} from 'vs/editor/common/view/renderingContext'; +import { FastDomNode, createFastDomNode } from 'vs/base/browser/styleMutator'; +import { IConfigurationChangedEvent, IPosition, TextEditorCursorStyle } from 'vs/editor/common/editorCommon'; +import { Configuration } from 'vs/editor/browser/config/configuration'; +import { ViewContext } from 'vs/editor/common/view/viewContext'; +import { IRenderingContext, IRestrictedRenderingContext } from 'vs/editor/common/view/renderingContext'; export interface IViewCursorRenderData { position: IPosition; @@ -19,19 +19,19 @@ export interface IViewCursorRenderData { } export class ViewCursor { - private _context:ViewContext; + private _context: ViewContext; private _position: IPosition; - private _domNode:FastDomNode; - private _positionTop:number; - private _positionLeft:number; - private _isInEditableRange:boolean; - private _isVisible:boolean; - private _isInViewport:boolean; + private _domNode: FastDomNode; + private _positionTop: number; + private _positionLeft: number; + private _isInEditableRange: boolean; + private _isVisible: boolean; + private _isInViewport: boolean; private _cursorStyle: TextEditorCursorStyle; private _lastRenderedContent: string; private _lineHeight: number; - constructor(context:ViewContext, isSecondary:boolean) { + constructor(context: ViewContext, isSecondary: boolean) { this._context = context; this._cursorStyle = this._context.configuration.editor.viewInfo.cursorStyle; this._lineHeight = this._context.configuration.editor.lineHeight; @@ -109,7 +109,7 @@ export class ViewCursor { return true; } - public onConfigurationChanged(e:IConfigurationChangedEvent): boolean { + public onConfigurationChanged(e: IConfigurationChangedEvent): boolean { if (e.lineHeight) { this._lineHeight = this._context.configuration.editor.lineHeight; } @@ -122,7 +122,7 @@ export class ViewCursor { return true; } - public prepareRender(ctx:IRenderingContext): void { + public prepareRender(ctx: IRenderingContext): void { var visibleRange = ctx.visibleRangeForPosition(this._position); if (visibleRange) { this._positionTop = visibleRange.top; @@ -141,7 +141,7 @@ export class ViewCursor { return ''; } - public render(ctx:IRestrictedRenderingContext): IViewCursorRenderData { + public render(ctx: IRestrictedRenderingContext): IViewCursorRenderData { if (this._isInViewport) { let top = this._positionTop + ctx.viewportTop - ctx.bigNumbersDelta; let renderContent = this._getRenderedContent(); @@ -169,7 +169,7 @@ export class ViewCursor { return null; } - private updatePosition(newPosition:IPosition): void { + private updatePosition(newPosition: IPosition): void { this._position = newPosition; this._domNode.domNode.setAttribute('lineNumber', this._position.lineNumber.toString()); this._domNode.domNode.setAttribute('column', this._position.column.toString()); diff --git a/src/vs/editor/browser/viewParts/viewCursors/viewCursors.ts b/src/vs/editor/browser/viewParts/viewCursors/viewCursors.ts index 413a7d0244086..f0989285fec76 100644 --- a/src/vs/editor/browser/viewParts/viewCursors/viewCursors.ts +++ b/src/vs/editor/browser/viewParts/viewCursors/viewCursors.ts @@ -7,13 +7,13 @@ import 'vs/css!./viewCursors'; import * as editorCommon from 'vs/editor/common/editorCommon'; -import {ClassNames} from 'vs/editor/browser/editorBrowser'; -import {ViewPart} from 'vs/editor/browser/view/viewPart'; -import {IViewCursorRenderData, ViewCursor} from 'vs/editor/browser/viewParts/viewCursors/viewCursor'; -import {ViewContext} from 'vs/editor/common/view/viewContext'; -import {IRenderingContext, IRestrictedRenderingContext} from 'vs/editor/common/view/renderingContext'; -import {FastDomNode, createFastDomNode} from 'vs/base/browser/styleMutator'; -import {TimeoutTimer, IntervalTimer} from 'vs/base/common/async'; +import { ClassNames } from 'vs/editor/browser/editorBrowser'; +import { ViewPart } from 'vs/editor/browser/view/viewPart'; +import { IViewCursorRenderData, ViewCursor } from 'vs/editor/browser/viewParts/viewCursors/viewCursor'; +import { ViewContext } from 'vs/editor/common/view/viewContext'; +import { IRenderingContext, IRestrictedRenderingContext } from 'vs/editor/common/view/renderingContext'; +import { FastDomNode, createFastDomNode } from 'vs/base/browser/styleMutator'; +import { TimeoutTimer, IntervalTimer } from 'vs/base/common/async'; import * as browsers from 'vs/base/browser/browser'; const ANIMATIONS_SUPPORTED = !browsers.isIE9; diff --git a/src/vs/editor/browser/viewParts/viewZones/viewZones.ts b/src/vs/editor/browser/viewParts/viewZones/viewZones.ts index c2ebe39d6021a..ae4821e08d09e 100644 --- a/src/vs/editor/browser/viewParts/viewZones/viewZones.ts +++ b/src/vs/editor/browser/viewParts/viewZones/viewZones.ts @@ -4,14 +4,14 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; -import {onUnexpectedError} from 'vs/base/common/errors'; -import {StyleMutator} from 'vs/base/browser/styleMutator'; +import { onUnexpectedError } from 'vs/base/common/errors'; +import { StyleMutator } from 'vs/base/browser/styleMutator'; import * as editorCommon from 'vs/editor/common/editorCommon'; -import {ClassNames, IViewZone} from 'vs/editor/browser/editorBrowser'; -import {ViewPart} from 'vs/editor/browser/view/viewPart'; -import {ViewContext} from 'vs/editor/common/view/viewContext'; -import {IRenderingContext, IRestrictedRenderingContext} from 'vs/editor/common/view/renderingContext'; -import {IWhitespaceManager} from 'vs/editor/browser/viewLayout/layoutProvider'; +import { ClassNames, IViewZone } from 'vs/editor/browser/editorBrowser'; +import { ViewPart } from 'vs/editor/browser/view/viewPart'; +import { ViewContext } from 'vs/editor/common/view/viewContext'; +import { IRenderingContext, IRestrictedRenderingContext } from 'vs/editor/common/view/renderingContext'; +import { IWhitespaceManager } from 'vs/editor/browser/viewLayout/layoutProvider'; export interface IMyViewZone { whitespaceId: number; @@ -30,14 +30,14 @@ interface IComputedViewZoneProps { export class ViewZones extends ViewPart { - private _whitespaceManager:IWhitespaceManager; - private _zones: { [id:string]:IMyViewZone; }; - private _lineHeight:number; - private _contentWidth:number; + private _whitespaceManager: IWhitespaceManager; + private _zones: { [id: string]: IMyViewZone; }; + private _lineHeight: number; + private _contentWidth: number; public domNode: HTMLElement; - constructor(context:ViewContext, whitespaceManager:IWhitespaceManager) { + constructor(context: ViewContext, whitespaceManager: IWhitespaceManager) { super(context); this._lineHeight = this._context.configuration.editor.lineHeight; this._contentWidth = this._context.configuration.editor.layoutInfo.contentWidth; @@ -75,7 +75,7 @@ export class ViewZones extends ViewPart { return hadAChange; } - public onConfigurationChanged(e:editorCommon.IConfigurationChangedEvent): boolean { + public onConfigurationChanged(e: editorCommon.IConfigurationChangedEvent): boolean { if (e.lineHeight) { this._lineHeight = this._context.configuration.editor.lineHeight; @@ -93,11 +93,11 @@ export class ViewZones extends ViewPart { return this._recomputeWhitespacesProps(); } - public onLayoutChanged(layoutInfo:editorCommon.EditorLayoutInfo): boolean { + public onLayoutChanged(layoutInfo: editorCommon.EditorLayoutInfo): boolean { return true; } - public onScrollChanged(e:editorCommon.IScrollEvent): boolean { + public onScrollChanged(e: editorCommon.IScrollEvent): boolean { return e.scrollTopChanged || e.scrollWidthChanged; } @@ -105,17 +105,17 @@ export class ViewZones extends ViewPart { return true; } - public onModelLinesDeleted(e:editorCommon.IModelContentChangedLinesDeletedEvent): boolean { + public onModelLinesDeleted(e: editorCommon.IModelContentChangedLinesDeletedEvent): boolean { return true; } - public onModelLinesInserted(e:editorCommon.IViewLinesInsertedEvent): boolean { + public onModelLinesInserted(e: editorCommon.IViewLinesInsertedEvent): boolean { return true; } // ---- end view event handlers - private _getZoneOrdinal(zone:IViewZone): number { + private _getZoneOrdinal(zone: IViewZone): number { if (typeof zone.afterColumn !== 'undefined') { return zone.afterColumn; @@ -125,7 +125,7 @@ export class ViewZones extends ViewPart { } - private _computeWhitespaceProps(zone:IViewZone): IComputedViewZoneProps { + private _computeWhitespaceProps(zone: IViewZone): IComputedViewZoneProps { if (zone.afterLineNumber === 0) { return { afterViewLineNumber: 0, @@ -133,7 +133,7 @@ export class ViewZones extends ViewPart { }; } - let zoneAfterModelPosition:editorCommon.IPosition; + let zoneAfterModelPosition: editorCommon.IPosition; if (typeof zone.afterColumn !== 'undefined') { zoneAfterModelPosition = this._context.model.validateModelPosition({ lineNumber: zone.afterLineNumber, @@ -151,7 +151,7 @@ export class ViewZones extends ViewPart { }; } - let zoneBeforeModelPosition:editorCommon.IPosition; + let zoneBeforeModelPosition: editorCommon.IPosition; if (zoneAfterModelPosition.column === this._context.model.getModelLineMaxColumn(zoneAfterModelPosition.lineNumber)) { zoneBeforeModelPosition = this._context.model.validateModelPosition({ lineNumber: zoneAfterModelPosition.lineNumber + 1, @@ -172,11 +172,11 @@ export class ViewZones extends ViewPart { }; } - public addZone(zone:IViewZone): number { + public addZone(zone: IViewZone): number { let props = this._computeWhitespaceProps(zone); let whitespaceId = this._whitespaceManager.addWhitespace(props.afterViewLineNumber, this._getZoneOrdinal(zone), props.heightInPx); - let myZone:IMyViewZone = { + let myZone: IMyViewZone = { whitespaceId: whitespaceId, delegate: zone, isVisible: false @@ -198,7 +198,7 @@ export class ViewZones extends ViewPart { return myZone.whitespaceId; } - public removeZone(id:number): boolean { + public removeZone(id: number): boolean { if (this._zones.hasOwnProperty(id.toString())) { var zone = this._zones[id.toString()]; delete this._zones[id.toString()]; @@ -232,7 +232,7 @@ export class ViewZones extends ViewPart { return changed; } - public shouldSuppressMouseDownOnViewZone(id:number): boolean { + public shouldSuppressMouseDownOnViewZone(id: number): boolean { if (this._zones.hasOwnProperty(id.toString())) { var zone = this._zones[id.toString()]; return zone.delegate.suppressMouseDown; @@ -240,7 +240,7 @@ export class ViewZones extends ViewPart { return false; } - private _heightInPixels(zone:IViewZone): number { + private _heightInPixels(zone: IViewZone): number { if (typeof zone.heightInPx === 'number') { return zone.heightInPx; } @@ -270,16 +270,16 @@ export class ViewZones extends ViewPart { } } - public prepareRender(ctx:IRenderingContext): void { + public prepareRender(ctx: IRenderingContext): void { // Nothing to read if (!this.shouldRender()) { throw new Error('I did not ask to render!'); } } - public render(ctx:IRestrictedRenderingContext): void { + public render(ctx: IRestrictedRenderingContext): void { let visibleWhitespaces = this._whitespaceManager.getWhitespaceViewportData(); - let visibleZones:{[id:string]:editorCommon.IViewWhitespaceViewportData;} = {}; + let visibleZones: { [id: string]: editorCommon.IViewWhitespaceViewportData; } = {}; let hasVisibleZone = false; for (let i = 0, len = visibleWhitespaces.length; i < len; i++) { diff --git a/src/vs/editor/browser/widget/codeEditorWidget.ts b/src/vs/editor/browser/widget/codeEditorWidget.ts index 8adb5ce1c4db5..321789169379d 100644 --- a/src/vs/editor/browser/widget/codeEditorWidget.ts +++ b/src/vs/editor/browser/widget/codeEditorWidget.ts @@ -6,75 +6,75 @@ import 'vs/css!./media/editor'; import 'vs/css!./media/tokens'; -import {onUnexpectedError} from 'vs/base/common/errors'; -import {IEventEmitter} from 'vs/base/common/eventEmitter'; +import { onUnexpectedError } from 'vs/base/common/errors'; +import { IEventEmitter } from 'vs/base/common/eventEmitter'; import * as browser from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; -import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; -import {ICommandService} from 'vs/platform/commands/common/commands'; -import {IContextKeyService} from 'vs/platform/contextkey/common/contextkey'; -import {CommonCodeEditor} from 'vs/editor/common/commonCodeEditor'; -import {CommonEditorConfiguration} from 'vs/editor/common/config/commonEditorConfig'; -import {Range} from 'vs/editor/common/core/range'; -import {Selection} from 'vs/editor/common/core/selection'; +import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; +import { ICommandService } from 'vs/platform/commands/common/commands'; +import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; +import { CommonCodeEditor } from 'vs/editor/common/commonCodeEditor'; +import { CommonEditorConfiguration } from 'vs/editor/common/config/commonEditorConfig'; +import { Range } from 'vs/editor/common/core/range'; +import { Selection } from 'vs/editor/common/core/selection'; import * as editorCommon from 'vs/editor/common/editorCommon'; -import {EditorAction} from 'vs/editor/common/editorCommonExtensions'; -import {ICodeEditorService} from 'vs/editor/common/services/codeEditorService'; -import {Configuration} from 'vs/editor/browser/config/configuration'; +import { EditorAction } from 'vs/editor/common/editorCommonExtensions'; +import { ICodeEditorService } from 'vs/editor/common/services/codeEditorService'; +import { Configuration } from 'vs/editor/browser/config/configuration'; import * as editorBrowser from 'vs/editor/browser/editorBrowser'; -import {Colorizer} from 'vs/editor/browser/standalone/colorizer'; -import {View} from 'vs/editor/browser/view/viewImpl'; -import {Disposable, IDisposable} from 'vs/base/common/lifecycle'; -import Event, {Emitter} from 'vs/base/common/event'; -import {IKeyboardEvent} from 'vs/base/browser/keyboardEvent'; -import {InternalEditorAction} from 'vs/editor/common/editorAction'; +import { Colorizer } from 'vs/editor/browser/standalone/colorizer'; +import { View } from 'vs/editor/browser/view/viewImpl'; +import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; +import Event, { Emitter } from 'vs/base/common/event'; +import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; +import { InternalEditorAction } from 'vs/editor/common/editorAction'; export abstract class CodeEditorWidget extends CommonCodeEditor implements editorBrowser.ICodeEditor { - public onMouseUp(listener: (e:editorBrowser.IEditorMouseEvent)=>void): IDisposable { + public onMouseUp(listener: (e: editorBrowser.IEditorMouseEvent) => void): IDisposable { return this.addListener2(editorCommon.EventType.MouseUp, listener); } - public onMouseDown(listener: (e:editorBrowser.IEditorMouseEvent)=>void): IDisposable { + public onMouseDown(listener: (e: editorBrowser.IEditorMouseEvent) => void): IDisposable { return this.addListener2(editorCommon.EventType.MouseDown, listener); } - public onContextMenu(listener: (e:editorBrowser.IEditorMouseEvent)=>void): IDisposable { + public onContextMenu(listener: (e: editorBrowser.IEditorMouseEvent) => void): IDisposable { return this.addListener2(editorCommon.EventType.ContextMenu, listener); } - public onMouseMove(listener: (e:editorBrowser.IEditorMouseEvent)=>void): IDisposable { + public onMouseMove(listener: (e: editorBrowser.IEditorMouseEvent) => void): IDisposable { return this.addListener2(editorCommon.EventType.MouseMove, listener); } - public onMouseLeave(listener: (e:editorBrowser.IEditorMouseEvent)=>void): IDisposable { + public onMouseLeave(listener: (e: editorBrowser.IEditorMouseEvent) => void): IDisposable { return this.addListener2(editorCommon.EventType.MouseLeave, listener); } - public onKeyUp(listener: (e:IKeyboardEvent)=>void): IDisposable { + public onKeyUp(listener: (e: IKeyboardEvent) => void): IDisposable { return this.addListener2(editorCommon.EventType.KeyUp, listener); } - public onKeyDown(listener: (e:IKeyboardEvent)=>void): IDisposable { + public onKeyDown(listener: (e: IKeyboardEvent) => void): IDisposable { return this.addListener2(editorCommon.EventType.KeyDown, listener); } - public onDidLayoutChange(listener: (e:editorCommon.EditorLayoutInfo)=>void): IDisposable { + public onDidLayoutChange(listener: (e: editorCommon.EditorLayoutInfo) => void): IDisposable { return this.addListener2(editorCommon.EventType.EditorLayout, listener); } - public onDidScrollChange(listener: (e:editorCommon.IScrollEvent)=>void): IDisposable { + public onDidScrollChange(listener: (e: editorCommon.IScrollEvent) => void): IDisposable { return this.addListener2('scroll', listener); } private _codeEditorService: ICodeEditorService; private _commandService: ICommandService; - protected domElement:HTMLElement; + protected domElement: HTMLElement; private _focusTracker: CodeEditorWidgetFocusTracker; - _configuration:Configuration; + _configuration: Configuration; - private contentWidgets:{ [key:string]:editorBrowser.IContentWidgetData; }; - private overlayWidgets:{ [key:string]:editorBrowser.IOverlayWidgetData; }; + private contentWidgets: { [key: string]: editorBrowser.IContentWidgetData; }; + private overlayWidgets: { [key: string]: editorBrowser.IOverlayWidgetData; }; - _view:editorBrowser.IView; + _view: editorBrowser.IView; constructor( - domElement:HTMLElement, - options:editorCommon.IEditorOptions, + domElement: HTMLElement, + options: editorCommon.IEditorOptions, @IInstantiationService instantiationService: IInstantiationService, @ICodeEditorService codeEditorService: ICodeEditorService, @ICommandService commandService: ICommandService, @@ -120,7 +120,7 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito protected abstract _getContributions(): editorBrowser.IEditorContributionCtor[]; protected abstract _getActions(): EditorAction[]; - protected _createConfiguration(options:editorCommon.ICodeEditorWidgetCreationOptions): CommonEditorConfiguration { + protected _createConfiguration(options: editorCommon.ICodeEditorWidgetCreationOptions): CommonEditorConfiguration { return new Configuration(options, this.domElement); } @@ -134,7 +134,7 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito super.dispose(); } - public updateOptions(newOptions:editorCommon.IEditorOptions): void { + public updateOptions(newOptions: editorCommon.IEditorOptions): void { let oldTheme = this._configuration.editor.viewInfo.theme; super.updateOptions(newOptions); let newTheme = this._configuration.editor.viewInfo.theme; @@ -144,7 +144,7 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito } } - public colorizeModelLine(lineNumber:number, model:editorCommon.IModel = this.model): string { + public colorizeModelLine(lineNumber: number, model: editorCommon.IModel = this.model): string { if (!model) { return ''; } @@ -205,7 +205,7 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito return this._view.getCodeEditorHelper().getScrollTop(); } - public setScrollLeft(newScrollLeft:number): void { + public setScrollLeft(newScrollLeft: number): void { if (!this.hasView) { return; } @@ -216,7 +216,7 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito scrollLeft: newScrollLeft }); } - public setScrollTop(newScrollTop:number): void { + public setScrollTop(newScrollTop: number): void { if (!this.hasView) { return; } @@ -234,7 +234,7 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito this._view.getCodeEditorHelper().setScrollPosition(position); } - public delegateVerticalScrollbarMouseDown(browserEvent:MouseEvent): void { + public delegateVerticalScrollbarMouseDown(browserEvent: MouseEvent): void { if (!this.hasView) { return; } @@ -245,7 +245,7 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito if (!this.cursor || !this.hasView) { return null; } - let contributionsState: {[key:string]:any} = {}; + let contributionsState: { [key: string]: any } = {}; let keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { @@ -265,7 +265,7 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito }; } - public restoreViewState(state:editorCommon.IEditorViewState): void { + public restoreViewState(state: editorCommon.IEditorViewState): void { if (!this.cursor || !this.hasView) { return; } @@ -293,7 +293,7 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito } } - public layout(dimension?:editorCommon.IDimension): void { + public layout(dimension?: editorCommon.IDimension): void { this._configuration.observeReferenceElement(dimension); this.render(); } @@ -391,9 +391,9 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito } } - public changeViewZones(callback:(accessor:editorBrowser.IViewZoneChangeAccessor)=>void): void { + public changeViewZones(callback: (accessor: editorBrowser.IViewZoneChangeAccessor) => void): void { if (!this.hasView) { -// console.warn('Cannot change view zones on editor that is not attached to a model, since there is no view.'); + // console.warn('Cannot change view zones on editor that is not attached to a model, since there is no view.'); return; } var hasChanges = this._view.change(callback); @@ -423,7 +423,7 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito return this._view.getCodeEditorHelper().getVerticalOffsetForPosition(lineNumber, column); } - public getScrolledVisiblePosition(rawPosition:editorCommon.IPosition): { top:number; left:number; height:number; } { + public getScrolledVisiblePosition(rawPosition: editorCommon.IPosition): { top: number; left: number; height: number; } { if (!this.hasView) { return null; } @@ -442,7 +442,7 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito }; } - public getOffsetForColumn(lineNumber:number, column:number): number { + public getOffsetForColumn(lineNumber: number, column: number): number { if (!this.hasView) { return -1; } @@ -456,24 +456,24 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito this._view.render(true, false); } - public setHiddenAreas(ranges:editorCommon.IRange[]): void { + public setHiddenAreas(ranges: editorCommon.IRange[]): void { if (this.viewModel) { this.viewModel.setHiddenAreas(ranges); } } - public setAriaActiveDescendant(id:string): void { + public setAriaActiveDescendant(id: string): void { if (!this.hasView) { return; } this._view.setAriaActiveDescendant(id); } - public applyFontInfo(target:HTMLElement): void { + public applyFontInfo(target: HTMLElement): void { Configuration.applyFontInfoSlow(target, this._configuration.editor.fontInfo); } - _attachModel(model:editorCommon.IModel): void { + _attachModel(model: editorCommon.IModel): void { this._view = null; super._attachModel(model); @@ -510,7 +510,7 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito this._commandService, this._configuration, this.viewModel, - (source:string, handlerId:string, payload:any) => { + (source: string, handlerId: string, payload: any) => { if (!this.cursor) { return; } @@ -524,7 +524,7 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito } protected _detachModel(): editorCommon.IModel { - var removeDomNode:HTMLElement = null; + var removeDomNode: HTMLElement = null; if (this._view) { this._view.dispose(); @@ -543,15 +543,15 @@ export abstract class CodeEditorWidget extends CommonCodeEditor implements edito // BEGIN decorations - protected _registerDecorationType(key:string, options: editorCommon.IDecorationRenderOptions, parentTypeKey?: string): void { + protected _registerDecorationType(key: string, options: editorCommon.IDecorationRenderOptions, parentTypeKey?: string): void { this._codeEditorService.registerDecorationType(key, options, parentTypeKey); } - protected _removeDecorationType(key:string): void { + protected _removeDecorationType(key: string): void { this._codeEditorService.removeDecorationType(key); } - protected _resolveDecorationOptions(typeKey:string, writable: boolean): editorCommon.IModelDecorationOptions { + protected _resolveDecorationOptions(typeKey: string, writable: boolean): editorCommon.IModelDecorationOptions { return this._codeEditorService.resolveDecorationOptions(typeKey, writable); } @@ -566,7 +566,7 @@ class CodeEditorWidgetFocusTracker extends Disposable { private _onChange: Emitter = this._register(new Emitter()); public onChage: Event = this._onChange.event; - constructor(domElement:HTMLElement) { + constructor(domElement: HTMLElement) { super(); this._hasFocus = false; @@ -593,11 +593,11 @@ class OverlayWidget2 implements editorBrowser.IOverlayWidget { private _position: editorBrowser.IOverlayWidgetPosition; private _domNode: HTMLElement; - constructor(id:string, position:editorBrowser.IOverlayWidgetPosition) { + constructor(id: string, position: editorBrowser.IOverlayWidgetPosition) { this._id = id; this._position = position; this._domNode = document.createElement('div'); - this._domNode.className = this._id.replace(/\./g, '-').replace(/[^a-z0-9\-]/,''); + this._domNode.className = this._id.replace(/\./g, '-').replace(/[^a-z0-9\-]/, ''); } public getId(): string { @@ -623,7 +623,7 @@ class SingleEditOperation { text: string; forceMoveMarkers: boolean; - constructor(source:editorCommon.ISingleEditOperation) { + constructor(source: editorCommon.ISingleEditOperation) { this.range = new Range(source.range.startLineNumber, source.range.startColumn, source.range.endLineNumber, source.range.endColumn); this.text = source.text; this.forceMoveMarkers = source.forceMoveMarkers || false; @@ -652,7 +652,7 @@ export class CommandRunner implements editorCommon.ICommand { }); // Merge operations that touch each other - var resultOps:editorCommon.ISingleEditOperation[] = []; + var resultOps: editorCommon.ISingleEditOperation[] = []; var previousOp = this._ops[0]; for (var i = 1; i < this._ops.length; i++) { if (previousOp.range.endLineNumber === this._ops[i].range.startLineNumber && previousOp.range.endColumn === this._ops[i].range.startColumn) { diff --git a/src/vs/editor/browser/widget/diffEditorWidget.ts b/src/vs/editor/browser/widget/diffEditorWidget.ts index a3d24a4fc2111..a91d8f6122646 100644 --- a/src/vs/editor/browser/widget/diffEditorWidget.ts +++ b/src/vs/editor/browser/widget/diffEditorWidget.ts @@ -6,64 +6,64 @@ 'use strict'; import 'vs/css!./media/diffEditor'; -import {RunOnceScheduler} from 'vs/base/common/async'; -import {EventEmitter, EmitterEvent} from 'vs/base/common/eventEmitter'; -import {IDisposable, dispose} from 'vs/base/common/lifecycle'; +import { RunOnceScheduler } from 'vs/base/common/async'; +import { EventEmitter, EmitterEvent } from 'vs/base/common/eventEmitter'; +import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import * as objects from 'vs/base/common/objects'; import * as dom from 'vs/base/browser/dom'; -import {StyleMutator} from 'vs/base/browser/styleMutator'; -import {ISashEvent, IVerticalSashLayoutProvider, Sash} from 'vs/base/browser/ui/sash/sash'; -import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; -import {IContextKeyService} from 'vs/platform/contextkey/common/contextkey'; -import {DefaultConfig} from 'vs/editor/common/config/defaultConfig'; -import {Range} from 'vs/editor/common/core/range'; +import { StyleMutator } from 'vs/base/browser/styleMutator'; +import { ISashEvent, IVerticalSashLayoutProvider, Sash } from 'vs/base/browser/ui/sash/sash'; +import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; +import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; +import { DefaultConfig } from 'vs/editor/common/config/defaultConfig'; +import { Range } from 'vs/editor/common/core/range'; import * as editorCommon from 'vs/editor/common/editorCommon'; -import {IEditorWorkerService} from 'vs/editor/common/services/editorWorkerService'; -import {createLineParts} from 'vs/editor/common/viewLayout/viewLineParts'; -import {renderLine, RenderLineInput} from 'vs/editor/common/viewLayout/viewLineRenderer'; +import { IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService'; +import { createLineParts } from 'vs/editor/common/viewLayout/viewLineParts'; +import { renderLine, RenderLineInput } from 'vs/editor/common/viewLayout/viewLineRenderer'; import * as editorBrowser from 'vs/editor/browser/editorBrowser'; -import {CodeEditor} from 'vs/editor/browser/codeEditor'; -import {ViewLineToken, ViewLineTokens} from 'vs/editor/common/core/viewLineToken'; -import {Configuration} from 'vs/editor/browser/config/configuration'; -import {Position} from 'vs/editor/common/core/position'; -import {Selection} from 'vs/editor/common/core/selection'; -import {InlineDecoration} from 'vs/editor/common/viewModel/viewModel'; +import { CodeEditor } from 'vs/editor/browser/codeEditor'; +import { ViewLineToken, ViewLineTokens } from 'vs/editor/common/core/viewLineToken'; +import { Configuration } from 'vs/editor/browser/config/configuration'; +import { Position } from 'vs/editor/common/core/position'; +import { Selection } from 'vs/editor/common/core/selection'; +import { InlineDecoration } from 'vs/editor/common/viewModel/viewModel'; interface IEditorDiffDecorations { - decorations:editorCommon.IModelDeltaDecoration[]; - overviewZones:editorCommon.OverviewRulerZone[]; + decorations: editorCommon.IModelDeltaDecoration[]; + overviewZones: editorCommon.OverviewRulerZone[]; } interface IEditorDiffDecorationsWithZones extends IEditorDiffDecorations { - zones:editorBrowser.IViewZone[]; + zones: editorBrowser.IViewZone[]; } interface IEditorsDiffDecorations { - original:IEditorDiffDecorations; - modified:IEditorDiffDecorations; + original: IEditorDiffDecorations; + modified: IEditorDiffDecorations; } interface IEditorsDiffDecorationsWithZones { - original:IEditorDiffDecorationsWithZones; - modified:IEditorDiffDecorationsWithZones; + original: IEditorDiffDecorationsWithZones; + modified: IEditorDiffDecorationsWithZones; } interface IEditorsZones { - original:editorBrowser.IViewZone[]; - modified:editorBrowser.IViewZone[]; + original: editorBrowser.IViewZone[]; + modified: editorBrowser.IViewZone[]; } interface IDiffEditorWidgetStyle { - getEditorsDiffDecorations(lineChanges:editorCommon.ILineChange[], ignoreTrimWhitespace:boolean, originalWhitespaces:editorCommon.IEditorWhitespace[], modifiedWhitespaces:editorCommon.IEditorWhitespace[], originalEditor:editorBrowser.ICodeEditor, modifiedEditor:editorBrowser.ICodeEditor): IEditorsDiffDecorationsWithZones; - setEnableSplitViewResizing(enableSplitViewResizing:boolean): void; + getEditorsDiffDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, originalWhitespaces: editorCommon.IEditorWhitespace[], modifiedWhitespaces: editorCommon.IEditorWhitespace[], originalEditor: editorBrowser.ICodeEditor, modifiedEditor: editorBrowser.ICodeEditor): IEditorsDiffDecorationsWithZones; + setEnableSplitViewResizing(enableSplitViewResizing: boolean): void; layout(): number; dispose(): void; } class VisualEditorState { - private _zones:number[]; - private _zonesMap:{[zoneId:string]:boolean;}; - private _decorations:string[]; + private _zones: number[]; + private _zonesMap: { [zoneId: string]: boolean; }; + private _decorations: string[]; constructor() { this._zones = []; @@ -71,14 +71,14 @@ class VisualEditorState { this._decorations = []; } - public getForeignViewZones(allViewZones:editorCommon.IEditorWhitespace[]): editorCommon.IEditorWhitespace[] { + public getForeignViewZones(allViewZones: editorCommon.IEditorWhitespace[]): editorCommon.IEditorWhitespace[] { return allViewZones.filter((z) => !this._zonesMap[String(z.id)]); } - public clean(editor:CodeEditor): void { + public clean(editor: CodeEditor): void { // (1) View zones if (this._zones.length > 0) { - editor.changeViewZones((viewChangeAccessor:editorBrowser.IViewZoneChangeAccessor) => { + editor.changeViewZones((viewChangeAccessor: editorBrowser.IViewZoneChangeAccessor) => { for (var i = 0, length = this._zones.length; i < length; i++) { viewChangeAccessor.removeZone(this._zones[i]); } @@ -89,19 +89,19 @@ class VisualEditorState { // (2) Model decorations if (this._decorations.length > 0) { - editor.changeDecorations((changeAccessor:editorCommon.IModelDecorationsChangeAccessor) => { + editor.changeDecorations((changeAccessor: editorCommon.IModelDecorationsChangeAccessor) => { changeAccessor.deltaDecorations(this._decorations, []); }); } this._decorations = []; } - public apply(editor:CodeEditor, overviewRuler:editorBrowser.IOverviewRuler, newDecorations:IEditorDiffDecorationsWithZones): void { - var i:number, + public apply(editor: CodeEditor, overviewRuler: editorBrowser.IOverviewRuler, newDecorations: IEditorDiffDecorationsWithZones): void { + var i: number, length: number; // view zones - editor.changeViewZones((viewChangeAccessor:editorBrowser.IViewZoneChangeAccessor) => { + editor.changeViewZones((viewChangeAccessor: editorBrowser.IViewZoneChangeAccessor) => { for (i = 0, length = this._zones.length; i < length; i++) { viewChangeAccessor.removeZone(this._zones[i]); } @@ -129,31 +129,31 @@ var DIFF_EDITOR_ID = 0; export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDiffEditor { - public onDidChangeModelRawContent(listener: (e:editorCommon.IModelContentChangedEvent)=>void): IDisposable { + public onDidChangeModelRawContent(listener: (e: editorCommon.IModelContentChangedEvent) => void): IDisposable { return this.addListener2(editorCommon.EventType.ModelRawContentChanged, listener); } - public onDidChangeModelContent(listener: (e:editorCommon.IModelContentChangedEvent2)=>void): IDisposable { + public onDidChangeModelContent(listener: (e: editorCommon.IModelContentChangedEvent2) => void): IDisposable { return this.addListener2(editorCommon.EventType.ModelContentChanged2, listener); } - public onDidChangeModelMode(listener: (e:editorCommon.IModelModeChangedEvent)=>void): IDisposable { + public onDidChangeModelMode(listener: (e: editorCommon.IModelModeChangedEvent) => void): IDisposable { return this.addListener2(editorCommon.EventType.ModelModeChanged, listener); } - public onDidChangeModelOptions(listener: (e:editorCommon.IModelOptionsChangedEvent)=>void): IDisposable { + public onDidChangeModelOptions(listener: (e: editorCommon.IModelOptionsChangedEvent) => void): IDisposable { return this.addListener2(editorCommon.EventType.ModelOptionsChanged, listener); } - public onDidChangeConfiguration(listener: (e:editorCommon.IConfigurationChangedEvent)=>void): IDisposable { + public onDidChangeConfiguration(listener: (e: editorCommon.IConfigurationChangedEvent) => void): IDisposable { return this.addListener2(editorCommon.EventType.ConfigurationChanged, listener); } - public onDidChangeCursorPosition(listener: (e:editorCommon.ICursorPositionChangedEvent)=>void): IDisposable { + public onDidChangeCursorPosition(listener: (e: editorCommon.ICursorPositionChangedEvent) => void): IDisposable { return this.addListener2(editorCommon.EventType.CursorPositionChanged, listener); } - public onDidChangeCursorSelection(listener: (e:editorCommon.ICursorSelectionChangedEvent)=>void): IDisposable { + public onDidChangeCursorSelection(listener: (e: editorCommon.ICursorSelectionChangedEvent) => void): IDisposable { return this.addListener2(editorCommon.EventType.CursorSelectionChanged, listener); } - public onDidDispose(listener: ()=>void): IDisposable { + public onDidDispose(listener: () => void): IDisposable { return this.addListener2(editorCommon.EventType.Disposed, listener); } - public onDidUpdateDiff(listener: ()=>void): IDisposable { + public onDidUpdateDiff(listener: () => void): IDisposable { return this.addListener2(editorCommon.EventType.DiffUpdated, listener); } @@ -163,51 +163,51 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif private id: number; - private _toDispose:IDisposable[]; + private _toDispose: IDisposable[]; - private _theme:string; - private _domElement:HTMLElement; - _containerDomElement:HTMLElement; - private _overviewDomElement:HTMLElement; + private _theme: string; + private _domElement: HTMLElement; + _containerDomElement: HTMLElement; + private _overviewDomElement: HTMLElement; private _overviewViewportDomElement: HTMLElement; - private _width:number; - private _height:number; - private _measureDomElementToken:number; + private _width: number; + private _height: number; + private _measureDomElementToken: number; - private originalEditor:CodeEditor; - private _originalDomNode:HTMLElement; - private _originalEditorState:VisualEditorState; - private _originalOverviewRuler:editorBrowser.IOverviewRuler; + private originalEditor: CodeEditor; + private _originalDomNode: HTMLElement; + private _originalEditorState: VisualEditorState; + private _originalOverviewRuler: editorBrowser.IOverviewRuler; - private modifiedEditor:CodeEditor; - private _modifiedDomNode:HTMLElement; - private _modifiedEditorState:VisualEditorState; - private _modifiedOverviewRuler:editorBrowser.IOverviewRuler; + private modifiedEditor: CodeEditor; + private _modifiedDomNode: HTMLElement; + private _modifiedEditorState: VisualEditorState; + private _modifiedOverviewRuler: editorBrowser.IOverviewRuler; - private _currentlyChangingViewZones:boolean; - private _beginUpdateDecorationsTimeout:number; - private _diffComputationToken:number; - private _lineChanges:editorCommon.ILineChange[]; + private _currentlyChangingViewZones: boolean; + private _beginUpdateDecorationsTimeout: number; + private _diffComputationToken: number; + private _lineChanges: editorCommon.ILineChange[]; - private _isVisible:boolean; - private _isHandlingScrollEvent:boolean; + private _isVisible: boolean; + private _isHandlingScrollEvent: boolean; private _ignoreTrimWhitespace: boolean; private _originalIsEditable: boolean; - private _renderSideBySide:boolean; - private _enableSplitViewResizing:boolean; - private _strategy:IDiffEditorWidgetStyle; + private _renderSideBySide: boolean; + private _enableSplitViewResizing: boolean; + private _strategy: IDiffEditorWidgetStyle; - private _updateDecorationsRunner:RunOnceScheduler; + private _updateDecorationsRunner: RunOnceScheduler; private _editorWorkerService: IEditorWorkerService; protected _contextKeyService: IContextKeyService; constructor( - domElement:HTMLElement, - options:editorCommon.IDiffEditorOptions, + domElement: HTMLElement, + options: editorCommon.IDiffEditorOptions, @IEditorWorkerService editorWorkerService: IEditorWorkerService, @IContextKeyService contextKeyService: IContextKeyService, @IInstantiationService instantiationService: IInstantiationService @@ -261,7 +261,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif this._overviewDomElement.appendChild(this._overviewViewportDomElement); - this._toDispose.push(dom.addDisposableListener(this._overviewDomElement, 'mousedown', (e:MouseEvent) => { + this._toDispose.push(dom.addDisposableListener(this._overviewDomElement, 'mousedown', (e: MouseEvent) => { this.modifiedEditor.delegateVerticalScrollbarMouseDown(e); })); this._containerDomElement.appendChild(this._overviewDomElement); @@ -312,7 +312,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif return this._renderSideBySide; } - private static _getClassName(theme:string, renderSideBySide:boolean): string { + private static _getClassName(theme: string, renderSideBySide: boolean): string { var result = 'monaco-diff-editor monaco-editor-background '; if (renderSideBySide) { result += 'side-by-side '; @@ -361,7 +361,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif this._toDispose.push(this.addEmitter2(this.originalEditor)); } - private _createRightHandSideEditor(options:editorCommon.IDiffEditorOptions, instantiationService:IInstantiationService): void { + private _createRightHandSideEditor(options: editorCommon.IDiffEditorOptions, instantiationService: IInstantiationService): void { this.modifiedEditor = instantiationService.createInstance(CodeEditor, this._modifiedDomNode, this._adjustOptionsForRightHandSide(options)); this._toDispose.push(this.modifiedEditor.addBulkListener2((events) => this._onModifiedEditorEvents(events))); this._toDispose.push(this.addEmitter2(this.modifiedEditor)); @@ -413,7 +413,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif return this.modifiedEditor; } - public updateOptions(newOptions:editorCommon.IDiffEditorOptions): void { + public updateOptions(newOptions: editorCommon.IDiffEditorOptions): void { // Handle new theme this._theme = newOptions && newOptions.theme ? newOptions.theme : this._theme; @@ -460,7 +460,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif } } - public getValue(options:{ preserveBOM:boolean; lineEnding:string; }=null): string { + public getValue(options: { preserveBOM: boolean; lineEnding: string; } = null): string { return this.modifiedEditor.getValue(options); } @@ -471,7 +471,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif }; } - public setModel(model:editorCommon.IDiffEditorModel): void { + public setModel(model: editorCommon.IDiffEditorModel): void { // Guard us against partial null model if (model && (!model.original || !model.modified)) { throw new Error(!model.original ? 'DiffEditorWidget.setModel: Original model is null' : 'DiffEditorWidget.setModel: Modified model is null'); @@ -510,7 +510,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif return this._domElement; } - public getVisibleColumnFromPosition(position:editorCommon.IPosition): number { + public getVisibleColumnFromPosition(position: editorCommon.IPosition): number { return this.modifiedEditor.getVisibleColumnFromPosition(position); } @@ -518,7 +518,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif return this.modifiedEditor.getPosition(); } - public setPosition(position: editorCommon.IPosition, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void { + public setPosition(position: editorCommon.IPosition, reveal?: boolean, revealVerticalInCenter?: boolean, revealHorizontal?: boolean): void { this.modifiedEditor.setPosition(position, reveal, revealVerticalInCenter, revealHorizontal); } @@ -534,7 +534,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif this.modifiedEditor.revealLineInCenterIfOutsideViewport(lineNumber); } - public revealPosition(position: editorCommon.IPosition, revealVerticalInCenter:boolean = false, revealHorizontal:boolean = false): void { + public revealPosition(position: editorCommon.IPosition, revealVerticalInCenter: boolean = false, revealHorizontal: boolean = false): void { this.modifiedEditor.revealPosition(position, revealVerticalInCenter, revealHorizontal); } @@ -554,11 +554,11 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif return this.modifiedEditor.getSelections(); } - public setSelection(range:editorCommon.IRange, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void; - public setSelection(editorRange:Range, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void; - public setSelection(selection:editorCommon.ISelection, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void; - public setSelection(editorSelection:Selection, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void; - public setSelection(something:any, reveal?:boolean, revealVerticalInCenter?:boolean, revealHorizontal?:boolean): void { + public setSelection(range: editorCommon.IRange, reveal?: boolean, revealVerticalInCenter?: boolean, revealHorizontal?: boolean): void; + public setSelection(editorRange: Range, reveal?: boolean, revealVerticalInCenter?: boolean, revealHorizontal?: boolean): void; + public setSelection(selection: editorCommon.ISelection, reveal?: boolean, revealVerticalInCenter?: boolean, revealHorizontal?: boolean): void; + public setSelection(editorSelection: Selection, reveal?: boolean, revealVerticalInCenter?: boolean, revealHorizontal?: boolean): void; + public setSelection(something: any, reveal?: boolean, revealVerticalInCenter?: boolean, revealHorizontal?: boolean): void { this.modifiedEditor.setSelection(something, reveal, revealVerticalInCenter, revealHorizontal); } @@ -578,7 +578,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif this.modifiedEditor.revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber); } - public revealRange(range: editorCommon.IRange, revealVerticalInCenter:boolean = false, revealHorizontal:boolean = true): void { + public revealRange(range: editorCommon.IRange, revealVerticalInCenter: boolean = false, revealHorizontal: boolean = true): void { this.modifiedEditor.revealRange(range, revealVerticalInCenter, revealHorizontal); } @@ -590,7 +590,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif this.modifiedEditor.revealRangeInCenterIfOutsideViewport(range); } - public addAction(descriptor:editorCommon.IActionDescriptor): void { + public addAction(descriptor: editorCommon.IActionDescriptor): void { this.modifiedEditor.addAction(descriptor); } @@ -602,7 +602,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif return this.modifiedEditor.getSupportedActions(); } - public getAction(id:string): editorCommon.IEditorAction { + public getAction(id: string): editorCommon.IEditorAction { return this.modifiedEditor.getAction(id); } @@ -615,7 +615,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif }; } - public restoreViewState(state:editorCommon.IEditorViewState): void { + public restoreViewState(state: editorCommon.IEditorViewState): void { var s = state; if (s.original && s.original) { var diffEditorState = s; @@ -624,7 +624,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif } } - public layout(dimension?:editorCommon.IDimension): void { + public layout(dimension?: editorCommon.IDimension): void { this._measureDomElement(false, dimension); } @@ -652,11 +652,11 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif this._cleanViewZonesAndDecorations(); } - public trigger(source:string, handlerId:string, payload:any): void { + public trigger(source: string, handlerId: string, payload: any): void { this.modifiedEditor.trigger(source, handlerId, payload); } - public changeDecorations(callback:(changeAccessor:editorCommon.IModelDecorationsChangeAccessor)=>any): any { + public changeDecorations(callback: (changeAccessor: editorCommon.IModelDecorationsChangeAccessor) => any): any { return this.modifiedEditor.changeDecorations(callback); } @@ -666,7 +666,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif //------------ begin layouting methods - private _measureDomElement(forceDoLayoutCall:boolean, dimensions?:editorCommon.IDimension): void { + private _measureDomElement(forceDoLayoutCall: boolean, dimensions?: editorCommon.IDimension): void { dimensions = dimensions || { width: this._containerDomElement.clientWidth, height: this._containerDomElement.clientHeight @@ -690,7 +690,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif } private _layoutOverviewRulers(): void { - var freeSpace = DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH - 2*DiffEditorWidget.ONE_OVERVIEW_WIDTH; + var freeSpace = DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH - 2 * DiffEditorWidget.ONE_OVERVIEW_WIDTH; var layoutInfo = this.modifiedEditor.getLayoutInfo(); if (layoutInfo) { this._originalOverviewRuler.setLayout(new editorCommon.OverviewRulerPosition({ @@ -710,7 +710,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif //------------ end layouting methods - private _recomputeIfNecessary(events:EmitterEvent[]): void { + private _recomputeIfNecessary(events: EmitterEvent[]): void { var changed = false; for (var i = 0; !changed && i < events.length; i++) { var type = events[i].getType(); @@ -726,7 +726,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif } } - private _onOriginalEditorEvents(events:EmitterEvent[]): void { + private _onOriginalEditorEvents(events: EmitterEvent[]): void { for (var i = 0; i < events.length; i++) { let type = events[i].getType(); let data = events[i].getData(); @@ -748,7 +748,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif this._recomputeIfNecessary(events); } - private _onModifiedEditorEvents(events:EmitterEvent[]): void { + private _onModifiedEditorEvents(events: EmitterEvent[]): void { for (var i = 0; i < events.length; i++) { let type = events[i].getType(); let data = events[i].getData(); @@ -803,18 +803,16 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif if (currentToken === this._diffComputationToken && currentOriginalModel === this.originalEditor.getModel() && currentModifiedModel === this.modifiedEditor.getModel() - ) - { + ) { this._lineChanges = result; this._updateDecorationsRunner.schedule(); - this.emit(editorCommon.EventType.DiffUpdated, { }); + this.emit(editorCommon.EventType.DiffUpdated, {}); } }, (error) => { if (currentToken === this._diffComputationToken && currentOriginalModel === this.originalEditor.getModel() && currentModifiedModel === this.modifiedEditor.getModel() - ) - { + ) { this._lineChanges = null; this._updateDecorationsRunner.schedule(); } @@ -843,8 +841,8 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif } } - private _adjustOptionsForSubEditor(options:editorCommon.IDiffEditorOptions): editorCommon.IDiffEditorOptions { - let clonedOptions:editorCommon.IDiffEditorOptions = objects.clone(options || {}); + private _adjustOptionsForSubEditor(options: editorCommon.IDiffEditorOptions): editorCommon.IDiffEditorOptions { + let clonedOptions: editorCommon.IDiffEditorOptions = objects.clone(options || {}); clonedOptions.wrappingColumn = -1; clonedOptions.automaticLayout = false; clonedOptions.scrollbar = clonedOptions.scrollbar || {}; @@ -854,7 +852,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif return clonedOptions; } - private _adjustOptionsForLeftHandSide(options:editorCommon.IDiffEditorOptions, isEditable:boolean): editorCommon.IDiffEditorOptions { + private _adjustOptionsForLeftHandSide(options: editorCommon.IDiffEditorOptions, isEditable: boolean): editorCommon.IDiffEditorOptions { let result = this._adjustOptionsForSubEditor(options); result.readOnly = !isEditable; result.overviewRulerLanes = 1; @@ -862,7 +860,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif return result; } - private _adjustOptionsForRightHandSide(options:editorCommon.IDiffEditorOptions): editorCommon.IDiffEditorOptions { + private _adjustOptionsForRightHandSide(options: editorCommon.IDiffEditorOptions): editorCommon.IDiffEditorOptions { let result = this._adjustOptionsForSubEditor(options); result.revealHorizontalRightPadding = DefaultConfig.editor.revealHorizontalRightPadding + DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH; result.scrollbar.verticalHasArrows = false; @@ -870,7 +868,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif return result; } - private _onOriginalEditorScroll(e:editorCommon.IScrollEvent): void { + private _onOriginalEditorScroll(e: editorCommon.IScrollEvent): void { if (!e.scrollTopChanged && !e.scrollLeftChanged) { return; } @@ -885,11 +883,11 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif this._isHandlingScrollEvent = false; } - private _onModifiedEditorScroll(e:editorCommon.IScrollEvent): void { + private _onModifiedEditorScroll(e: editorCommon.IScrollEvent): void { if (!e.scrollTopChanged && !e.scrollLeftChanged) { return; } - if(this._isHandlingScrollEvent) { + if (this._isHandlingScrollEvent) { return; } this._isHandlingScrollEvent = true; @@ -936,7 +934,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif } } - private _computeOverviewViewport(): { height: number; top: number;} { + private _computeOverviewViewport(): { height: number; top: number; } { var layoutInfo = this.modifiedEditor.getLayoutInfo(); if (!layoutInfo) { return null; @@ -958,7 +956,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif }; } - private _createDataSource():IDataSource { + private _createDataSource(): IDataSource { return { getWidth: () => { return this._width; @@ -986,7 +984,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif }; } - private _setStrategy(newStrategy:IDiffEditorWidgetStyle): void { + private _setStrategy(newStrategy: IDiffEditorWidgetStyle): void { if (this._strategy) { this._strategy.dispose(); } @@ -1001,7 +999,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif this._measureDomElement(true); } - private _getLineChangeAtOrBeforeLineNumber(lineNumber: number, startLineNumberExtractor:(lineChange:editorCommon.ILineChange)=>number): editorCommon.ILineChange { + private _getLineChangeAtOrBeforeLineNumber(lineNumber: number, startLineNumberExtractor: (lineChange: editorCommon.ILineChange) => number): editorCommon.ILineChange { if (this._lineChanges.length === 0 || lineNumber < startLineNumberExtractor(this._lineChanges[0])) { // There are no changes or `lineNumber` is before the first change return null; @@ -1045,7 +1043,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif return modifiedEquivalentLineNumber + Math.min(delta, lineChangeModifiedLength); } - return modifiedEquivalentLineNumber + lineChangeModifiedLength - lineChangeOriginalLength + delta ; + return modifiedEquivalentLineNumber + lineChangeModifiedLength - lineChangeOriginalLength + delta; } private _getEquivalentLineForModifiedLineNumber(lineNumber: number): number { @@ -1067,10 +1065,10 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif return originalEquivalentLineNumber + Math.min(delta, lineChangeOriginalLength); } - return originalEquivalentLineNumber + lineChangeOriginalLength - lineChangeModifiedLength + delta ; + return originalEquivalentLineNumber + lineChangeOriginalLength - lineChangeModifiedLength + delta; } - public getDiffLineInformationForOriginal(lineNumber:number): editorCommon.IDiffLineInformation { + public getDiffLineInformationForOriginal(lineNumber: number): editorCommon.IDiffLineInformation { if (!this._lineChanges) { // Cannot answer that which I don't know return null; @@ -1080,7 +1078,7 @@ export class DiffEditorWidget extends EventEmitter implements editorBrowser.IDif }; } - public getDiffLineInformationForModified(lineNumber:number): editorCommon.IDiffLineInformation { + public getDiffLineInformationForModified(lineNumber: number): editorCommon.IDiffLineInformation { if (!this._lineChanges) { // Cannot answer that which I don't know return null; @@ -1103,13 +1101,13 @@ interface IDataSource { class DiffEditorWidgetStyle { - _dataSource:IDataSource; + _dataSource: IDataSource; - constructor(dataSource:IDataSource) { + constructor(dataSource: IDataSource) { this._dataSource = dataSource; } - public getEditorsDiffDecorations(lineChanges:editorCommon.ILineChange[], ignoreTrimWhitespace:boolean, originalWhitespaces:editorCommon.IEditorWhitespace[], modifiedWhitespaces:editorCommon.IEditorWhitespace[], originalEditor:editorBrowser.ICodeEditor, modifiedEditor:editorBrowser.ICodeEditor): IEditorsDiffDecorationsWithZones { + public getEditorsDiffDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, originalWhitespaces: editorCommon.IEditorWhitespace[], modifiedWhitespaces: editorCommon.IEditorWhitespace[], originalEditor: editorBrowser.ICodeEditor, modifiedEditor: editorBrowser.ICodeEditor): IEditorsDiffDecorationsWithZones { // Get view zones modifiedWhitespaces = modifiedWhitespaces.sort((a, b) => { return a.afterLineNumber - b.afterLineNumber; @@ -1137,15 +1135,15 @@ class DiffEditorWidgetStyle { }; } - _getViewZones(lineChanges:editorCommon.ILineChange[], originalForeignVZ:editorCommon.IEditorWhitespace[], modifiedForeignVZ:editorCommon.IEditorWhitespace[], originalEditor:editorBrowser.ICodeEditor, modifiedEditor:editorBrowser.ICodeEditor): IEditorsZones { + _getViewZones(lineChanges: editorCommon.ILineChange[], originalForeignVZ: editorCommon.IEditorWhitespace[], modifiedForeignVZ: editorCommon.IEditorWhitespace[], originalEditor: editorBrowser.ICodeEditor, modifiedEditor: editorBrowser.ICodeEditor): IEditorsZones { return null; } - _getOriginalEditorDecorations(lineChanges:editorCommon.ILineChange[], ignoreTrimWhitespace:boolean, originalEditor:editorBrowser.ICodeEditor, modifiedEditor:editorBrowser.ICodeEditor): IEditorDiffDecorations { + _getOriginalEditorDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, originalEditor: editorBrowser.ICodeEditor, modifiedEditor: editorBrowser.ICodeEditor): IEditorDiffDecorations { return null; } - _getModifiedEditorDecorations(lineChanges:editorCommon.ILineChange[], ignoreTrimWhitespace:boolean, originalEditor:editorBrowser.ICodeEditor, modifiedEditor:editorBrowser.ICodeEditor): IEditorDiffDecorations { + _getModifiedEditorDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, originalEditor: editorBrowser.ICodeEditor, modifiedEditor: editorBrowser.ICodeEditor): IEditorDiffDecorations { return null; } } @@ -1178,11 +1176,11 @@ class ForeignViewZonesIterator { abstract class ViewZonesComputer { - private lineChanges:editorCommon.ILineChange[]; - private originalForeignVZ:editorCommon.IEditorWhitespace[]; - private modifiedForeignVZ:editorCommon.IEditorWhitespace[]; + private lineChanges: editorCommon.ILineChange[]; + private originalForeignVZ: editorCommon.IEditorWhitespace[]; + private modifiedForeignVZ: editorCommon.IEditorWhitespace[]; - constructor(lineChanges:editorCommon.ILineChange[], originalForeignVZ:editorCommon.IEditorWhitespace[], modifiedForeignVZ:editorCommon.IEditorWhitespace[]) { + constructor(lineChanges: editorCommon.ILineChange[], originalForeignVZ: editorCommon.IEditorWhitespace[], modifiedForeignVZ: editorCommon.IEditorWhitespace[]) { this.lineChanges = lineChanges; this.originalForeignVZ = originalForeignVZ; this.modifiedForeignVZ = modifiedForeignVZ; @@ -1194,27 +1192,27 @@ abstract class ViewZonesComputer { modified: [] }; - var i:number, - length:number, - lineChange:editorCommon.ILineChange; + var i: number, + length: number, + lineChange: editorCommon.ILineChange; var stepOriginal: IMyViewZone[], stepModified: IMyViewZone[], stepOriginalIndex: number, stepModifiedIndex: number, - lineChangeModifiedLength:number = 0, - lineChangeOriginalLength:number = 0, + lineChangeModifiedLength: number = 0, + lineChangeOriginalLength: number = 0, originalEquivalentLineNumber: number = 0, modifiedEquivalentLineNumber: number = 0, originalEndEquivalentLineNumber: number = 0, modifiedEndEquivalentLineNumber: number = 0, viewZoneLineNumber: number = 0; - var sortMyViewZones = (a:IMyViewZone, b:IMyViewZone) => { + var sortMyViewZones = (a: IMyViewZone, b: IMyViewZone) => { return a.afterLineNumber - b.afterLineNumber; }; - var addAndCombineIfPossible = (destination:editorBrowser.IViewZone[], item:IMyViewZone) => { + var addAndCombineIfPossible = (destination: editorBrowser.IViewZone[], item: IMyViewZone) => { if (item.domNode === null && destination.length > 0) { var lastItem = destination[destination.length - 1]; if (lastItem.afterLineNumber === item.afterLineNumber && lastItem.domNode === null) { @@ -1356,7 +1354,7 @@ abstract class ViewZonesComputer { // ---------------------------- END EMIT MINIMAL VIEW ZONES } - var ensureDomNode = (z:IMyViewZone) => { + var ensureDomNode = (z: IMyViewZone) => { if (!z.domNode) { z.domNode = createFakeLinesDiv(); } @@ -1368,9 +1366,9 @@ abstract class ViewZonesComputer { return result; } - protected abstract _produceOriginalFromDiff(lineChange:editorCommon.ILineChange, lineChangeOriginalLength:number, lineChangeModifiedLength:number): IMyViewZone; + protected abstract _produceOriginalFromDiff(lineChange: editorCommon.ILineChange, lineChangeOriginalLength: number, lineChangeModifiedLength: number): IMyViewZone; - protected abstract _produceModifiedFromDiff(lineChange:editorCommon.ILineChange, lineChangeOriginalLength:number, lineChangeModifiedLength:number): IMyViewZone; + protected abstract _produceModifiedFromDiff(lineChange: editorCommon.ILineChange, lineChangeOriginalLength: number, lineChangeModifiedLength: number): IMyViewZone; } class DiffEdtorWidgetSideBySide extends DiffEditorWidgetStyle implements IDiffEditorWidgetStyle, IVerticalSashLayoutProvider { @@ -1378,12 +1376,12 @@ class DiffEdtorWidgetSideBySide extends DiffEditorWidgetStyle implements IDiffEd static MINIMUM_EDITOR_WIDTH = 100; private _disableSash: boolean; - private _sash:Sash; - private _sashRatio:number; - private _sashPosition:number; - private _startSashPosition:number; + private _sash: Sash; + private _sashRatio: number; + private _sashPosition: number; + private _startSashPosition: number; - constructor(dataSource:IDataSource, enableSplitViewResizing:boolean) { + constructor(dataSource: IDataSource, enableSplitViewResizing: boolean) { super(dataSource); this._disableSash = (enableSplitViewResizing === false); @@ -1405,7 +1403,7 @@ class DiffEdtorWidgetSideBySide extends DiffEditorWidgetStyle implements IDiffEd this._sash.dispose(); } - public setEnableSplitViewResizing(enableSplitViewResizing:boolean): void { + public setEnableSplitViewResizing(enableSplitViewResizing: boolean): void { var newDisableSash = (enableSplitViewResizing === false); if (this._disableSash !== newDisableSash) { this._disableSash = newDisableSash; @@ -1418,7 +1416,7 @@ class DiffEdtorWidgetSideBySide extends DiffEditorWidgetStyle implements IDiffEd } } - public layout(sashRatio:number = this._sashRatio): number { + public layout(sashRatio: number = this._sashRatio): number { var w = this._dataSource.getWidth(); var contentWidth = w - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH; @@ -1451,7 +1449,7 @@ class DiffEdtorWidgetSideBySide extends DiffEditorWidgetStyle implements IDiffEd this._startSashPosition = this._sashPosition; } - private onSashDrag(e:ISashEvent): void { + private onSashDrag(e: ISashEvent): void { var w = this._dataSource.getWidth(); var contentWidth = w - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH; var sashPosition = this.layout((this._startSashPosition + (e.currentX - e.startX)) / contentWidth); @@ -1483,26 +1481,26 @@ class DiffEdtorWidgetSideBySide extends DiffEditorWidgetStyle implements IDiffEd return this._dataSource.getHeight(); } - _getViewZones(lineChanges:editorCommon.ILineChange[], originalForeignVZ:editorCommon.IEditorWhitespace[], modifiedForeignVZ:editorCommon.IEditorWhitespace[], originalEditor:editorBrowser.ICodeEditor, modifiedEditor:editorBrowser.ICodeEditor): IEditorsZones { + _getViewZones(lineChanges: editorCommon.ILineChange[], originalForeignVZ: editorCommon.IEditorWhitespace[], modifiedForeignVZ: editorCommon.IEditorWhitespace[], originalEditor: editorBrowser.ICodeEditor, modifiedEditor: editorBrowser.ICodeEditor): IEditorsZones { var c = new SideBySideViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ); return c.getViewZones(); } - _getOriginalEditorDecorations(lineChanges:editorCommon.ILineChange[], ignoreTrimWhitespace:boolean, originalEditor:editorBrowser.ICodeEditor, modifiedEditor:editorBrowser.ICodeEditor): IEditorDiffDecorations { + _getOriginalEditorDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, originalEditor: editorBrowser.ICodeEditor, modifiedEditor: editorBrowser.ICodeEditor): IEditorDiffDecorations { - var result:IEditorDiffDecorations = { - decorations: [], - overviewZones: [] - }, - i:number, - length:number, - j:number, - lengthJ:number, - lineChange:editorCommon.ILineChange, - charChange:editorCommon.ICharChange, - lineNumber:number, - startColumn:number, - endColumn:number, + var result: IEditorDiffDecorations = { + decorations: [], + overviewZones: [] + }, + i: number, + length: number, + j: number, + lengthJ: number, + lineChange: editorCommon.ILineChange, + charChange: editorCommon.ICharChange, + lineNumber: number, + startColumn: number, + endColumn: number, originalModel = originalEditor.getModel(); for (i = 0, length = lineChanges.length; i < length; i++) { @@ -1554,21 +1552,21 @@ class DiffEdtorWidgetSideBySide extends DiffEditorWidgetStyle implements IDiffEd return result; } - _getModifiedEditorDecorations(lineChanges:editorCommon.ILineChange[], ignoreTrimWhitespace:boolean, originalEditor:editorBrowser.ICodeEditor, modifiedEditor:editorBrowser.ICodeEditor): IEditorDiffDecorations { + _getModifiedEditorDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, originalEditor: editorBrowser.ICodeEditor, modifiedEditor: editorBrowser.ICodeEditor): IEditorDiffDecorations { - var result:IEditorDiffDecorations = { - decorations: [], - overviewZones: [] - }, - i:number, - length:number, - j:number, - lengthJ:number, - lineChange:editorCommon.ILineChange, - charChange:editorCommon.ICharChange, - lineNumber:number, - startColumn:number, - endColumn:number, + var result: IEditorDiffDecorations = { + decorations: [], + overviewZones: [] + }, + i: number, + length: number, + j: number, + lengthJ: number, + lineChange: editorCommon.ILineChange, + charChange: editorCommon.ICharChange, + lineNumber: number, + startColumn: number, + endColumn: number, modifiedModel = modifiedEditor.getModel(); for (i = 0, length = lineChanges.length; i < length; i++) { @@ -1622,11 +1620,11 @@ class DiffEdtorWidgetSideBySide extends DiffEditorWidgetStyle implements IDiffEd class SideBySideViewZonesComputer extends ViewZonesComputer { - constructor(lineChanges:editorCommon.ILineChange[], originalForeignVZ:editorCommon.IEditorWhitespace[], modifiedForeignVZ:editorCommon.IEditorWhitespace[]) { + constructor(lineChanges: editorCommon.ILineChange[], originalForeignVZ: editorCommon.IEditorWhitespace[], modifiedForeignVZ: editorCommon.IEditorWhitespace[]) { super(lineChanges, originalForeignVZ, modifiedForeignVZ); } - _produceOriginalFromDiff(lineChange:editorCommon.ILineChange, lineChangeOriginalLength:number, lineChangeModifiedLength:number): IMyViewZone { + _produceOriginalFromDiff(lineChange: editorCommon.ILineChange, lineChangeOriginalLength: number, lineChangeModifiedLength: number): IMyViewZone { if (lineChangeModifiedLength > lineChangeOriginalLength) { return { afterLineNumber: Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber), @@ -1637,7 +1635,7 @@ class SideBySideViewZonesComputer extends ViewZonesComputer { return null; } - _produceModifiedFromDiff(lineChange:editorCommon.ILineChange, lineChangeOriginalLength:number, lineChangeModifiedLength:number): IMyViewZone { + _produceModifiedFromDiff(lineChange: editorCommon.ILineChange, lineChangeOriginalLength: number, lineChangeModifiedLength: number): IMyViewZone { if (lineChangeOriginalLength > lineChangeModifiedLength) { return { afterLineNumber: Math.max(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber), @@ -1651,16 +1649,16 @@ class SideBySideViewZonesComputer extends ViewZonesComputer { class DiffEdtorWidgetInline extends DiffEditorWidgetStyle implements IDiffEditorWidgetStyle { - private toDispose:IDisposable[]; + private toDispose: IDisposable[]; private decorationsLeft: number; - constructor(dataSource:IDataSource, enableSplitViewResizing:boolean) { + constructor(dataSource: IDataSource, enableSplitViewResizing: boolean) { super(dataSource); this.decorationsLeft = dataSource.getOriginalEditor().getLayoutInfo().decorationsLeft; this.toDispose = []; - this.toDispose.push(dataSource.getOriginalEditor().onDidLayoutChange((layoutInfo:editorCommon.EditorLayoutInfo) => { + this.toDispose.push(dataSource.getOriginalEditor().onDidLayoutChange((layoutInfo: editorCommon.EditorLayoutInfo) => { if (this.decorationsLeft !== layoutInfo.decorationsLeft) { this.decorationsLeft = layoutInfo.decorationsLeft; dataSource.relayoutEditors(); @@ -1672,23 +1670,23 @@ class DiffEdtorWidgetInline extends DiffEditorWidgetStyle implements IDiffEditor this.toDispose = dispose(this.toDispose); } - public setEnableSplitViewResizing(enableSplitViewResizing:boolean): void { + public setEnableSplitViewResizing(enableSplitViewResizing: boolean): void { // Nothing to do.. } - _getViewZones(lineChanges:editorCommon.ILineChange[], originalForeignVZ:editorCommon.IEditorWhitespace[], modifiedForeignVZ:editorCommon.IEditorWhitespace[], originalEditor:editorBrowser.ICodeEditor, modifiedEditor:editorBrowser.ICodeEditor): IEditorsZones { + _getViewZones(lineChanges: editorCommon.ILineChange[], originalForeignVZ: editorCommon.IEditorWhitespace[], modifiedForeignVZ: editorCommon.IEditorWhitespace[], originalEditor: editorBrowser.ICodeEditor, modifiedEditor: editorBrowser.ICodeEditor): IEditorsZones { var computer = new InlineViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor); return computer.getViewZones(); } - _getOriginalEditorDecorations(lineChanges:editorCommon.ILineChange[], ignoreTrimWhitespace:boolean, originalEditor:editorBrowser.ICodeEditor, modifiedEditor:editorBrowser.ICodeEditor): IEditorDiffDecorations { - var result:IEditorDiffDecorations = { - decorations: [], - overviewZones: [] - }, - i:number, - length:number, - lineChange:editorCommon.ILineChange; + _getOriginalEditorDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, originalEditor: editorBrowser.ICodeEditor, modifiedEditor: editorBrowser.ICodeEditor): IEditorDiffDecorations { + var result: IEditorDiffDecorations = { + decorations: [], + overviewZones: [] + }, + i: number, + length: number, + lineChange: editorCommon.ILineChange; for (i = 0, length = lineChanges.length; i < length; i++) { lineChange = lineChanges[i]; @@ -1709,21 +1707,21 @@ class DiffEdtorWidgetInline extends DiffEditorWidgetStyle implements IDiffEditor return result; } - _getModifiedEditorDecorations(lineChanges:editorCommon.ILineChange[], ignoreTrimWhitespace:boolean, originalEditor:editorBrowser.ICodeEditor, modifiedEditor:editorBrowser.ICodeEditor): IEditorDiffDecorations { + _getModifiedEditorDecorations(lineChanges: editorCommon.ILineChange[], ignoreTrimWhitespace: boolean, originalEditor: editorBrowser.ICodeEditor, modifiedEditor: editorBrowser.ICodeEditor): IEditorDiffDecorations { - var result:IEditorDiffDecorations = { - decorations: [], - overviewZones: [] - }, - i:number, - length:number, - lineChange:editorCommon.ILineChange, - j:number, - lengthJ:number, + var result: IEditorDiffDecorations = { + decorations: [], + overviewZones: [] + }, + i: number, + length: number, + lineChange: editorCommon.ILineChange, + j: number, + lengthJ: number, charChange: editorCommon.ICharChange, - lineNumber:number, - startColumn:number, - endColumn:number, + lineNumber: number, + startColumn: number, + endColumn: number, modifiedModel = modifiedEditor.getModel(); for (i = 0, length = lineChanges.length; i < length; i++) { @@ -1783,30 +1781,30 @@ class DiffEdtorWidgetInline extends DiffEditorWidgetStyle implements IDiffEditor class InlineViewZonesComputer extends ViewZonesComputer { - private originalModel:editorCommon.IModel; - private modifiedEditorConfiguration:editorCommon.InternalEditorOptions; - private modifiedEditorTabSize:number; + private originalModel: editorCommon.IModel; + private modifiedEditorConfiguration: editorCommon.InternalEditorOptions; + private modifiedEditorTabSize: number; - constructor(lineChanges:editorCommon.ILineChange[], originalForeignVZ:editorCommon.IEditorWhitespace[], modifiedForeignVZ:editorCommon.IEditorWhitespace[], originalEditor:editorBrowser.ICodeEditor, modifiedEditor:editorBrowser.ICodeEditor) { + constructor(lineChanges: editorCommon.ILineChange[], originalForeignVZ: editorCommon.IEditorWhitespace[], modifiedForeignVZ: editorCommon.IEditorWhitespace[], originalEditor: editorBrowser.ICodeEditor, modifiedEditor: editorBrowser.ICodeEditor) { super(lineChanges, originalForeignVZ, modifiedForeignVZ); this.originalModel = originalEditor.getModel(); this.modifiedEditorConfiguration = modifiedEditor.getConfiguration(); this.modifiedEditorTabSize = modifiedEditor.getModel().getOptions().tabSize; } - _produceOriginalFromDiff(lineChange:editorCommon.ILineChange, lineChangeOriginalLength:number, lineChangeModifiedLength:number): IMyViewZone { + _produceOriginalFromDiff(lineChange: editorCommon.ILineChange, lineChangeOriginalLength: number, lineChangeModifiedLength: number): IMyViewZone { return { - afterLineNumber:Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber), + afterLineNumber: Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber), heightInLines: lineChangeModifiedLength, domNode: document.createElement('div') }; } - _produceModifiedFromDiff(lineChange:editorCommon.ILineChange, lineChangeOriginalLength:number, lineChangeModifiedLength:number): IMyViewZone { - var decorations:InlineDecoration[] = [], - j:number, - lengthJ:number, - charChange:editorCommon.ICharChange; + _produceModifiedFromDiff(lineChange: editorCommon.ILineChange, lineChangeOriginalLength: number, lineChangeModifiedLength: number): IMyViewZone { + var decorations: InlineDecoration[] = [], + j: number, + lengthJ: number, + charChange: editorCommon.ICharChange; if (lineChange.charChanges) { for (j = 0, lengthJ = lineChange.charChanges.length; j < lengthJ; j++) { @@ -1839,7 +1837,7 @@ class InlineViewZonesComputer extends ViewZonesComputer { }; } - private renderOriginalLine(count:number, originalModel:editorCommon.IModel, config:editorCommon.InternalEditorOptions, tabSize:number, lineNumber:number, decorations:InlineDecoration[]): string[] { + private renderOriginalLine(count: number, originalModel: editorCommon.IModel, config: editorCommon.InternalEditorOptions, tabSize: number, lineNumber: number, decorations: InlineDecoration[]): string[] { let lineContent = originalModel.getLineContent(lineNumber); let lineTokens = new ViewLineTokens([new ViewLineToken(0, '')], 0, lineContent.length); @@ -1855,7 +1853,7 @@ class InlineViewZonesComputer extends ViewZonesComputer { parts.getParts() )); - let myResult:string[] = []; + let myResult: string[] = []; myResult.push('