From ff96c535faf19bdb6b84a32a7236dc7dfb95abf6 Mon Sep 17 00:00:00 2001 From: Erich Gamma Date: Fri, 25 Sep 2015 12:23:44 +0200 Subject: [PATCH 1/3] update to latest API --- .vscode/launch.json | 2 +- package.json | 108 +++- src/goCheck.ts | 8 +- src/goDeclaration.ts | 35 +- src/goExtraInfo.ts | 36 +- src/goFormat.ts | 45 +- src/goMain.ts | 101 ++-- src/goReferences.ts | 41 +- src/goRename.ts | 29 +- src/goSuggest.ts | 34 +- ticino.plugin.json | 49 -- typings/vscode.d.ts | 1189 ++++++++++++++++++------------------------ 12 files changed, 727 insertions(+), 950 deletions(-) delete mode 100644 ticino.plugin.json diff --git a/.vscode/launch.json b/.vscode/launch.json index a393a378e8..85adacb724 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -8,7 +8,7 @@ "runtimeExecutable": "${execPath}", // force VSCode to create a new window and pass this project as an additonal plugin location // add workspace path to %GOPATH% so that there is some meaningful contents - "args": [ "--new-window", "--extensionDevelopmentWorkspacePath=${workspaceRoot}" ], + "args": [ "--new-window", "--extensionDevelopmentPath=${workspaceRoot}" ], "stopOnEntry": false, "sourceMaps": true, "outDir": "out" diff --git a/package.json b/package.json index 33e8464ce4..37da0537ea 100644 --- a/package.json +++ b/package.json @@ -1,22 +1,88 @@ { - "name": "go-code", - "version": "1.0.0", - "description": "Go support for Visual Studio Code", - "author": { - "name": "Microsoft Corporation" - }, - "private": true, - "repository": { - "type": "git", - "url": "https://monacotools.visualstudio.com/DefaultCollection/Monaco/_git/go-code" - }, - "scripts": { - "prepublish": "tsc" - }, - "dependencies": { - "json-rpc2": "^1.0.2" - }, - "devDependencies": { - "typescript": "^1.6.2" - } -} + "name": "go-code", + "version": "1.0.0", + "description": "Go support for Visual Studio Code", + "author": { + "name": "Microsoft Corporation" + }, + "private": true, + "repository": { + "type": "git", + "url": "https://monacotools.visualstudio.com/DefaultCollection/Monaco/_git/go-code" + }, + "scripts": { + "prepublish": "tsc" + }, + "extensionDependencies": [ + "go" + ], + "dependencies": { + "json-rpc2": "^1.0.2" + }, + "devDependencies": { + "typescript": "^1.6.2" + }, + "engines": { + "vscode": "*" + }, + "activationEvents": [ + "textModel:go" + ], + "main": "./out/goMain", + "contributes": { + "language": + [{ + "id": "go", + "extensions": [ + ".go" + ], + "aliases": [ + "Go" + ] + } + ], + "debugAdapter": [ + { + "type": "go", + "enableBreakpointsFor": { + "languageIds": [ + "go" + ] + }, + "program": "./out/debugAdapter/openDebugMock.js", + "runtime": "node" + } + ], + "configuration": { + "type": "object", + "title": "Go configuration", + "properties": { + "go.buildOnSave": { + "type": "boolean", + "default": true, + "description": "Run 'go build'/'go test' on save." + }, + "go.lintOnSave": { + "type": "boolean", + "default": true, + "description": "Run 'golint' on save." + }, + "go.vetOnSave": { + "type": "boolean", + "default": true, + "description": "Run 'go tool vet' on save." + }, + "go.formatTool": { + "type": "string", + "default": "goreturns", + "description": "Pick 'gofmt', 'goimports' or 'goreturns' to run on format." + }, + "go.gopath": { + "type": "string", + "default": null, + "description": "Specifies the GOPATH to use when no environment variable is set." + } + } + } + } +} \ No newline at end of file diff --git a/src/goCheck.ts b/src/goCheck.ts index 75cd931e95..2266a17148 100644 --- a/src/goCheck.ts +++ b/src/goCheck.ts @@ -19,7 +19,7 @@ if(process.env.GOROOT) { go = pathparts.map(dir => path.join(dir, 'go' + (os.platform() == "win32" ? ".exe" : ""))).filter(candidate => fs.existsSync(candidate))[0]; } if(!go) { - vscode.shell.showInformationMessage("No 'go' binary could be found on PATH or in GOROOT. Set location manual in 'go.goroot' setting."); + vscode.window.showInformationMessage("No 'go' binary could be found on PATH or in GOROOT. Set location manual in 'go.goroot' setting."); } export interface ICheckResult { @@ -40,7 +40,7 @@ export function check(filename: string, buildOnSave = true, lintOnSave = true, v cp.execFile(go, args, {cwd: cwd}, (err, stdout, stderr) => { try { if (err && (err).code == "ENOENT") { - vscode.shell.showInformationMessage("The 'go' compiler is not available. Install Go from http://golang.org/dl/."); + vscode.window.showInformationMessage("The 'go' compiler is not available. Install Go from http://golang.org/dl/."); return resolve([]); } var lines = stderr.toString().split('\n'); @@ -65,7 +65,7 @@ export function check(filename: string, buildOnSave = true, lintOnSave = true, v cp.execFile(golint, [filename], {cwd: cwd}, (err, stdout, stderr) => { try { if (err && (err).code == "ENOENT") { - vscode.shell.showInformationMessage("The 'golint' command is not available. Use 'go get -u github.com/golang/lint/golint' to install."); + vscode.window.showInformationMessage("The 'golint' command is not available. Use 'go get -u github.com/golang/lint/golint' to install."); return resolve([]); } var lines = stdout.toString().split('\n'); @@ -89,7 +89,7 @@ export function check(filename: string, buildOnSave = true, lintOnSave = true, v cp.execFile(go, ["tool", "vet", filename], {cwd: cwd}, (err, stdout, stderr) => { try { if (err && (err).code == "ENOENT") { - vscode.shell.showInformationMessage("The 'go tool vet' compiler is not available. Install Go from http://golang.org/dl/."); + vscode.window.showInformationMessage("The 'go tool vet' compiler is not available. Install Go from http://golang.org/dl/."); return resolve([]); } var lines = stdout.toString().split('\n'); diff --git a/src/goDeclaration.ts b/src/goDeclaration.ts index 01020a97bf..8cb82951ff 100644 --- a/src/goDeclaration.ts +++ b/src/goDeclaration.ts @@ -10,34 +10,23 @@ import path = require('path'); class DeclartionSupport implements vscode.Modes.IDeclarationSupport { - private modelService: vscode.Services.IModelService; - - constructor(modelService: vscode.Services.IModelService) { - this.modelService = modelService; - } - - public findDeclaration(resource:vscode.Uri, position:vscode.IPosition, token: vscode.CancellationToken):Promise { + public findDeclaration(document:vscode.Document, position:vscode.Position, token: vscode.CancellationToken):Thenable { return new Promise((resolve, reject) => { - var filename = resource.fsPath; - var model = this.modelService.getModel(resource); - var wordAtPosition = model.getWordAtPosition(position); + + var wordAtPosition = document.getWordRangeAtPosition(position); // compute the file offset for position - var offset = model.getValueInRange({ - startLineNumber: 0, - startColumn: 0, - endLineNumber: position.lineNumber, - endColumn: position.column - }).length; + var range = new vscode.Range(0, 0, position.line, position.column); + var offset = document.getTextInRange(range).length; var godef = path.join(process.env["GOPATH"], "bin", "godef"); // Spawn `godef` process - var p = cp.execFile(godef, ["-t", "-i", "-f", filename, "-o", offset.toString()], {}, (err, stdout, stderr) => { + var p = cp.execFile(godef, ["-t", "-i", "-f", document.getUri().fsPath, "-o", offset.toString()], {}, (err, stdout, stderr) => { try { if (err && (err).code == "ENOENT") { - vscode.shell.showInformationMessage("The 'godef' command is not available. Use 'go get -u github.com/rogpeppe/godef' to install."); + vscode.window.showInformationMessage("The 'godef' command is not available. Use 'go get -u github.com/rogpeppe/godef' to install."); } if (err) return resolve(null); var result = stdout.toString(); @@ -48,20 +37,16 @@ class DeclartionSupport implements vscode.Modes.IDeclarationSupport { if(!match) return resolve(null); var [_, file, line, col] = match; var definitionResource = vscode.Uri.file(file); + var range = new vscode.Range(+line, +col, +line, +col + 1); return resolve({ resource: definitionResource, - range: { - startLineNumber: +line, - startColumn: +col, - endLineNumber: +line, - endColumn: +col + 1 - } + range }); } catch(e) { reject(e); } }); - p.stdin.end(model.getValue()); + p.stdin.end(document.getText()); }); } } diff --git a/src/goExtraInfo.ts b/src/goExtraInfo.ts index 179032a958..b518aac7dd 100644 --- a/src/goExtraInfo.ts +++ b/src/goExtraInfo.ts @@ -10,26 +10,16 @@ import path = require('path'); class ExtraInfoSupport implements vscode.Modes.IExtraInfoSupport { - private modelService: vscode.Services.IModelService; - constructor(modelService: vscode.Services.IModelService) { - this.modelService = modelService; - } - - public computeInfo(resource:vscode.Uri, position:vscode.IPosition, token: vscode.CancellationToken): Promise { + public computeInfo(document:vscode.Document, position:vscode.Position, token: vscode.CancellationToken): Promise { return new Promise((resolve, reject) => { - var filename = resource.fsPath; - var model = this.modelService.getModel(resource); - var wordAtPosition = model.getWordAtPosition(position); + var filename = document.getUri().fsPath; + var wordAtPosition = document.getWordRangeAtPosition(position); // compute the file offset for position - var offset = model.getValueInRange({ - startLineNumber: 0, - startColumn: 0, - endLineNumber: position.lineNumber, - endColumn: position.column - }).length; + var range = new vscode.Range(0, 0, position.line, position.column); + var offset = document.getTextInRange(range).length; var godef = path.join(process.env["GOPATH"], "bin", "godef"); @@ -37,29 +27,29 @@ class ExtraInfoSupport implements vscode.Modes.IExtraInfoSupport { var p = cp.execFile(godef, ["-t", "-i", "-f", filename, "-o", offset.toString()], {}, (err, stdout, stderr) => { try { if (err && (err).code == "ENOENT") { - vscode.shell.showInformationMessage("The 'godef' command is not available. Use 'go get -u github.com/rogpeppe/godef' to install."); + vscode.window.showInformationMessage("The 'godef' command is not available. Use 'go get -u github.com/rogpeppe/godef' to install."); } if (err) return resolve(null); var result = stdout.toString(); var lines = result.split('\n'); if(lines.length > 10) lines[9] = "..."; var text = lines.slice(1,10).join('\n'); + var range = new vscode.Range( + position.line, + wordAtPosition ? wordAtPosition.start.column : position.column, + position.line, + wordAtPosition ? wordAtPosition.end.column : position.column); return resolve({ htmlContent: [ { formattedText: text } ], - range: { - startLineNumber: position.lineNumber, - startColumn: wordAtPosition ? wordAtPosition.startColumn : position.column, - endLineNumber: position.lineNumber, - endColumn: wordAtPosition ? wordAtPosition.endColumn : position.column - } + range }); } catch(e) { reject(e); } }); - p.stdin.end(model.getValue()); + p.stdin.end(document.getText()); }); } } diff --git a/src/goFormat.ts b/src/goFormat.ts index e9aa0f40b2..af5f4ed0b1 100644 --- a/src/goFormat.ts +++ b/src/goFormat.ts @@ -10,59 +10,64 @@ import path = require('path'); class FormattingSupport implements vscode.Modes.IFormattingSupport { - private modelService: vscode.Services.IModelService; private formatCommand = "goreturns"; public autoFormatTriggerCharacters: string[] = [';', '}', '\n']; - constructor(modelService: vscode.Services.IModelService, configurationService: vscode.Services.IConfigurationService) { - this.modelService = modelService; - configurationService.loadConfiguration('go').then(config => { - if(config.formatTool) { - this.formatCommand = config.formatTool; + constructor() { + vscode.plugins.getConfigurationObject('go').getValue('formatTool').then(formatTool => { + if(formatTool) { + this.formatCommand = formatTool; } }); } - public formatDocument(resource: vscode.Uri, options: vscode.Modes.IFormattingOptions, token: vscode.CancellationToken):Thenable { - // TODO: We don't really need to save all the buffers, just the one for 'resource'. + // TODO: work around bug that Code always calls formatRange + public formatRange(document: vscode.Document, range: vscode.Range, options: vscode.Modes.IFormattingOptions, token: vscode.CancellationToken): Thenable { + return this.formatDocument(document, options, token) + } + + public formatDocument(document: vscode.Document, options: vscode.Modes.IFormattingOptions, token: vscode.CancellationToken): Thenable { + // TODO: We don't really need to save all the buffers, just the one for 'resource. return vscode.workspace.anyDirty().then(anyDirty => { if (anyDirty) { vscode.workspace.saveAll(false).then(() => { - return this.doFormatDocument(resource, options, token); + return this.doFormatDocument(document, options, token); }); } - return this.doFormatDocument(resource, options, token); + return this.doFormatDocument(document, options, token); }); } - private doFormatDocument(resource: vscode.Uri, options: vscode.Modes.IFormattingOptions, token: vscode.CancellationToken):Thenable { + private doFormatDocument(document: vscode.Document, options: vscode.Modes.IFormattingOptions, token: vscode.CancellationToken):Thenable { return new Promise((resolve, reject) => { - var filename = resource.fsPath; - var model = this.modelService.getModel(resource); + var filename = document.getUri().fsPath; var goreturns = path.join(process.env["GOPATH"], "bin", this.formatCommand); cp.execFile(goreturns, [filename], {}, (err, stdout, stderr) => { try { if (err && (err).code == "ENOENT") { - vscode.shell.showInformationMessage("The 'goreturns' command is not available. Use 'go get -u sourcegraph.com/sqs/goreturns' to install."); + vscode.window.showInformationMessage("The 'goreturns' command is not available. Use 'go get -u sourcegraph.com/sqs/goreturns' to install."); return resolve(null); } if (err) return reject("Cannot format due to syntax errors."); var result = stdout.toString(); // TODO: Should use `-d` option to get a diff and then compute the // specific edits instead of replace whole buffer - var lastLine = model.getLineCount(); - var lastLineLastCol = model.getLineMaxColumn(lastLine); - return resolve([{ - text: result, - range: { + var lastLine = document.getLineCount(); + var lastLineLastCol = document.getLineMaxColumn(lastLine); + // API TODO: ISingleEditOperation is using IRange instead of Range + //var range = new vscode.Range(1, 1, lastLine, lastLineLastCol); + var range = { startLineNumber: 1, startColumn: 1, endLineNumber: lastLine, endColumn: lastLineLastCol - } + }; + return resolve([{ + text: result, + range }]); } catch(e) { reject(e); diff --git a/src/goMain.ts b/src/goMain.ts index d8c94e569e..fcea552436 100644 --- a/src/goMain.ts +++ b/src/goMain.ts @@ -18,12 +18,12 @@ import {check, ICheckResult} from './goCheck'; import vscode = require('vscode'); export function activate() { - vscode.Modes.SuggestSupport.register('go', new SuggestSupport(vscode.Services.ModelService)); - vscode.Modes.ExtraInfoSupport.register('go', new ExtraInfoSupport(vscode.Services.ModelService)); - vscode.Modes.DeclarationSupport.register('go', new DeclarationSupport(vscode.Services.ModelService)); - vscode.Modes.ReferenceSupport.register('go', new ReferencesSupport(vscode.Services.ModelService)); - vscode.Modes.FormattingSupport.register('go', new FormattingSupport(vscode.Services.ModelService, vscode.Services.ConfigurationService)); - vscode.Modes.RenameSupport.register('go', new RenameSupport(vscode.Services.ModelService)); + vscode.Modes.SuggestSupport.register('go', new SuggestSupport()); + vscode.Modes.ExtraInfoSupport.register('go', new ExtraInfoSupport()); + vscode.Modes.DeclarationSupport.register('go', new DeclarationSupport()); + vscode.Modes.ReferenceSupport.register('go', new ReferencesSupport()); + vscode.Modes.FormattingSupport.register('go', new FormattingSupport()); + vscode.Modes.RenameSupport.register('go', new RenameSupport()); setupGoPathAndOfferToInstallTools(); startBuildOnSaveWatcher(); @@ -31,11 +31,11 @@ export function activate() { function setupGoPathAndOfferToInstallTools() { // TODO: There should be a better way to do this? - vscode.Services.ConfigurationService.loadConfiguration('go').then((config = {}) => { + vscode.plugins.getConfigurationObject('go').getValue('gopath').then(gopath => { // Make sure GOPATH is set - if(!process.env["GOPATH"] && config.gopath) { - process.env["GOPATH"] = config.gopath; + if(!process.env["GOPATH"] && gopath) { + process.env["GOPATH"] = gopath; } // Offer to install any missing tools @@ -63,13 +63,13 @@ function setupGoPathAndOfferToInstallTools() { }); } }); - + function promptForInstall(missing: string[], status: vscode.Disposable) { - vscode.shell.showInformationMessage("Some Go analysis tools are missing from your GOPATH. Would you like to install them?", { + vscode.window.showInformationMessage("Some Go analysis tools are missing from your GOPATH. Would you like to install them?", { title: "Install", command: () => { missing.forEach(tool => { - vscode.shell.runInTerminal("go", ["get", "-u", "-v", tool], { cwd: process.env['GOPATH'] }); + vscode.window.runInTerminal("go", ["get", "-u", "-v", tool], { cwd: process.env['GOPATH'] }); }); } }); @@ -78,53 +78,50 @@ function setupGoPathAndOfferToInstallTools() { }); } +let _diagnostics:vscode.Disposable = null; + +function deactivate() { + if (_diagnostics) { + _diagnostics.dispose(); + } +} + function startBuildOnSaveWatcher() { - function mapSeverityToMonacoSeverity(sev: string) { + function mapSeverityToVSCodeSeverity(sev: string) { switch(sev) { - case "error": return vscode.Services.Severity.Error; - case "warning": return vscode.Services.Severity.Warning; - default: return vscode.Services.Severity.Error; + case "error": return vscode.DiagnosticSeverity.Error; + case "warning": return vscode.DiagnosticSeverity.Warning; + default: return vscode.DiagnosticSeverity.Error; } } - vscode.Services.ConfigurationService.loadConfiguration('go').then((config = {}) => { - var watcher = vscode.Services.FileSystemEventService.createWatcher(); - watcher.onFileChange(fileSystemEvent => { - if(fileSystemEvent.resource.fsPath.indexOf('.go') !== -1) { - check(fileSystemEvent.resource.fsPath, config['buildOnSave'], config['lintOnSave'], config['vetOnSave']).then(errors => { - vscode.Services.MarkerService.changeAll('go', errors.map(error => { - var targetResource = vscode.Uri.file(error.file); - var model = vscode.Services.ModelService.getModel(targetResource); - var startColumn = 0; - var endColumn = 1; - if(model) { - var text = model.getValueInRange({ - startLineNumber: error.line, - endLineNumber: error.line, - startColumn: 0, - endColumn: model.getLineMaxColumn(error.line) - }); - var [_, leading, trailing] = /^(\s*).*(\s*)$/.exec(text); - startColumn = leading.length + 1; - endColumn = text.length - trailing.length + 1; - } - return { - resource: targetResource, - marker: { - severity: mapSeverityToMonacoSeverity(error.severity), - message: error.msg, - startLineNumber: error.line, - endLineNumber: error.line, - startColumn, - endColumn - } - }; - })); - }).catch(err => { - vscode.shell.showInformationMessage("Error: " + err); + vscode.plugins.getConfigurationObject('go').getValues().then((config = {}) => { + vscode.workspace.onDidSaveDocument(document => { + check(document.getUri().fsPath, config['buildOnSave'], config['lintOnSave'], config['vetOnSave']).then(errors => { + if (_diagnostics) { + _diagnostics.dispose(); + } + var diagnostics = errors.map(error => { + let targetResource = vscode.Uri.file(error.file); + let document = vscode.workspace.getDocument(targetResource); + let startColumn = 0; + let endColumn = 1; + if (document) { + let range = new vscode.Range(error.line, 0, error.line, document.getLineMaxColumn(error.line)); + let text = document.getTextInRange(range); + let [_, leading, trailing] = /^(\s*).*(\s*)$/.exec(text); + startColumn = leading.length + 1; + endColumn = text.length - trailing.length + 1; + } + let range = new vscode.Range(error.line, startColumn, error.line, endColumn); + let location = new vscode.Location(document.getUri(), range); + return new vscode.Diagnostic(mapSeverityToVSCodeSeverity(error.severity), location, error.msg); }); - } + _diagnostics = vscode.languages.addDiagnostics(diagnostics); + }).catch(err => { + vscode.window.showInformationMessage("Error: " + err); + }); }); }); } diff --git a/src/goReferences.ts b/src/goReferences.ts index d3a0c58ded..5cdead69a4 100644 --- a/src/goReferences.ts +++ b/src/goReferences.ts @@ -10,50 +10,39 @@ import path = require('path'); class ReferenceSupport implements vscode.Modes.IReferenceSupport { - private modelService: vscode.Services.IModelService; - - constructor(modelService: vscode.Services.IModelService) { - this.modelService = modelService; - } - - public findReferences(resource:vscode.Uri, position:vscode.IPosition, includeDeclaration:boolean, token: vscode.CancellationToken): Thenable { + public findReferences(document: vscode.Document, position:vscode.Position, includeDeclaration:boolean, token: vscode.CancellationToken): Thenable { return vscode.workspace.anyDirty().then(anyDirty => { if (anyDirty) { vscode.workspace.saveAll(false).then(() => { - return this.doFindReferences(resource, position, includeDeclaration, token); + return this.doFindReferences(document, position, includeDeclaration, token); }); } - return this.doFindReferences(resource, position, includeDeclaration, token); + return this.doFindReferences(document, position, includeDeclaration, token); }); } - private doFindReferences(resource:vscode.Uri, position:vscode.IPosition, includeDeclaration:boolean, token: vscode.CancellationToken): Thenable { + private doFindReferences(document:vscode.Document, position:vscode.Position, includeDeclaration:boolean, token: vscode.CancellationToken): Thenable { return new Promise((resolve, reject) => { - var filename = this.canonicalizeForWindows(resource.fsPath); + var filename = this.canonicalizeForWindows(document.getUri().fsPath); var cwd = path.dirname(filename) - var model = this.modelService.getModel(resource); var workspaceRoot = vscode.workspace.getPath(); // get current word - var wordAtPosition = model.getWordAtPosition(position); + var wordAtPosition = document.getWordRangeAtPosition(position); // compute the file offset for position - var offset = model.getValueInRange({ - startLineNumber: 0, - startColumn: 0, - endLineNumber: position.lineNumber, - endColumn: position.column - }).length; + var range = new vscode.Range(0, 0, position.line, position.column); + var offset = document.getTextInRange(range).length; var gofindreferences = path.join(process.env["GOPATH"], "bin", "go-find-references"); cp.execFile(gofindreferences, ["-file", filename, "-offset", offset.toString(), "-root", workspaceRoot], {}, (err, stdout, stderr) => { try { if (err && (err).code == "ENOENT") { - vscode.shell.showInformationMessage("The 'go-find-references' command is not available. Use 'go get -v github.com/lukehoban/go-find-references' to install."); + vscode.window.showInformationMessage("The 'go-find-references' command is not available. Use 'go get -v github.com/lukehoban/go-find-references' to install."); return resolve(null); } - + var lines = stdout.toString().split('\n'); var results: vscode.Modes.IReference[] = []; for(var i = 0; i < lines.length; i+=2) { @@ -62,14 +51,12 @@ class ReferenceSupport implements vscode.Modes.IReferenceSupport { if(!match) continue; var [_, file, lineStr, colStr] = match; var referenceResource = vscode.Uri.file(path.resolve(cwd, file)); + var range = new vscode.Range( + +lineStr, +colStr, +lineStr, +colStr + wordAtPosition.end.column - wordAtPosition.start.column + ); results.push({ resource: referenceResource, - range: { - startLineNumber: +lineStr, - startColumn: +colStr, - endLineNumber: +lineStr, - endColumn: +colStr + wordAtPosition.endColumn - wordAtPosition.startColumn - } + range }); } resolve(results); diff --git a/src/goRename.ts b/src/goRename.ts index b70a26731c..2fef308bc2 100644 --- a/src/goRename.ts +++ b/src/goRename.ts @@ -10,42 +10,31 @@ import path = require('path'); class RenameSupport implements vscode.Modes.IRenameSupport { - private modelService: vscode.Services.IModelService; - - constructor(modelService: vscode.Services.IModelService) { - this.modelService = modelService; - } - - public rename(resource:vscode.Uri, position:vscode.IPosition, newName: string, token: vscode.CancellationToken): Thenable { + public rename(document:vscode.Document, position:vscode.Position, newName: string, token: vscode.CancellationToken): Thenable { return vscode.workspace.anyDirty().then(anyDirty => { if (anyDirty) { vscode.workspace.saveAll(false).then(() => { - return this.doRename(resource, position, newName, token); + return this.doRename(document, position, newName, token); }); } - return this.doRename(resource, position, newName, token); + return this.doRename(document, position, newName, token); }); } - private doRename(resource:vscode.Uri, position:vscode.IPosition, newName: string, token: vscode.CancellationToken): Thenable { + private doRename(document:vscode.Document, position:vscode.Position, newName: string, token: vscode.CancellationToken): Thenable { return new Promise((resolve, reject) => { - var filename = this.canonicalizeForWindows(resource.fsPath); - var model = this.modelService.getModel(resource); + var filename = this.canonicalizeForWindows(document.getUri().fsPath); // compute the file offset for position - var offset = model.getValueInRange({ - startLineNumber: 0, - startColumn: 0, - endLineNumber: position.lineNumber, - endColumn: position.column - }).length; + var range = new vscode.Range(0, 0, position.line, position.column); + var offset = document.getTextInRange(range).length; var gorename = path.join(process.env["GOPATH"], "bin", "gorename"); cp.execFile(gorename, ["-offset", filename+":#"+offset, "-to", newName], {}, (err, stdout, stderr) => { try { if (err && (err).code == "ENOENT") { - vscode.shell.showInformationMessage("The 'gorename' command is not available. Use 'go get golang.org/x/tools/cmd/gorename' to install."); + vscode.window.showInformationMessage("The 'gorename' command is not available. Use 'go get golang.org/x/tools/cmd/gorename' to install."); return resolve(null); } if (err) return reject("Cannot rename due to errors: " + err); @@ -67,7 +56,7 @@ class RenameSupport implements vscode.Modes.IRenameSupport { var gopath: string = process.env['GOPATH'] if(!gopath) return filename; if(filename.toLowerCase().substring(0, gopath.length) != gopath.toLowerCase()) return filename; - return gopath + filename.slice(gopath.length); + return gopath + filename.slice(gopath.length); } } diff --git a/src/goSuggest.ts b/src/goSuggest.ts index bbabf93abc..f3765032a7 100644 --- a/src/goSuggest.ts +++ b/src/goSuggest.ts @@ -8,7 +8,7 @@ import vscode = require('vscode'); import cp = require('child_process'); import path = require('path'); -function monacoTypeFromGoCodeClass(kind: string): string { +function vscodeTypeFromGoCodeClass(kind: string): string { switch (kind) { case "const": case "package": @@ -33,31 +33,21 @@ class SuggestSupport implements vscode.Modes.ISuggestSupport { public triggerCharacters = ['.']; public excludeTokens = ['string', 'comment', 'numeric']; - private modelService: vscode.Services.IModelService; - - constructor(modelService: vscode.Services.IModelService) { - this.modelService = modelService; - } - - public suggest(resource: vscode.Uri, position: vscode.IPosition, token: vscode.CancellationToken): Promise { + public suggest(document: vscode.Document, position: vscode.Position, token: vscode.CancellationToken): Promise { return new Promise((resolve, reject) => { - var filename = resource.fsPath; - var model = this.modelService.getModel(resource); + var filename = document.getUri().fsPath; // get current word - var wordAtPosition = model.getWordAtPosition(position); + var wordAtPosition = document.getWordRangeAtPosition(position); + var word = document.getTextInRange(wordAtPosition); var currentWord = ''; - if (wordAtPosition && wordAtPosition.startColumn < position.column) { - currentWord = wordAtPosition.word.substr(0, position.column - wordAtPosition.startColumn); + if (wordAtPosition && wordAtPosition.start.column < position.column) { + currentWord = word.substr(0, position.column - wordAtPosition.start.column); } // compute the file offset for position - var offset = model.getValueInRange({ - startLineNumber: 0, - startColumn: 0, - endLineNumber: position.lineNumber, - endColumn: position.column - }).length; + var range = new vscode.Range(0, 0, position.line, position.column); + var offset = document.getTextInRange(range).length; var gocode = path.join(process.env["GOPATH"], "bin", "gocode"); @@ -65,7 +55,7 @@ class SuggestSupport implements vscode.Modes.ISuggestSupport { var p = cp.execFile(gocode, ["-f=json", "autocomplete", filename, "" + offset], {}, (err, stdout, stderr) => { try { if (err && (err).code == "ENOENT") { - vscode.shell.showInformationMessage("The 'gocode' command is not available. Use 'go get -u github.com/nsf/gocode' to install."); + vscode.window.showInformationMessage("The 'gocode' command is not available. Use 'go get -u github.com/nsf/gocode' to install."); } if (err) return reject(err); var results = <[number, GoCodeSuggestion[]]>JSON.parse(stdout.toString()); @@ -74,7 +64,7 @@ class SuggestSupport implements vscode.Modes.ISuggestSupport { label: suggest.name, typeLabel: (suggest.class == "func" ? suggest.type.substring(4) : suggest.type), codeSnippet: suggest.name, - type: monacoTypeFromGoCodeClass(suggest.class) + type: vscodeTypeFromGoCodeClass(suggest.class) }; }) resolve([{ currentWord, suggestions }]); @@ -82,7 +72,7 @@ class SuggestSupport implements vscode.Modes.ISuggestSupport { reject(e); } }); - p.stdin.end(model.getValue()); + p.stdin.end(document.getText()); }); } diff --git a/ticino.plugin.json b/ticino.plugin.json deleted file mode 100644 index 33608c97a6..0000000000 --- a/ticino.plugin.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "pluginId": "vs.language.go", - "activationEvents": ["textModel:go"], - "mainModule": "./out/goMain", - "contributes": { - "language": [{ - "id": "go", - "extensions": [ ".go" ], - "aliases": [ "Go" ] - }], - "debugAdapter": [{ - "type": "go", - "enableBreakpointsFor": { "languageIds": ["go"] }, - "program": "./out/debugAdapter/openDebugMock.js", - "runtime": "node" - }], - "configuration": { - "type": "object", - "title": "Go configuration", - "properties": { - "go.buildOnSave": { - "type": "boolean", - "default": true, - "description": "Run 'go build'/'go test' on save." - }, - "go.lintOnSave": { - "type": "boolean", - "default": true, - "description": "Run 'golint' on save." - }, - "go.vetOnSave": { - "type": "boolean", - "default": true, - "description": "Run 'go tool vet' on save." - }, - "go.formatTool": { - "type": "string", - "default": "goreturns", - "description": "Pick 'gofmt', 'goimports' or 'goreturns' to run on format." - }, - "go.gopath": { - "type": "string", - "default": null, - "description": "Specifies the GOPATH to use when no environment variable is set." - } - } - } - } -} \ No newline at end of file diff --git a/typings/vscode.d.ts b/typings/vscode.d.ts index 7fe6d6aab3..4e0090b9af 100644 --- a/typings/vscode.d.ts +++ b/typings/vscode.d.ts @@ -19,9 +19,10 @@ declare module 'vscode' { (...args:any[]):T | Thenable; } - // TODO@api - // Naming: Inline types or have an explicit ICommands interface? - export const commands: { + /** + * Namespace for commanding + */ + export namespace commands { /** * Registers a command that can be invoked via a keyboard shortcut, @@ -32,7 +33,18 @@ declare module 'vscode' { * @param thisArgs - (optional) The this context used when invoking {{callback}} * @return Disposable which unregisters this command on disposal */ - registerCommand(commandId: string, callback: CommandCallback, thisArg?: any): Disposable; + export function registerCommand(commandId: string, callback: CommandCallback, thisArg?: any): Disposable; + + /** + * Register a text editor command that will make edits. + * It can be invoked via a keyboard shortcut, a menu item, an action, or directly. + * + * @param commandId - The unique identifier of this command + * @param callback - The command callback. The {{textEditor}} and {{edit}} passed in are available only for the duration of the callback. + * @param thisArgs - (optional) The `this` context used when invoking {{callback}} + * @return Disposable which unregisters this command on disposal + */ + export function registerTextEditorCommand(commandId: string, callback: (textEditor:TextEditor, edit:TextEditorEdit) => void, thisArg?: any): Disposable; /** * Executes a command @@ -41,167 +53,192 @@ declare module 'vscode' { * @param ...rest - Parameter passed to the command function * @return */ - executeCommand(commandId: string, ...rest: any[]): Thenable; - }; -} - -declare module 'vscode' { + export function executeCommand(commandId: string, ...rest: any[]): Thenable; + } export interface EditorOptions { tabSize: number; - useSpaces: boolean; + insertSpaces: boolean; } export class Document { - constructor(resource: Uri); + + constructor(uri: Uri, lines: string[], eol: string, languageId: string, versionId: number); + + /** + * Get the associated URI for this document. Most documents have the file:// scheme, indicating that they represent files on disk. + * However, some documents may have other schemes indicating that they are not available on disk. + */ getUri(): Uri; - getText():string; - } - export class Editor { - getDocument(): Document; - setDocument(doc: Document): void; - onDocumentChange: Event; - getSelection(): any; - setSelection(selection: any): void; - getSelections(): any[]; - setSelections(selections: any[]): void; - onSelectionChange: Event; - updateOptions(options: EditorOptions): Thenable; - } + /** + * Is this document representing an untitled file. + */ + isUntitled(): boolean; - // TODO@api, TODO@Joh,Ben - // output channels need to be known upfront (contributes in ticino.plugin.json) - export interface OutputChannel extends Disposable { - append(value: string): void; - appendLine(value: string): void; - clear(): void; - reveal(): void; - } + /** + * The language identifier associated with this document. + */ + getLanguageId(): string; - export interface ExecutionOptions { - cwd?: string; - env?: { [name: string]: any }; - } + /** + * The version number of this document (it will strictly increase after each change). + */ + getVersionId(): number; - export namespace shell { + /** + * Get the entire text in this document. + */ + getText(): string; - export function getEditors(): Editor[]; + /** + * Get the text in a specific range in this document. + */ + getTextInRange(range: Range): string; - export function getActiveEditor(): Editor; + /** + * Get the text on a specific line in this document. + */ + getTextOnLine(line:number): string; /** - * The union of calling 'getEditors()' and 'onEditorOpen(lister)' + * Ensure a range sticks to the text. */ - export function withEditors(callback:(editor:Editor)=>any, thisArg?:any, bucket?:Disposable[]):Disposable; + validateRange(range:Range): Range; - export const onEditorOpen: Event; + /** + * Ensure a position sticks to the text. + */ + validatePosition(position:Position): Position; - export const onEditorClose: Event; + /** + * Get the number of lines in this document. + */ + getLineCount(): number; - export interface MessageFunction { - (message: string): Thenable; - (message: string, ...commands: { title: string; command: string | CommandCallback; }[]): Thenable; - } + /** + * Get the maximum column for line {{line}}. + */ + getLineMaxColumn(line:number): number; - export const showInformationMessage: MessageFunction; + /** + * Get the word under a certain position. May return null if position is at whitespace, on empty line, etc. + */ + getWordRangeAtPosition(position:Position): Range; + } - export const showWarningMessage: MessageFunction; + export class Position { - export const showErrorMessage: MessageFunction; + line: number; - export function setStatusBarMessage(message: string, hideAfter?: number): Disposable; + column: number; - export interface QuickPickOptions { - /** - * an optional flag to include the description when filtering the picks - */ - matchOnDescription?: boolean; + constructor(line: number, column: number); - /** - * an optional string to show as place holder in the input box to guide the user what she picks on - */ - placeHolder?: string; - } + isBefore(other: Position): boolean; - export interface QuickPickItem { - label: string; - description: string; - } + isBeforeOrEqual(other: Position): boolean; + } - // TODO@api naming: showQuickOpen, showQuickPanel, showSelectionPanel, showQuickie - export function showQuickPick(items: string[], options?: QuickPickOptions): Thenable; - export function showQuickPick(items: T[], options?: QuickPickOptions): Thenable; + export class Range { + start: Position; - export function getOutputChannel(name: string): OutputChannel; + end: Position; - // TODO@api - // Justification: Should this be part of the API? Is there a node module that can do the same? - export function runInTerminal(command: string, args: string[], options?: ExecutionOptions): Thenable; + constructor(start: Position, end: Position); + constructor(startLine: number, startColumn: number, endLine:number, endColumn:number); + + contains(positionOrRange: Position | Range): boolean; + isEmpty(): boolean; } -} -declare module 'vscode' { + export class Selection { - // TODO@api in the future there might be multiple opened folder in VSCode - // so that we shouldn't make broken assumptions here - export namespace workspace { + start: Position; - // TODO@api - justify this being here - export function getPath(): string; + end: Position; - export function getRelativePath(pathOrUri: string|Uri): string; + constructor(start: Position, end: Position); - // TODO@api - justify this being here - export function findFiles(include: string, exclude: string, maxResults?:number): Thenable; + isReversed(): boolean; + } + + export class TextEditor { + + constructor(document: Document, selections: Selection[], options: EditorOptions); + + dispose(); /** - * save all dirty files + * Get the document associated with this text editor. The document will be the same for the entire lifetime of this text editor. */ - export function saveAll(includeUntitled?: boolean): Thenable; + getDocument(): Document; /** - * are there any dirty files + * Get the primary selection on this text editor. In case the text editor has multiple selections, the first one will be returned. */ - export function anyDirty(): Thenable; - } + getSelection(): Selection; - export namespace languages { + /** + * Set the selection on this text editor. + */ + setSelection(value: Position | Range | Selection): Thenable; - interface LanguageFilter { - language: string; - scheme?: string; - pattern?: string; - } + /** + * Get the selections in this text editor. + */ + getSelections(): Selection[]; - type LanguageSelector = string|LanguageFilter|(string|LanguageFilter)[]; + /** + * Set the selections in this text editor. + */ + setSelections(value: Selection[]): Thenable; - export interface LanguageStatusFunction { - (language: LanguageSelector, message: string | { octicon: string; message: string;}, command: string | CommandCallback): Disposable - } + /** + * Get text editor options. + */ + getOptions(): EditorOptions; - export const addInformationLanguageStatus:LanguageStatusFunction; - export const addWarningLanguageStatus: LanguageStatusFunction; - export const addErrorLanguageStatus: LanguageStatusFunction; - } -} + /** + * Change text editor options. + */ + setOptions(options: EditorOptions): Thenable; -declare module 'vscode' { + /** + * Perform an edit on the document associated with this text editor. + * The passed in {{edit}} is available only for the duration of the callback. + */ + edit(callback:(edit:TextEditorEdit)=>void): Thenable; - interface Memento { - // createChild(key: string): Memento; - getValue(key: string, defaultValue?: T): Thenable; - setValue(key: string, value: any): Thenable; } - export namespace plugins { - export function getStateObject(pluginId: string, global?: boolean): Memento; - } -} + /** + * A complex edit that will be applied on a TextEditor. + * This holds a description of the edits and if the edits are valid (i.e. no overlapping regions, etc.) they can be applied on a Document associated with a TextEditor. + */ + export interface TextEditorEdit { + /** + * Replace a certain text region with a new value. + */ + replace(location: Position | Range | Selection, value: string): void; -declare module 'vscode' { + /** + * Insert text at a location + */ + insert(location: Position, value: string): void; + /** + * Delete a certain text region. + */ + delete(location: Range | Selection): void; + + } + + /** + * A universal resource identifier representing either a file on disk on + * or another resource, e.g untitled. + */ class Uri { constructor(); @@ -238,13 +275,6 @@ declare module 'vscode' { */ fragment: string; - withScheme(value: string): Uri; - withAuthority(value: string): Uri; - withPath(value: string): Uri; - withQuery(value: string): Uri; - withFragment(value: string): Uri; - with(scheme: string, authority: string, path: string, query: string, fragment: string): Uri; - /** * Retuns a string representing the corresponding file system path of this URI. * Will handle UNC paths and normalize windows drive letters to lower-case. Also @@ -267,10 +297,49 @@ declare module 'vscode' { onCancellationRequested: Event; } + class CancellationTokenSource { + + token: CancellationToken; + + cancel(): void; + + dispose(): void; + } + + /** + * Represents a type which can release resources, such + * as event listening or a timer. + */ class Disposable { + + /** + * Combine many disposables into one. + * + * @return Returns a new disposable which, upon dispose, will + * dispose all provided disposables + */ static of(...disposables: Disposable[]): Disposable; - static from(...disposableLikes: { dispose: () => void }[]): Disposable; + + /** + * Combine many disposable-likes into one. Use this method + * when having objects with a dispose function which are not + * instances of Disposable. + * + * @return Returns a new disposable which, upon dispose, will + * dispose all provides disposable-likes. + */ + static from(...disposableLikes: { dispose: () => any }[]): Disposable; + + /** + * Creates a new Disposable calling the provided function + * on dispose + * @param callOnDispose Function that disposes something + */ constructor(callOnDispose: Function); + + /** + * Dispose this object. + */ dispose(): any; } @@ -290,290 +359,345 @@ declare module 'vscode' { } /** - * A position in the editor. This interface is suitable for serialization. + * A file system watcher notifies about changes to files and folders + * on disk. To get an instanceof of a {{FileSystemWatcher}} use + * {{workspace.createFileSystemWatcher}}. */ - export interface IPosition { + export interface FileSystemWatcher extends Disposable { + + /** + * Happens on file/folder creation. + */ + onDidCreate: Event; + /** - * line number (starts at 1) + * Happens on file/folder change. */ - lineNumber:number; + onDidChange: Event; + /** - * column (the first character in a line is between column 1 and column 2) + * Happens on file/folder deletion. */ - column:number; + onDidDelete: Event; } /** - * A range in the editor. This interface is suitable for serialization. + * */ - interface IRange { + export interface QuickPickOptions { /** - * Line number on which the range starts (starts at 1). - */ - startLineNumber:number; + * an optional flag to include the description when filtering the picks + */ + matchOnDescription?: boolean; + /** - * Column on which the range starts in line `startLineNumber` (starts at 1). - */ - startColumn:number; + * an optional string to show as place holder in the input box to guide the user what she picks on + */ + placeHolder?: string; + } + + /** + * + */ + export interface QuickPickItem { + label: string; + description: string; + } + + /** + * + */ + export interface InputBoxOptions { /** - * Line number on which the range ends. + * More context around the input that is being asked for. + */ + description?: string; + + /** + * an optional string to show as place holder in the input box to guide the user what to type + */ + placeHolder?: string; + } + + /** + * + */ + interface LanguageFilter { + language: string; + scheme?: string; + pattern?: string; + } + + /** + * + */ + type LanguageSelector = string|LanguageFilter|(string|LanguageFilter)[]; + + + /** + * + */ + interface ReadOnlyMemento { + + /** + * @param key The name of a property to read. + * @param defaultValue The default value in case the denoted property doesn't exists. + * @return */ - endLineNumber:number; + getValue(key: string, defaultValue?: T): Thenable; + /** - * Column on which the range ends in line `endLineNumber`. + * */ - endColumn:number; + getValues(defaultValue?: T): Thenable; } - var Range: { - containsPosition(range:IRange, position:IPosition): boolean; - }; + /** + * + */ + interface Memento extends ReadOnlyMemento { + setValue(key: string, value: any): Thenable; + } - export interface IHTMLContentElement { - formattedText?:string; - text?: string; - className?: string; - style?: string; - customStyle?: any; - tagName?: string; - children?: IHTMLContentElement[]; - isText?: boolean; + /** + * Represents the severity of diagnostics. + */ + export enum DiagnosticSeverity { + Warning = 1, + Error = 2 } - module Services { - enum Severity { - Ignore = 0, - Info = 1, - Warning = 2, - Error = 3 - } + /** + * Represents a location inside a resource, such as a line + * inside a text file. + */ + export class Location { + constructor(uri: Uri, range: Selection | Range | Position); + uri: Uri; + range: Range; + } - module Severity { - export function fromValue(value: string): Severity; - } + /** + * Represents a diagnostic, such as a compiler error or warning, along with the location + * in which they occurred. + */ + export class Diagnostic { - export interface IModelService { - onModelAdd: Event; - onModelRemove: Event; - addModel(model: IModel): void; - removeModel(model: IModel): void; - getModels(): IModel[]; - getModel(resource: Uri): IModel; - } + public static createErrorDiagnostic(location: Location, message: string): Diagnostic; - // --- Begin MarkerService - export interface IMarkerData { - code?: string; - severity: Severity; - message: string; - startLineNumber: number; - startColumn: number; - endLineNumber: number; - endColumn: number; - } + public static createWarningDiagnostic(location: Location, message: string): Diagnostic; - export interface IResourceMarker { - resource: Uri; - marker:IMarkerData; - } + constructor(severity: DiagnosticSeverity, location: Location, message: string); - export interface IMarker { - owner: string; - resource: Uri; - severity: Severity; - code?: string; - message: string; - startLineNumber: number; - startColumn: number; - endLineNumber: number; - endColumn: number; - } + severity: DiagnosticSeverity; - export interface IMarkerService { + location: Location; - changeOne(owner: string, resource: Uri, markers: IMarkerData[]): void; + message: string; + } - changeAll(owner: string, data: IResourceMarker[]): void; + // TODO@api, TODO@Joh,Ben + // output channels need to be known upfront (contributes in package.json) + export interface OutputChannel extends Disposable { + append(value: string): void; + appendLine(value: string): void; + clear(): void; + reveal(): void; + } - remove(owner: string, resources: Uri[]): void - } + export interface ExecutionOptions { + cwd?: string; + env?: { [name: string]: any }; + } - // --- End IMarkerService + export interface TextEditorSelectionChangeEvent { + textEditor: TextEditor; + selections: Selection[]; + } - // --- Begin IConfigurationService + export interface TextEditorOptionsChangeEvent { + textEditor: TextEditor; + options: EditorOptions; + } - export interface IConfigurationService { - loadConfiguration(section?: string): Thenable; - } + export namespace window { - // --- End IConfigurationService + export function getActiveTextEditor(): TextEditor; - // --- Begin IFileSystemEventService + export const onDidChangeActiveTextEditor: Event; - export enum FileChangeTypes { - Changed = 0, - Created = 1, - Deleted = 2 - } + export const onDidChangeTextEditorSelection: Event; - export interface IFileSystemEvent { - resource: Uri; - changeType: FileChangeTypes; - } + export const onDidChangeTextEditorOptions: Event; - export interface IFileSystemWatcher extends Disposable { - onFileChange: Event; - } + export function showInformationMessage(message: string, ...commands: { title: string; command: string | CommandCallback; }[]): Thenable; - export interface IFileSystemEventService { - createWatcher(pattern?: string): IFileSystemWatcher; - } + export function showWarningMessage(message: string, ...commands: { title: string; command: string | CommandCallback; }[]): Thenable; + + export function showErrorMessage(message: string, ...commands: { title: string; command: string | CommandCallback; }[]): Thenable; - // --- End IFileSystemEventService + export function setStatusBarMessage(message: string, hideAfterSeconds?: number): Disposable; + + export function showQuickPick(items: string[], options?: QuickPickOptions): Thenable; + + export function showQuickPick(items: T[], options?: QuickPickOptions): Thenable; - export var MarkerService: IMarkerService; + /** + * Opens an input box to ask the user for input. + */ + export function showInputBox(options?: InputBoxOptions): Thenable; - export var ModelService: IModelService; + export function getOutputChannel(name: string): OutputChannel; - export var ConfigurationService: IConfigurationService; + // TODO@api + // Justification: Should this be part of the API? Is there a node module that can do the same? + export function runInTerminal(command: string, args: string[], options?: ExecutionOptions): Thenable; - export var FileSystemEventService: IFileSystemEventService; } - module Models { + /** + * An event describing a change in the text of a model. + */ + export interface DocumentContentChangeEvent { /** - * A single edit operation, that acts as a simple replace. - * i.e. Replace text at `range` with `text` in model. + * The range that got replaced. */ - export interface ISingleEditOperation { - /** - * The range to replace. This can be empty to emulate a simple insert. - */ - range: IRange; - /** - * The text to replace with. This can be null to emulate a simple delete. - */ - text: string; - } + range: IRange; + /** + * The length of the range that got replaced. + */ + rangeLength: number; + /** + * The new text for the range. + */ + text: string; + /** + * The new version id the model has transitioned to. + */ + versionId: number; + /** + * Flag that indicates that this event was generated while undoing. + */ + isUndoing: boolean; + /** + * Flag that indicates that this event was generated while redoing. + */ + isRedoing: boolean; + } + + export interface DocumentChangeEvent { + document: Document; + contentChanges: DocumentContentChangeEvent[]; + } + + // TODO@api in the future there might be multiple opened folder in VSCode + // so that we shouldn't make broken assumptions here + export namespace workspace { /** - * Word inside a model. + * Creates a file system watcher. A glob pattern that filters the + * file events must be provided. Optionally, flags to ignore certain + * kind of events can be provided. + * + * @param globPattern - A glob pattern that is applied to the names of created, changed, and deleted files. + * @param ignoreCreateEvents - Ignore when files have been created. + * @param ignoreChangeEvents - Ignore when files have been changed. + * @param ignoreDeleteEvents - Ignore when files have been deleted. */ - export interface IWordAtPosition { - /** - * The word. - */ - word: string; - /** - * The column where the word starts. - */ - startColumn: number; - /** - * The column where the word ends. - */ - endColumn: number; - } + export function createFileSystemWatcher(globPattern: string, ignoreCreateEvents?: boolean, ignoreChangeEvents?: boolean, ignoreDeleteEvents?: boolean): FileSystemWatcher; + + // TODO@api - justify this being here + export function getPath(): string; + + export function getRelativePath(pathOrUri: string|Uri): string; + + // TODO@api - justify this being here + export function findFiles(include: string, exclude: string, maxResults?:number): Thenable; /** - * End of line character preference. + * save all dirty files */ - export enum EndOfLinePreference { - /** - * Use the end of line character identified in the text buffer. - */ - TextDefined = 0, - /** - * Use line feed (\n) as the end of line character. - */ - LF = 1, - /** - * Use carriage return and line feed (\r\n) as the end of line character. - */ - CRLF = 2 - } + export function saveAll(includeUntitled?: boolean): Thenable; + + export function getAllDocuments(): Document[]; + export function getDocument(resource: Uri): Document; + export const onDidAddDocument: Event; + export const onDidRemoveDocument: Event; + export const onDidChangeDocument: Event; + export const onDidSaveDocument: Event; /** - * An event describing a change in the text of a model. + * are there any dirty files */ - export interface IContentChangedEvent { - /** - * The range that got replaced. - */ - range: IRange; - /** - * The length of the range that got replaced. - */ - rangeLength: number; - /** - * The new text for the range. - */ - text: string; - /** - * The new version id the model has transitioned to. - */ - versionId: number; - /** - * Flag that indicates that this event was generated while undoing. - */ - isUndoing: boolean; - /** - * Flag that indicates that this event was generated while redoing. - */ - isRedoing: boolean; - } + export function anyDirty(): Thenable; } - export interface IModel { - - getUri(): Uri; + export namespace languages { /** - * @review + * Add diagnostics, such as compiler errors or warnings. They wil represented as + * squiggles in text editors and in general list of errors. + * To remove the diagnostics again, dispose the `Disposable` which is returned + * from this function call. + * + * @param diagnostics Array of diagnostics + * @return A disposable the removes the diagnostics again. */ - isUntitled(): boolean; + export function addDiagnostics(diagnostics: Diagnostic[]): Disposable; /** - * Get the current version id of the model. - * Anytime a change happens to the model (even undo/redo), - * the version id is incremented. + * */ - getVersionId(): number; + export function addInformationLanguageStatus(language: LanguageSelector|Uri|Uri[], message: string | { octicon: string; message: string;}, command: string | CommandCallback): Disposable; /** - * Get the text stored in this model. - * @param eol The end of line character preference. Defaults to `EndOfLinePreference.TextDefined`. - * @param preserverBOM Preserve a BOM character if it was detected when the model was constructed. - * @return The text. + * */ - getValue(eol?:Models.EndOfLinePreference, preserveBOM?:boolean): string; + export function addWarningLanguageStatus(language: LanguageSelector | Uri | Uri[], message: string | { octicon: string; message: string; }, command: string | CommandCallback): Disposable; /** - * Get the text in a certain range. - * @param range The range describing what text to get. - * @param eol The end of line character preference. This will only be used for multiline ranges. Defaults to `EndOfLinePreference.TextDefined`. - * @return The text. + * */ - getValueInRange(range: IRange, eol?: Models.EndOfLinePreference): string; + export function addErrorLanguageStatus(language: LanguageSelector | Uri | Uri[], message: string | { octicon: string; message: string; }, command: string | CommandCallback): Disposable; + } + + export namespace plugins { + export function getStateObject(pluginId: string, global?: boolean): Memento; + + export function getConfigurationObject(pluginId: string): ReadOnlyMemento; + } + /** + * A range in the editor. This interface is suitable for serialization. + */ + interface IRange { /** - * Get the number of lines in the model. + * Line number on which the range starts (starts at 1). */ - getLineCount(): number; - + startLineNumber:number; /** - * Get the maximum legal column for line at `lineNumber` + * Column on which the range starts in line `startLineNumber` (starts at 1). */ - getLineMaxColumn(lineNumber:number): number; - + startColumn:number; /** - * Get the word under or besides `position`. - * @return The word under or besides `position`. Might be null. + * Line number on which the range ends. */ - getWordAtPosition(position:IPosition): Models.IWordAtPosition; - - getModeId(): string; + endLineNumber:number; + /** + * Column on which the range ends in line `endLineNumber`. + */ + endColumn:number; + } - onContentChange: Event; + export interface IHTMLContentElement { + formattedText?:string; + text?: string; + className?: string; + style?: string; + customStyle?: any; + tagName?: string; + children?: IHTMLContentElement[]; + isText?: boolean; } // --- Begin Monaco.Modes @@ -612,13 +736,13 @@ declare module 'vscode' { interface ILanguageAutoComplete { triggers: string; // characters that trigger auto completion rules - match: string /* || RegExp */; // autocomplete if this matches + match: string|RegExp; // autocomplete if this matches complete: string; // complete with this string } interface ILanguageAutoIndent { - match: string /* || RegExp */; // auto indent if this matches on enter - matchAfter: string /* || RegExp */; // and auto-outdent if this matches on the next line + match: string|RegExp; // auto indent if this matches on enter + matchAfter: string|RegExp; // and auto-outdent if this matches on the next line } /** @@ -662,166 +786,30 @@ declare module 'vscode' { } // --- Begin InplaceReplaceSupport - interface IInplaceReplaceSupportResult { - value: string; - range:IRange; - } /** * Interface used to navigate with a value-set. */ interface IInplaceReplaceSupport { - navigateValueSet(resource:Uri, range:IRange, up:boolean, token: CancellationToken):Thenable; - } - interface IInplaceReplaceSupportCustomization { - textReplace?: (value: string, up: boolean) => string; - navigateValueSetFallback?: (resource: Uri, range: IRange, up: boolean, token: CancellationToken) => Thenable; + sets: string[][]; } + var InplaceReplaceSupport: { + register(modeId: string, inplaceReplaceSupport: Modes.IInplaceReplaceSupport): void; + }; // --- End InplaceReplaceSupport // --- Begin TokenizationSupport - interface IStream { - /** - * Returns the current character position of the stream on the line. - */ - pos():number; - /** - * Returns true iff the stream is at the end of the line. - */ - eos():boolean; - /** - * Returns the next character in the stream. - */ - peek():string; - /** - * Returns the next character in the stream, and advances it by one character. - */ - next():string; - /** - * Advances the stream by `n` characters. - */ - advance(n:number):string; - /** - * Advances the stream until the end of the line. - */ - advanceToEOS():string; - /** - * Brings the stream back `n` characters. - */ - goBack(n:number):void; - /** - * Advances the stream if the next characters validate a condition. A condition can be - * - * - a regular expression (always starting with ^) - * EXAMPLES: /^\d+/, /^function|var|interface|class/ - * - * - a string - * EXAMPLES: "1954", "albert" - */ - advanceIfCharCode(charCode:number): string; - advanceIfString(condition:string):string; - advanceIfStringCaseInsensitive(condition:string):string; - advanceIfRegExp(condition:RegExp):string; - /** - * Advances the stream while the next characters validate a condition. Check #advanceIf for - * details on the possible types for condition. - */ - advanceWhile(condition:string):string; - advanceWhile(condition:RegExp):string; - /** - * Advances the stream until the some characters validate a condition. Check #advanceIf for - * details on the possible types for condition. The `including` boolean value indicates - * whether the stream will advance the characters that matched the condition as well, or not. - */ - advanceUntil(condition:string, including:boolean):string; - advanceUntil(condition:RegExp, including:boolean):string; - /** - * The token rules define how consecutive characters should be put together as a token, - * or separated into two different tokens. They are given through a separator characters - * string and a whitespace characters string. A separator is always one token. Consecutive - * whitespace is always one token. Everything in between these two token types, is also a token. - * - * EXAMPLE: stream.setTokenRules("+-", " "); - * Setting these token rules defines the tokens for the string "123+456 - 7" as being - * ["123", "+", "456", " ", "-", " ", "7"] - */ - setTokenRules(separators:string, whitespace:string):void; - /** - * Returns the next token, given that the stream was configured with token rules. - */ - peekToken():string; - /** - * Returns the next token, given that the stream was configured with token rules, and advances the - * stream by the exact length of the found token. - */ - nextToken():string; - /** - * Returns the next whitespace, if found. Returns an empty string otherwise. - */ - peekWhitespace():string; - /** - * Returns the next whitespace, if found, and advances the stream by the exact length of the found - * whitespace. Returns an empty string otherwise. - */ - skipWhitespace():string; - } - enum Bracket { None = 0, Open = 1, Close = -1 } - - interface ITokenizationResult { - type?:string; - bracket?:Bracket; - nextState?:IState; - } - - interface IToken { - startIndex:number; - type:string; - bracket:Bracket; - } - - interface IModeTransition { - startIndex: number; - mode: IMode; - } - - interface ILineTokens { - tokens: IToken[]; - actualStopOffset: number; - endState: IState; - modeTransitions: IModeTransition[]; - retokenize?: Thenable; - } - - interface IState { - clone():IState; - equals(other:IState):boolean; - getMode():IMode; - tokenize(stream:IStream):ITokenizationResult; - getStateData(): IState; - setStateData(state:IState):void; - } - - export interface ITokenizationSupport { - - shouldGenerateEmbeddedModels: boolean; - - getInitialState():IState; - - // add offsetDelta to each of the returned indices - // stop tokenizing at absolute value stopAtOffset (i.e. stream.pos() + offsetDelta > stopAtOffset) - tokenize(line:string, state:IState, offsetDelta?:number, stopAtOffset?:number):ILineTokens; - } // --- End TokenizationSupport // --- Begin IDeclarationSupport export interface IDeclarationSupport { tokens?: string[]; - findDeclaration(resource: Uri, position: IPosition, token: CancellationToken): Thenable; + findDeclaration(document: Document, position: Position, token: CancellationToken): Thenable; } var DeclarationSupport: { register(modeId: string, declarationSupport: IDeclarationSupport): void; @@ -830,32 +818,32 @@ declare module 'vscode' { // --- Begin ICodeLensSupport export interface ICodeLensSupport { - findCodeLensSymbols(resource:Uri, token:CancellationToken): Thenable; - findCodeLensReferences(resource:Uri, requests: ICodeLensSymbolRequest[], token:CancellationToken): Thenable; + findCodeLensSymbols(document: Document, token: CancellationToken): Thenable; + findCodeLensReferences(document: Document, requests: ICodeLensSymbolRequest[], token: CancellationToken): Thenable; } export interface ICodeLensSymbolRequest { - position:IPosition; + position: Position; languageModeStateId?: number; } export interface ICodeLensSymbol { - range:IRange; + range: Range; } export interface ICodeLensReferences { - references: IReference[][]; - languageModeStateId?: number; + references: IReference[][]; + languageModeStateId?: number; } var CodeLensSupport: { - register(modeId: string, codeLensSupport:ICodeLensSupport): void; + register(modeId: string, codeLensSupport: ICodeLensSupport): void; }; // --- End ICodeLensSupport // --- Begin IOccurrencesSupport export interface IOccurrence { kind?:string; - range:IRange; + range:Range; } export interface IOccurrencesSupport { - findOccurrences(resource: Uri, position: IPosition, token: CancellationToken): Thenable; + findOccurrences(resource: Document, position: Position, token: CancellationToken): Thenable; } var OccurrencesSupport: { register(modeId: string, occurrencesSupport:IOccurrencesSupport): void; @@ -867,11 +855,11 @@ declare module 'vscode' { label: string; type: string; icon?: string; // icon class or null to use the default images based on the type - range: IRange; + range: Range; children?: IOutlineEntry[]; } export interface IOutlineSupport { - getOutline(resource: Uri, token: CancellationToken): Thenable; + getOutline(document: Document, token: CancellationToken): Thenable; outlineGroupLabel?: { [name: string]: string; }; } var OutlineSupport: { @@ -892,8 +880,8 @@ declare module 'vscode' { } export interface IQuickFixSupport { - getQuickFixes(resource: Uri, marker: Services.IMarker | IRange, token: CancellationToken): Thenable; - runQuickFixAction(resource: Uri, range: IRange, id: any, token: CancellationToken): Thenable; + getQuickFixes(resource: Document, marker: Range, token: CancellationToken): Thenable; + runQuickFixAction(resource: Document, range: Range, id: any, token: CancellationToken): Thenable; } var QuickFixSupport: { register(modeId: string, quickFixSupport:IQuickFixSupport): void @@ -908,7 +896,7 @@ declare module 'vscode' { * @returns a list of reference of the symbol at the position in the * given resource. */ - findReferences(resource: Uri, position: IPosition, includeDeclaration: boolean, token: CancellationToken): Thenable; + findReferences(document: Document, position: Position, includeDeclaration: boolean, token: CancellationToken): Thenable; } var ReferenceSupport: { register(modeId: string, quickFixSupport:IReferenceSupport): void; @@ -948,7 +936,7 @@ declare module 'vscode' { /** * @returns the parameter hints for the specified position in the file. */ - getParameterHints(resource: Uri, position: IPosition, token: CancellationToken): Thenable; + getParameterHints(document: Document, position: Position, token: CancellationToken): Thenable; } var ParameterHintsSupport: { register(modeId: string, parameterHintsSupport:IParameterHintsSupport): void; @@ -957,13 +945,13 @@ declare module 'vscode' { // --- Begin IExtraInfoSupport export interface IComputeExtraInfoResult { - range: IRange; + range: Range; value?: string; htmlContent?: IHTMLContentElement[]; className?: string; } export interface IExtraInfoSupport { - computeInfo(resource: Uri, position: IPosition, token: CancellationToken): Thenable; + computeInfo(document: Document, position: Position, token: CancellationToken): Thenable; } var ExtraInfoSupport: { register(modeId: string, extraInfoSupport:IExtraInfoSupport): void; @@ -978,7 +966,7 @@ declare module 'vscode' { } export interface IRenameSupport { filter?: string[]; - rename(resource: Uri, position: IPosition, newName: string, token: CancellationToken): Thenable; + rename(document: Document, position: Position, newName: string, token: CancellationToken): Thenable; } var RenameSupport: { register(modeId: string, renameSupport:IRenameSupport): void; @@ -993,6 +981,20 @@ declare module 'vscode' { tabSize:number; insertSpaces:boolean; } + /** + * A single edit operation, that acts as a simple replace. + * i.e. Replace text at `range` with `text` in model. + */ + export interface ISingleEditOperation { + /** + * The range to replace. This can be empty to emulate a simple insert. + */ + range: IRange; + /** + * The text to replace with. This can be null to emulate a simple delete. + */ + text: string; + } /** * Supports to format source code. There are three levels * on which formatting can be offered: @@ -1001,10 +1003,10 @@ declare module 'vscode' { * (3) format on keystroke */ export interface IFormattingSupport { - formatDocument: (resource: Uri, options: IFormattingOptions, token: CancellationToken) => Thenable; - formatRange?: (resource: Uri, range: IRange, options: IFormattingOptions, token: CancellationToken) => Thenable; + formatDocument: (document: Document, options: IFormattingOptions, token: CancellationToken) => Thenable; + formatRange?: (document: Document, range: Range, options: IFormattingOptions, token: CancellationToken) => Thenable; autoFormatTriggerCharacters?: string[]; - formatAfterKeystroke?: (resource: Uri, position: IPosition, ch: string, options: IFormattingOptions, token: CancellationToken) => Thenable; + formatAfterKeystroke?: (document: Document, position: Position, ch: string, options: IFormattingOptions, token: CancellationToken) => Thenable; } var FormattingSupport: { register(modeId: string, formattingSupport:IFormattingSupport): void; @@ -1041,8 +1043,8 @@ declare module 'vscode' { sortBy?: ISortingTypeAndSeparator[]; - suggest: (resource: Uri, position: IPosition, token: CancellationToken) => Thenable; - getSuggestionDetails? : (resource:Uri, position:IPosition, suggestion:ISuggestion, token: CancellationToken) => Thenable; + suggest: (document: Document, position: Position, token: CancellationToken) => Thenable; + getSuggestionDetails? : (document: Document, position: Position, suggestion:ISuggestion, token: CancellationToken) => Thenable; } var SuggestSupport: { register(modeId:string, suggestSupport:ISuggestSupport): void; @@ -1056,12 +1058,12 @@ declare module 'vscode' { name: string; parameters: string; type: string; - range: IRange; + range: Range; resourceUri: Uri; } export interface INavigateTypesSupport { - getNavigateToItems:(search: string, resource: Uri, token: CancellationToken) => Thenable; + getNavigateToItems:(search: string, token: CancellationToken) => Thenable; } var NavigateTypesSupport: { register(modeId:string, navigateTypeSupport:INavigateTypesSupport): void; @@ -1162,29 +1164,15 @@ declare module 'vscode' { }; // --- End IOnEnterSupport - export interface ILineContext { - getLineContent(): string; - // TODO@Alex - modeTransitions: IModeTransition[]; - - getTokenCount(): number; - getTokenStartIndex(tokenIndex:number): number; - getTokenType(tokenIndex:number): string; - getTokenBracket(tokenIndex:number): Bracket; - getTokenText(tokenIndex:number): string; - getTokenEndIndex(tokenIndex:number): number; - findIndexOfOffset(offset:number): number; - } - export interface IResourceEdit { resource: Uri; - range?: IRange; + range?: Range; newText: string; } export interface IReference { resource: Uri; - range: IRange; + range: Range; } interface IMode { @@ -1193,20 +1181,12 @@ declare module 'vscode' { function registerMonarchDefinition(modeId: string, language: Modes.ILanguage): void; function loadInBackgroundWorker(scriptSrc: string): Thenable; - var InplaceReplaceSupport: { - register(modeId: string, inplaceReplaceSupport: Modes.IInplaceReplaceSupport): void; - create(customization?: Modes.IInplaceReplaceSupportCustomization): Modes.IInplaceReplaceSupport; - valueSetReplace(valueSet: string[], value: string, up: boolean): string; - valueSetsReplace(valueSets: string[][], value: string, up: boolean): string; - }; + } module Plugins { function get(pluginId:string): any; } -} - -declare module 'vscode' { /** * DO NOT USE. @@ -1247,15 +1227,15 @@ declare module 'vscode-testing' { * enables reusing existing code without migrating to a specific promise implementation. Still, * we recommand the use of native promises which are available in VS Code. */ -interface Thenable { +interface Thenable { /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onfulfilled The callback to execute when the Promise is resolved. * @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): Thenable; - then(onfulfilled?: (value: T) => 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; } // ---- ES6 promise ------------------------------------------------------ @@ -1344,166 +1324,3 @@ interface PromiseConstructor { } declare var Promise: PromiseConstructor; - - -// --- for the future ------------ - -declare module 'vscode2' { - - export interface Event { - (listener: (event: T) => any, thisArg?: any); - } - - interface CommandCallback { - (...args: any[]): T|Thenable; - } - - class Disposable { - constructor(disposeFunction: () => any); - dispose(): any; - } - - class Uri { - static parse(value:string):Uri; - static file(fsPath: string): Uri; - scheme: string; - authority: string; - path: string; - fsPath: string; - query: string; - fragment: string; - } - - class Point { - constructor(line: number, character: number); - line: number; - character: number; - } - - class Range { - static from(point: Point): Range; - constructor(start: Point, end: Point); - start: Point; - end: Point; - isEmpty(): boolean; - } - - class Document { - - /** - * @return The resource identifier for this document. - */ - getUri(): Uri; - - /** - * Shorthand for ```getUri().scheme === 'untitled'``` - * @return {true} when this is an untitled document - */ - isUntitled(): boolean; - - /** - * @param range - The range from which text is returned. Iff omitted all text is returned - */ - getText(range?: Range): string; - - /** - * - */ - replaceText(newText: string, range: Range, options: { eol: any }): void; - } - - class Editor { - - getDocument(): Document; - - setDocument(doc: Document): void; - - getSelection(): Range; - - getSelections(): Range[]; - - setSelection(rangeOrPoint: Range|Point); - - setSelections(rangeOrPoint: Range[]|Point[]); - } - - export namespace workspace { - - export const onDocumentClose: Event; - - export const onDocumentOpen: Event; - - export const onDocumentChange: Event; - - export const trackDocuments: Event; - - export const onFileChange: Event; - - export function getRelativePath(pathOrUri: string | Uri): string; - } - - export namespace shell { - - export function getActiveEditor(): Editor; - - export const onEditorOpen: Event; - - export const onEditorClose: Event; - - export function showQuickPanel(item: string[]): Thenable; - - export function showInformationMessage(message:string, ...commands: {title:string; command:string | CommandCallback}[]): Thenable; - - export function showWarningMessage(message: string, ...commands: { title: string; command: string | CommandCallback }[]): Thenable; - - export function showErrorMessage(message:string, ...commands: {title:string; command:string | CommandCallback}[]): Thenable; - - export function setStatusBarMessage(message: string, ...commands: {title:string; command:string | CommandCallback}[]): Thenable; - } - - export namespace commands { - - export function registerCommand(commandId: string, callback: CommandCallback): Disposable; - - export function executeCommand(commandId: string, ...args: any[]): Thenable; - } - - export namespace languages { - - export interface Filter { - - /** - * Filters on the name of a language, e.g ```javascript```, ```markdown```. - */ - language: string; - - /** - * Filters on the scope of the current token, e.g comment - */ - scope?: string; - - /** - * Filters on the path. - */ - filePathPattern?: RegExp; - - /** - * Filters on the scheme of the resource, e.g. ```!untitled``` for everything except - * untitled resources or ```file|untitled``` for only {file} and {untitled} resources - */ - schemePattern?: RegExp; - } - - export interface IntelliSenseProvider { - provideIntelliSense(doc: Document, point: Point): Thenable | string[]; - } - - export function registerIntelliSenseProvider(provider: IntelliSenseProvider, filter: Filter, ...more: Filter[]); - - export interface HoverProvider { - provideHover(doc: Document, point: Point): Thenable | string; - } - - export function registerHoverProvider(provider: HoverProvider, filter:Filter, ...more: Filter[]):void; - } -} \ No newline at end of file From 6344fad492b66549bcba2c522fa962b53fb608f8 Mon Sep 17 00:00:00 2001 From: Erich Gamma Date: Fri, 25 Sep 2015 15:30:42 +0200 Subject: [PATCH 2/3] more API updates for commit a3e48a6 --- src/goDeclaration.ts | 2 +- src/goExtraInfo.ts | 2 +- src/goFormat.ts | 15 ++--- src/goMain.ts | 8 +-- src/goReferences.ts | 13 ++-- src/goRename.ts | 11 +--- src/goSuggest.ts | 2 +- typings/vscode.d.ts | 138 ++++++++++++++++--------------------------- 8 files changed, 69 insertions(+), 122 deletions(-) diff --git a/src/goDeclaration.ts b/src/goDeclaration.ts index 8cb82951ff..65ccc0ab86 100644 --- a/src/goDeclaration.ts +++ b/src/goDeclaration.ts @@ -10,7 +10,7 @@ import path = require('path'); class DeclartionSupport implements vscode.Modes.IDeclarationSupport { - public findDeclaration(document:vscode.Document, position:vscode.Position, token: vscode.CancellationToken):Thenable { + public findDeclaration(document:vscode.TextDocument, position:vscode.Position, token: vscode.CancellationToken):Thenable { return new Promise((resolve, reject) => { diff --git a/src/goExtraInfo.ts b/src/goExtraInfo.ts index b518aac7dd..94f46435b2 100644 --- a/src/goExtraInfo.ts +++ b/src/goExtraInfo.ts @@ -11,7 +11,7 @@ import path = require('path'); class ExtraInfoSupport implements vscode.Modes.IExtraInfoSupport { - public computeInfo(document:vscode.Document, position:vscode.Position, token: vscode.CancellationToken): Promise { + public computeInfo(document:vscode.TextDocument, position:vscode.Position, token: vscode.CancellationToken): Promise { return new Promise((resolve, reject) => { var filename = document.getUri().fsPath; diff --git a/src/goFormat.ts b/src/goFormat.ts index af5f4ed0b1..295d348809 100644 --- a/src/goFormat.ts +++ b/src/goFormat.ts @@ -15,7 +15,7 @@ class FormattingSupport implements vscode.Modes.IFormattingSupport { public autoFormatTriggerCharacters: string[] = [';', '}', '\n']; constructor() { - vscode.plugins.getConfigurationObject('go').getValue('formatTool').then(formatTool => { + vscode.extensions.getConfigurationMemento('go').getValue('formatTool').then(formatTool => { if(formatTool) { this.formatCommand = formatTool; } @@ -23,23 +23,18 @@ class FormattingSupport implements vscode.Modes.IFormattingSupport { } // TODO: work around bug that Code always calls formatRange - public formatRange(document: vscode.Document, range: vscode.Range, options: vscode.Modes.IFormattingOptions, token: vscode.CancellationToken): Thenable { + public formatRange(document: vscode.TextDocument, range: vscode.Range, options: vscode.Modes.IFormattingOptions, token: vscode.CancellationToken): Thenable { return this.formatDocument(document, options, token) } - public formatDocument(document: vscode.Document, options: vscode.Modes.IFormattingOptions, token: vscode.CancellationToken): Thenable { + public formatDocument(document: vscode.TextDocument, options: vscode.Modes.IFormattingOptions, token: vscode.CancellationToken): Thenable { // TODO: We don't really need to save all the buffers, just the one for 'resource. - return vscode.workspace.anyDirty().then(anyDirty => { - if (anyDirty) { - vscode.workspace.saveAll(false).then(() => { - return this.doFormatDocument(document, options, token); - }); - } + return vscode.workspace.saveAll(false).then(() => { return this.doFormatDocument(document, options, token); }); } - private doFormatDocument(document: vscode.Document, options: vscode.Modes.IFormattingOptions, token: vscode.CancellationToken):Thenable { + private doFormatDocument(document: vscode.TextDocument, options: vscode.Modes.IFormattingOptions, token: vscode.CancellationToken):Thenable { return new Promise((resolve, reject) => { var filename = document.getUri().fsPath; diff --git a/src/goMain.ts b/src/goMain.ts index fcea552436..8e862900f4 100644 --- a/src/goMain.ts +++ b/src/goMain.ts @@ -31,7 +31,7 @@ export function activate() { function setupGoPathAndOfferToInstallTools() { // TODO: There should be a better way to do this? - vscode.plugins.getConfigurationObject('go').getValue('gopath').then(gopath => { + vscode.extensions.getConfigurationMemento('go').getValue('gopath').then(gopath => { // Make sure GOPATH is set if(!process.env["GOPATH"] && gopath) { @@ -96,15 +96,15 @@ function startBuildOnSaveWatcher() { } } - vscode.plugins.getConfigurationObject('go').getValues().then((config = {}) => { - vscode.workspace.onDidSaveDocument(document => { + vscode.extensions.getConfigurationMemento('go').getValues().then((config = {}) => { + vscode.workspace.onDidSaveTextDocument(document => { check(document.getUri().fsPath, config['buildOnSave'], config['lintOnSave'], config['vetOnSave']).then(errors => { if (_diagnostics) { _diagnostics.dispose(); } var diagnostics = errors.map(error => { let targetResource = vscode.Uri.file(error.file); - let document = vscode.workspace.getDocument(targetResource); + let document = vscode.workspace.getTextDocument(targetResource); let startColumn = 0; let endColumn = 1; if (document) { diff --git a/src/goReferences.ts b/src/goReferences.ts index 5cdead69a4..a49c48a69c 100644 --- a/src/goReferences.ts +++ b/src/goReferences.ts @@ -10,18 +10,13 @@ import path = require('path'); class ReferenceSupport implements vscode.Modes.IReferenceSupport { - public findReferences(document: vscode.Document, position:vscode.Position, includeDeclaration:boolean, token: vscode.CancellationToken): Thenable { - return vscode.workspace.anyDirty().then(anyDirty => { - if (anyDirty) { - vscode.workspace.saveAll(false).then(() => { - return this.doFindReferences(document, position, includeDeclaration, token); - }); - } - return this.doFindReferences(document, position, includeDeclaration, token); + public findReferences(document: vscode.TextDocument, position:vscode.Position, includeDeclaration:boolean, token: vscode.CancellationToken): Thenable { + return vscode.workspace.saveAll(false).then(() => { + return this.doFindReferences(document, position, includeDeclaration, token); }); } - private doFindReferences(document:vscode.Document, position:vscode.Position, includeDeclaration:boolean, token: vscode.CancellationToken): Thenable { + private doFindReferences(document:vscode.TextDocument, position:vscode.Position, includeDeclaration:boolean, token: vscode.CancellationToken): Thenable { return new Promise((resolve, reject) => { var filename = this.canonicalizeForWindows(document.getUri().fsPath); var cwd = path.dirname(filename) diff --git a/src/goRename.ts b/src/goRename.ts index 2fef308bc2..69aac39018 100644 --- a/src/goRename.ts +++ b/src/goRename.ts @@ -10,18 +10,13 @@ import path = require('path'); class RenameSupport implements vscode.Modes.IRenameSupport { - public rename(document:vscode.Document, position:vscode.Position, newName: string, token: vscode.CancellationToken): Thenable { - return vscode.workspace.anyDirty().then(anyDirty => { - if (anyDirty) { - vscode.workspace.saveAll(false).then(() => { - return this.doRename(document, position, newName, token); - }); - } + public rename(document:vscode.TextDocument, position:vscode.Position, newName: string, token: vscode.CancellationToken): Thenable { + return vscode.workspace.saveAll(false).then(() => { return this.doRename(document, position, newName, token); }); } - private doRename(document:vscode.Document, position:vscode.Position, newName: string, token: vscode.CancellationToken): Thenable { + private doRename(document:vscode.TextDocument, position:vscode.Position, newName: string, token: vscode.CancellationToken): Thenable { return new Promise((resolve, reject) => { var filename = this.canonicalizeForWindows(document.getUri().fsPath); diff --git a/src/goSuggest.ts b/src/goSuggest.ts index f3765032a7..8c5f03a60c 100644 --- a/src/goSuggest.ts +++ b/src/goSuggest.ts @@ -33,7 +33,7 @@ class SuggestSupport implements vscode.Modes.ISuggestSupport { public triggerCharacters = ['.']; public excludeTokens = ['string', 'comment', 'numeric']; - public suggest(document: vscode.Document, position: vscode.Position, token: vscode.CancellationToken): Promise { + public suggest(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise { return new Promise((resolve, reject) => { var filename = document.getUri().fsPath; diff --git a/typings/vscode.d.ts b/typings/vscode.d.ts index 4e0090b9af..9b274f5428 100644 --- a/typings/vscode.d.ts +++ b/typings/vscode.d.ts @@ -56,14 +56,14 @@ declare module 'vscode' { export function executeCommand(commandId: string, ...rest: any[]): Thenable; } - export interface EditorOptions { + export interface TextEditorOptions { tabSize: number; insertSpaces: boolean; } - export class Document { + export class TextDocument { - constructor(uri: Uri, lines: string[], eol: string, languageId: string, versionId: number); + constructor(uri: Uri, lines: string[], eol: string, languageId: string, versionId: number, isDirty:boolean); /** * Get the associated URI for this document. Most documents have the file:// scheme, indicating that they represent files on disk. @@ -76,6 +76,8 @@ declare module 'vscode' { */ isUntitled(): boolean; + isDirty(): boolean; + /** * The language identifier associated with this document. */ @@ -166,14 +168,14 @@ declare module 'vscode' { export class TextEditor { - constructor(document: Document, selections: Selection[], options: EditorOptions); + constructor(document: TextDocument, selections: Selection[], options: TextEditorOptions); dispose(); /** * Get the document associated with this text editor. The document will be the same for the entire lifetime of this text editor. */ - getDocument(): Document; + getTextDocument(): TextDocument; /** * Get the primary selection on this text editor. In case the text editor has multiple selections, the first one will be returned. @@ -198,12 +200,12 @@ declare module 'vscode' { /** * Get text editor options. */ - getOptions(): EditorOptions; + getOptions(): TextEditorOptions; /** * Change text editor options. */ - setOptions(options: EditorOptions): Thenable; + setOptions(options: TextEditorOptions): Thenable; /** * Perform an edit on the document associated with this text editor. @@ -483,17 +485,15 @@ declare module 'vscode' { */ export class Diagnostic { - public static createErrorDiagnostic(location: Location, message: string): Diagnostic; - - public static createWarningDiagnostic(location: Location, message: string): Diagnostic; - - constructor(severity: DiagnosticSeverity, location: Location, message: string); + constructor(severity: DiagnosticSeverity, location: Location, message: string, source?:string); severity: DiagnosticSeverity; location: Location; message: string; + + source: string; } // TODO@api, TODO@Joh,Ben @@ -517,7 +517,7 @@ declare module 'vscode' { export interface TextEditorOptionsChangeEvent { textEditor: TextEditor; - options: EditorOptions; + options: TextEditorOptions; } export namespace window { @@ -549,8 +549,10 @@ declare module 'vscode' { export function getOutputChannel(name: string): OutputChannel; - // TODO@api - // Justification: Should this be part of the API? Is there a node module that can do the same? + /** + * ✂ - don't use. Will be cut soone! + TODO@api move into a node_module + */ export function runInTerminal(command: string, args: string[], options?: ExecutionOptions): Thenable; } @@ -558,11 +560,11 @@ declare module 'vscode' { /** * An event describing a change in the text of a model. */ - export interface DocumentContentChangeEvent { + export interface TextDocumentContentChangeEvent { /** * The range that got replaced. */ - range: IRange; + range: Range; /** * The length of the range that got replaced. */ @@ -571,23 +573,11 @@ declare module 'vscode' { * The new text for the range. */ text: string; - /** - * The new version id the model has transitioned to. - */ - versionId: number; - /** - * Flag that indicates that this event was generated while undoing. - */ - isUndoing: boolean; - /** - * Flag that indicates that this event was generated while redoing. - */ - isRedoing: boolean; } - export interface DocumentChangeEvent { - document: Document; - contentChanges: DocumentContentChangeEvent[]; + export interface TextDocumentChangeEvent { + document: TextDocument; + contentChanges: TextDocumentContentChangeEvent[]; } // TODO@api in the future there might be multiple opened folder in VSCode @@ -619,17 +609,12 @@ declare module 'vscode' { */ export function saveAll(includeUntitled?: boolean): Thenable; - export function getAllDocuments(): Document[]; - export function getDocument(resource: Uri): Document; - export const onDidAddDocument: Event; - export const onDidRemoveDocument: Event; - export const onDidChangeDocument: Event; - export const onDidSaveDocument: Event; - - /** - * are there any dirty files - */ - export function anyDirty(): Thenable; + export function getTextDocuments(): TextDocument[]; + export function getTextDocument(resource: Uri): TextDocument; + export const onDidAddTextDocument: Event; + export const onDidRemoveTextDocument: Event; + export const onDidChangeTextDocument: Event; + export const onDidSaveTextDocument: Event; } export namespace languages { @@ -661,32 +646,13 @@ declare module 'vscode' { export function addErrorLanguageStatus(language: LanguageSelector | Uri | Uri[], message: string | { octicon: string; message: string; }, command: string | CommandCallback): Disposable; } - export namespace plugins { - export function getStateObject(pluginId: string, global?: boolean): Memento; + export namespace extensions { - export function getConfigurationObject(pluginId: string): ReadOnlyMemento; - } + export function getStateMemento(extensionId: string, global?: boolean): Memento; - /** - * A range in the editor. This interface is suitable for serialization. - */ - interface IRange { - /** - * Line number on which the range starts (starts at 1). - */ - startLineNumber:number; - /** - * Column on which the range starts in line `startLineNumber` (starts at 1). - */ - startColumn:number; - /** - * Line number on which the range ends. - */ - endLineNumber:number; - /** - * Column on which the range ends in line `endLineNumber`. - */ - endColumn:number; + export function getConfigurationMemento(extensionId: string): ReadOnlyMemento; + + export function getExtension(extensionId: string): any; } export interface IHTMLContentElement { @@ -809,7 +775,7 @@ declare module 'vscode' { // --- Begin IDeclarationSupport export interface IDeclarationSupport { tokens?: string[]; - findDeclaration(document: Document, position: Position, token: CancellationToken): Thenable; + findDeclaration(document: TextDocument, position: Position, token: CancellationToken): Thenable; } var DeclarationSupport: { register(modeId: string, declarationSupport: IDeclarationSupport): void; @@ -818,8 +784,8 @@ declare module 'vscode' { // --- Begin ICodeLensSupport export interface ICodeLensSupport { - findCodeLensSymbols(document: Document, token: CancellationToken): Thenable; - findCodeLensReferences(document: Document, requests: ICodeLensSymbolRequest[], token: CancellationToken): Thenable; + findCodeLensSymbols(document: TextDocument, token: CancellationToken): Thenable; + findCodeLensReferences(document: TextDocument, requests: ICodeLensSymbolRequest[], token: CancellationToken): Thenable; } export interface ICodeLensSymbolRequest { position: Position; @@ -843,7 +809,7 @@ declare module 'vscode' { range:Range; } export interface IOccurrencesSupport { - findOccurrences(resource: Document, position: Position, token: CancellationToken): Thenable; + findOccurrences(resource: TextDocument, position: Position, token: CancellationToken): Thenable; } var OccurrencesSupport: { register(modeId: string, occurrencesSupport:IOccurrencesSupport): void; @@ -859,7 +825,7 @@ declare module 'vscode' { children?: IOutlineEntry[]; } export interface IOutlineSupport { - getOutline(document: Document, token: CancellationToken): Thenable; + getOutline(document: TextDocument, token: CancellationToken): Thenable; outlineGroupLabel?: { [name: string]: string; }; } var OutlineSupport: { @@ -880,8 +846,8 @@ declare module 'vscode' { } export interface IQuickFixSupport { - getQuickFixes(resource: Document, marker: Range, token: CancellationToken): Thenable; - runQuickFixAction(resource: Document, range: Range, id: any, token: CancellationToken): Thenable; + getQuickFixes(resource: TextDocument, marker: Range, token: CancellationToken): Thenable; + runQuickFixAction(resource: TextDocument, range: Range, id: any, token: CancellationToken): Thenable; } var QuickFixSupport: { register(modeId: string, quickFixSupport:IQuickFixSupport): void @@ -896,7 +862,7 @@ declare module 'vscode' { * @returns a list of reference of the symbol at the position in the * given resource. */ - findReferences(document: Document, position: Position, includeDeclaration: boolean, token: CancellationToken): Thenable; + findReferences(document: TextDocument, position: Position, includeDeclaration: boolean, token: CancellationToken): Thenable; } var ReferenceSupport: { register(modeId: string, quickFixSupport:IReferenceSupport): void; @@ -936,7 +902,7 @@ declare module 'vscode' { /** * @returns the parameter hints for the specified position in the file. */ - getParameterHints(document: Document, position: Position, token: CancellationToken): Thenable; + getParameterHints(document: TextDocument, position: Position, token: CancellationToken): Thenable; } var ParameterHintsSupport: { register(modeId: string, parameterHintsSupport:IParameterHintsSupport): void; @@ -951,7 +917,7 @@ declare module 'vscode' { className?: string; } export interface IExtraInfoSupport { - computeInfo(document: Document, position: Position, token: CancellationToken): Thenable; + computeInfo(document: TextDocument, position: Position, token: CancellationToken): Thenable; } var ExtraInfoSupport: { register(modeId: string, extraInfoSupport:IExtraInfoSupport): void; @@ -966,7 +932,7 @@ declare module 'vscode' { } export interface IRenameSupport { filter?: string[]; - rename(document: Document, position: Position, newName: string, token: CancellationToken): Thenable; + rename(document: TextDocument, position: Position, newName: string, token: CancellationToken): Thenable; } var RenameSupport: { register(modeId: string, renameSupport:IRenameSupport): void; @@ -989,7 +955,7 @@ declare module 'vscode' { /** * The range to replace. This can be empty to emulate a simple insert. */ - range: IRange; + range: Range; /** * The text to replace with. This can be null to emulate a simple delete. */ @@ -1003,10 +969,10 @@ declare module 'vscode' { * (3) format on keystroke */ export interface IFormattingSupport { - formatDocument: (document: Document, options: IFormattingOptions, token: CancellationToken) => Thenable; - formatRange?: (document: Document, range: Range, options: IFormattingOptions, token: CancellationToken) => Thenable; + formatDocument: (document: TextDocument, options: IFormattingOptions, token: CancellationToken) => Thenable; + formatRange?: (document: TextDocument, range: Range, options: IFormattingOptions, token: CancellationToken) => Thenable; autoFormatTriggerCharacters?: string[]; - formatAfterKeystroke?: (document: Document, position: Position, ch: string, options: IFormattingOptions, token: CancellationToken) => Thenable; + formatAfterKeystroke?: (document: TextDocument, position: Position, ch: string, options: IFormattingOptions, token: CancellationToken) => Thenable; } var FormattingSupport: { register(modeId: string, formattingSupport:IFormattingSupport): void; @@ -1043,8 +1009,8 @@ declare module 'vscode' { sortBy?: ISortingTypeAndSeparator[]; - suggest: (document: Document, position: Position, token: CancellationToken) => Thenable; - getSuggestionDetails? : (document: Document, position: Position, suggestion:ISuggestion, token: CancellationToken) => Thenable; + suggest: (document: TextDocument, position: Position, token: CancellationToken) => Thenable; + getSuggestionDetails? : (document: TextDocument, position: Position, suggestion:ISuggestion, token: CancellationToken) => Thenable; } var SuggestSupport: { register(modeId:string, suggestSupport:ISuggestSupport): void; @@ -1184,10 +1150,6 @@ declare module 'vscode' { } - module Plugins { - function get(pluginId:string): any; - } - /** * DO NOT USE. */ From 8e96786ace1b59901d289f2fbfd4d92c1670ca39 Mon Sep 17 00:00:00 2001 From: Luke Hoban Date: Fri, 25 Sep 2015 08:48:24 -0700 Subject: [PATCH 3/3] Fix issues in Suggest and Format after API update --- src/goFormat.ts | 9 +-------- src/goSuggest.ts | 2 +- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/src/goFormat.ts b/src/goFormat.ts index 295d348809..b6cdbc6a9f 100644 --- a/src/goFormat.ts +++ b/src/goFormat.ts @@ -52,14 +52,7 @@ class FormattingSupport implements vscode.Modes.IFormattingSupport { // specific edits instead of replace whole buffer var lastLine = document.getLineCount(); var lastLineLastCol = document.getLineMaxColumn(lastLine); - // API TODO: ISingleEditOperation is using IRange instead of Range - //var range = new vscode.Range(1, 1, lastLine, lastLineLastCol); - var range = { - startLineNumber: 1, - startColumn: 1, - endLineNumber: lastLine, - endColumn: lastLineLastCol - }; + var range = new vscode.Range(1, 1, lastLine, lastLineLastCol); return resolve([{ text: result, range diff --git a/src/goSuggest.ts b/src/goSuggest.ts index 8c5f03a60c..f66df0fcd7 100644 --- a/src/goSuggest.ts +++ b/src/goSuggest.ts @@ -39,9 +39,9 @@ class SuggestSupport implements vscode.Modes.ISuggestSupport { // get current word var wordAtPosition = document.getWordRangeAtPosition(position); - var word = document.getTextInRange(wordAtPosition); var currentWord = ''; if (wordAtPosition && wordAtPosition.start.column < position.column) { + var word = document.getTextInRange(wordAtPosition); currentWord = word.substr(0, position.column - wordAtPosition.start.column); }