export function activate(context: ExtensionContext) {

    console.log("Write-Good Linter active...");
    diagnosticCollection = languages.createDiagnosticCollection("Write-Good Lints");
    diagnosticMap = new Map();

    function isWriteGoodLanguage(languageId) {
        let wgLanguages: string = workspace.getConfiguration('write-good').get('languages');
        return (wgLanguages.indexOf(languageId) > -1 || wgLanguages === '*');
    }
    
    context.subscriptions.push(workspace.onDidChangeTextDocument(event => {
        if (isWriteGoodLanguage(event.document.languageId)) {
            doLint(event.document);
        }
    }));

    context.subscriptions.push(workspace.onDidOpenTextDocument(event => {
        if (isWriteGoodLanguage(event.languageId)) {
            doLint(event);
        }
    }));

    context.subscriptions.push(workspace.onDidCloseTextDocument(event => {
        if (diagnosticMap.has(event.uri.toString())) {
            diagnosticMap.delete(event.uri.toString());
        }
        resetDiagnostics();
    }));
}
function trackFutureVirtualDocuments(server: OmniSharpServer, eventStream: EventStream): IDisposable {
    let onTextDocumentOpen = workspace.onDidOpenTextDocument(async document => {
        if (shouldIgnoreDocument(document, server)) {
            return;
        }

        await openVirtualDocument(document, server, eventStream);
    });

    let onTextDocumentChange = workspace.onDidChangeTextDocument(async changeEvent => {
        const document = changeEvent.document;

        if (shouldIgnoreDocument(document, server)) {
            return;
        }

        await changeVirtualDocument(document, server, eventStream);
    });

    let onTextDocumentClose = workspace.onDidCloseTextDocument(async document => {
        if (shouldIgnoreDocument(document, server)) {
            return;
        }

        await closeVirtualDocument(document, server, eventStream);
    });

    // We already track text document changes for virtual documents in our change forwarder.
    return new CompositeDisposable(
        onTextDocumentOpen,
        onTextDocumentClose,
        onTextDocumentChange);
}
Example #3
0
function loadConfiguration(context: ExtensionContext): void {
	const section = workspace.getConfiguration('npm');
	if (section) {
		validationEnabled = section.get<boolean>('validate.enable', true);
	}
	diagnosticCollection.clear();

	if (validationEnabled) {
		workspace.onDidSaveTextDocument(document => {
			validateDocument(document);
		}, null, context.subscriptions);
		window.onDidChangeActiveTextEditor(editor => {
			if (editor && editor.document) {
				validateDocument(editor.document);
			}
		}, null, context.subscriptions);

		// remove markers on close
		workspace.onDidCloseTextDocument(_document => {
			diagnosticCollection.clear();
		}, null, context.subscriptions);

		// workaround for onDidOpenTextDocument
		// workspace.onDidOpenTextDocument(document => {
		// 	console.log("onDidOpenTextDocument ", document.fileName);
		// 	validateDocument(document);
		// }, null, context.subscriptions);
		validateAllDocuments();
	}
}
Example #4
0
const startLinting = (context: ExtensionContext): void => {
    const diagnostics = vscode.languages.createDiagnosticCollection("fish");
    context.subscriptions.push(diagnostics);

    const lint = (document: TextDocument) => {
        if (isSavedFishDocument(document)) {
            return getDiagnostics(document)
                .catch((error) => {
                    vscode.window.showErrorMessage(error.toString());
                    diagnostics.delete(document.uri);
                })
                // tslint:disable-next-line:readonly-array
                .then((d) => diagnostics.set(document.uri, d as Diagnostic[]));
        } else {
            Promise.resolve();
        }
    };

    vscode.workspace.onDidOpenTextDocument(lint, null, context.subscriptions);
    vscode.workspace.onDidSaveTextDocument(lint, null, context.subscriptions);
    vscode.workspace.textDocuments.forEach(lint);

    // Remove diagnostics for closed files
    vscode.workspace.onDidCloseTextDocument(
        (d) => diagnostics.delete(d.uri), null, context.subscriptions);
};
Example #5
0
	client.onReady().then(() => {
		disposable = client.onTelemetry(e => {
			if (telemetryReporter) {
				telemetryReporter.sendTelemetryEvent(e.key, e.data);
			}
		});

		// handle content request
		client.onRequest(VSCodeContentRequest.type, (uriPath: string) => {
			let uri = Uri.parse(uriPath);
			return workspace.openTextDocument(uri).then(doc => {
				return doc.getText();
			}, error => {
				return Promise.reject(error);
			});
		});

		let handleContentChange = (uri: Uri) => {
			if (uri.scheme === 'vscode' && uri.authority === 'schemas') {
				client.sendNotification(SchemaContentChangeNotification.type, uri.toString());
			}
		};
		toDispose.push(workspace.onDidChangeTextDocument(e => handleContentChange(e.document.uri)));
		toDispose.push(workspace.onDidCloseTextDocument(d => handleContentChange(d.uri)));

		client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));

		initFoldingProvider();
		toDispose.push(workspace.onDidChangeConfiguration(c => {
			if (c.affectsConfiguration(foldingSetting)) {
				initFoldingProvider();
			}
		}));
		toDispose.push({ dispose: () => foldingProviderRegistration && foldingProviderRegistration.dispose() });
	});
Example #6
0
export async function activate(context: ExtensionContext) {
    const logger = new Logger();

    let requestController = new RequestController(context, logger);
    let historyController = new HistoryController(logger);
    let responseController = new ResponseController();
    let codeSnippetController = new CodeSnippetController();
    let environmentController = new EnvironmentController(await EnvironmentController.getCurrentEnvironment());
    context.subscriptions.push(requestController);
    context.subscriptions.push(historyController);
    context.subscriptions.push(responseController);
    context.subscriptions.push(codeSnippetController);
    context.subscriptions.push(environmentController);
    context.subscriptions.push(commands.registerCommand('rest-client.request', ((document: TextDocument, range: Range) => requestController.run(range))));
    context.subscriptions.push(commands.registerCommand('rest-client.rerun-last-request', () => requestController.rerun()));
    context.subscriptions.push(commands.registerCommand('rest-client.cancel-request', () => requestController.cancel()));
    context.subscriptions.push(commands.registerCommand('rest-client.history', () => historyController.save()));
    context.subscriptions.push(commands.registerCommand('rest-client.clear-history', () => historyController.clear()));
    context.subscriptions.push(commands.registerCommand('rest-client.save-response', () => responseController.save()));
    context.subscriptions.push(commands.registerCommand('rest-client.save-response-body', () => responseController.saveBody()));
    context.subscriptions.push(commands.registerCommand('rest-client.copy-response-body', () => responseController.copyBody()));
    context.subscriptions.push(commands.registerCommand('rest-client.generate-codesnippet', () => codeSnippetController.run()));
    context.subscriptions.push(commands.registerCommand('rest-client.copy-codesnippet', () => codeSnippetController.copy()));
    context.subscriptions.push(commands.registerCommand('rest-client.copy-request-as-curl', () => codeSnippetController.copyAsCurl()));
    context.subscriptions.push(commands.registerCommand('rest-client.switch-environment', () => environmentController.switchEnvironment()));
    context.subscriptions.push(commands.registerCommand('rest-client.clear-aad-token-cache', () => AadTokenCache.clear()));
    context.subscriptions.push(commands.registerCommand('rest-client._openDocumentLink', args => {
        workspace.openTextDocument(Uri.parse(args.path)).then(window.showTextDocument, error => {
            window.showErrorMessage(error.message);
        });
    }));

    const documentSelector = [
        { language: 'http', scheme: 'file' },
        { language: 'http', scheme: 'untitled' },
    ];

    context.subscriptions.push(languages.registerCompletionItemProvider(documentSelector, new HttpCompletionItemProvider()));
    context.subscriptions.push(languages.registerCompletionItemProvider(documentSelector, new RequestVariableCompletionItemProvider(), '.'));
    context.subscriptions.push(languages.registerHoverProvider(documentSelector, new CustomVariableHoverProvider()));
    context.subscriptions.push(languages.registerHoverProvider(documentSelector, new RequestVariableHoverProvider()));
    context.subscriptions.push(
        new ConfigurationDependentRegistration(
            () => languages.registerCodeLensProvider(documentSelector, new HttpCodeLensProvider()),
            s => s.enableSendRequestCodeLens));
    context.subscriptions.push(
        new ConfigurationDependentRegistration(
            () => languages.registerCodeLensProvider(documentSelector, new CustomVariableReferencesCodeLensProvider()),
            s => s.enableCustomVariableReferencesCodeLens));
    context.subscriptions.push(languages.registerDocumentLinkProvider(documentSelector, new RequestBodyDocumentLinkProvider()));
    context.subscriptions.push(languages.registerDefinitionProvider(documentSelector, new CustomVariableDefinitionProvider()));
    context.subscriptions.push(languages.registerReferenceProvider(documentSelector, new CustomVariableReferenceProvider()));
    context.subscriptions.push(languages.registerDocumentSymbolProvider(documentSelector, new HttpDocumentSymbolProvider()));

    const diagnosticsProviders = new VariableDiagnosticsProvider();
    workspace.onDidOpenTextDocument(diagnosticsProviders.checkVariables, diagnosticsProviders, context.subscriptions);
    workspace.onDidCloseTextDocument(diagnosticsProviders.deleteDocumentFromDiagnosticCollection, diagnosticsProviders, context.subscriptions);
    workspace.onDidSaveTextDocument(diagnosticsProviders.checkVariables, diagnosticsProviders, context.subscriptions);
}
export function activate(context: vscode.ExtensionContext) : api.PrettifySymbolsMode {
	function registerTextEditorCommand(commandId:string, run:(editor:vscode.TextEditor,edit:vscode.TextEditorEdit,...args:any[])=>void): void {
    context.subscriptions.push(vscode.commands.registerTextEditorCommand(commandId, run));
  }
  function registerCommand(commandId:string, run:(...args:any[])=>void): void {
    context.subscriptions.push(vscode.commands.registerCommand(commandId, run));
  }

  registerTextEditorCommand('prettifySymbolsMode.copyWithSubstitutions', copyWithSubstitutions);
  registerCommand('prettifySymbolsMode.disablePrettySymbols', disablePrettySymbols);
  registerCommand('prettifySymbolsMode.enablePrettySymbols', enablePrettySymbols);
  registerCommand('prettifySymbolsMode.togglePrettySymbols', (editor: vscode.TextEditor) => {
    if(prettySymbolsEnabled) {
      disablePrettySymbols();
    } else {
      enablePrettySymbols();
    }
  });

  registerCommand('extension.disablePrettySymbols', () => { vscode.window.showErrorMessage('Command "extension.disablePrettySymbols" is deprecated; use "prettifySymbolsMode.disablePrettySymbols" instead.') });
  registerCommand('extension.enablePrettySymbols', () => { vscode.window.showErrorMessage('Command "extension.enablePrettySymbols" is deprecated; use "prettifySymbolsMode.enablePrettySymbols" instead.') });
  registerCommand('extension.togglePrettySymbols', () => { vscode.window.showErrorMessage('Command "extension.togglePrettySymbols" is deprecated; use "prettifySymbolsMode.togglePrettySymbols" instead.') });

  context.subscriptions.push(vscode.window.onDidChangeTextEditorSelection(selectionChanged));

  context.subscriptions.push(vscode.workspace.onDidOpenTextDocument(openDocument));
  context.subscriptions.push(vscode.workspace.onDidCloseTextDocument(closeDocument));
  context.subscriptions.push(vscode.workspace.onDidChangeConfiguration(onConfigurationChanged));

  context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor(changeActiveTextEditor));

  reloadConfiguration();

  const result : api.PrettifySymbolsMode = {
    onDidEnabledChange: function(handler: (enabled:boolean)=>void) : vscode.Disposable {
      onEnabledChangeHandlers.add(handler);
      return {
        dispose() {
          onEnabledChangeHandlers.delete(handler);
        }
      }
    },
    isEnabled: function() : boolean {
      return prettySymbolsEnabled;
    },
    registerSubstitutions: function(substitutions: api.LanguageEntry) : vscode.Disposable {
      additionalSubstitutions.add(substitutions);
      // TODO: this could be smart about not unloading & reloading everything 
      reloadConfiguration();
      return {
        dispose() {
          additionalSubstitutions.delete(substitutions);
        }
      }
    }
  };

  return result;
}
Example #8
0
 const chan = eventChannel((emit) => {
   vscode.workspace.onDidCloseTextDocument(() => {
     if (!vscode.window.activeTextEditor) return;
     const doc = vscode.window.activeTextEditor.document;
     emit(textContentChanged(doc.uri.fsPath.replace(".git", ""), fs.readFileSync(doc.uri.fsPath.replace(".git", ""), "utf8")))
   });
   return () => {};
 });
Example #9
0
	client.onReady().then(() => {
		client.onTelemetry(e => {
			if (telemetryReporter) {
				telemetryReporter.sendTelemetryEvent(e.key, e.data);
			}
		});

		// handle content request
		client.onRequest(VSCodeContentRequest.type, (uriPath: string) => {
			let uri = Uri.parse(uriPath);
			return workspace.openTextDocument(uri).then(doc => {
				return doc.getText();
			}, error => {
				return Promise.reject(error);
			});
		});

		let handleContentChange = (uri: Uri) => {
			if (uri.scheme === 'vscode' && uri.authority === 'schemas') {
				client.sendNotification(SchemaContentChangeNotification.type, uri.toString());
			}
		};
		toDispose.push(workspace.onDidChangeTextDocument(e => handleContentChange(e.document.uri)));
		toDispose.push(workspace.onDidCloseTextDocument(d => handleContentChange(d.uri)));

		client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));

		// register color provider
		toDispose.push(languages.registerColorProvider(documentSelector, {
			provideDocumentColors(document: TextDocument): Thenable<ColorInformation[]> {
				let params: DocumentColorParams = {
					textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document)
				};
				return client.sendRequest(DocumentColorRequest.type, params).then(symbols => {
					return symbols.map(symbol => {
						let range = client.protocol2CodeConverter.asRange(symbol.range);
						let color = new Color(symbol.color.red, symbol.color.green, symbol.color.blue, symbol.color.alpha);
						return new ColorInformation(range, color);
					});
				});
			},
			provideColorPresentations(color: Color, context): Thenable<ColorPresentation[]> {
				let params: ColorPresentationParams = {
					textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(context.document),
					color: color,
					range: client.code2ProtocolConverter.asRange(context.range)
				};
				return client.sendRequest(ColorPresentationRequest.type, params).then(presentations => {
					return presentations.map(p => {
						let presentation = new ColorPresentation(p.label);
						presentation.textEdit = p.textEdit && client.protocol2CodeConverter.asTextEdit(p.textEdit);
						presentation.additionalTextEdits = p.additionalTextEdits && client.protocol2CodeConverter.asTextEdits(p.additionalTextEdits);
						return presentation;
					});
				});
			}
		}));
	});
Example #10
0
			const p = new Promise((resolve, reject) => {
				const sub = workspace.onDidCloseTextDocument(doc => {
					try {
						sub.dispose();
						assert.ok(window.activeTextEditor === undefined);
						assert.equal(window.visibleTextEditors.length, 0);
						resolve();
					} catch (e) {
						reject(e);
					}
				});
			});
Example #11
0
	public constructor(client: ITypescriptServiceClient) {
		this.client = client;
		this.config = Configuration.def();
		this.formatOptions = Object.create(null);
		Workspace.onDidCloseTextDocument((textDocument) => {
			let key = textDocument.uri.toString();
			// When a document gets closed delete the cached formatting options.
			// This is necessary sine the tsserver now closed a project when its
			// last file in it closes which drops the stored formatting options
			// as well.
			delete this.formatOptions[key];
		});
	}
export function activate(context: ExtensionContext) {
  const abapFS = new FsProvider()
  const sub = context.subscriptions
  // register the filesystem type
  sub.push(
    workspace.registerFileSystemProvider(ADTSCHEME, abapFS, {
      isCaseSensitive: true
    })
  )

  // change document listener, for locking (and possibly validation in future)
  sub.push(workspace.onDidChangeTextDocument(documentChangedListener))
  // opened document listener, for main program
  sub.push(workspace.onDidOpenTextDocument(documentOpenListener))
  // closed document listener, for locking
  sub.push(workspace.onDidCloseTextDocument(documentClosedListener))
  // Editor changed listener, updates context and icons
  sub.push(window.onDidChangeActiveTextEditor(activeTextEditorChangedListener))

  // connect command
  sub.push(commands.registerCommand("abapfs.connect", connectAdtServer))

  // activate command
  sub.push(commands.registerCommand("abapfs.activate", activateCurrent))

  // search command
  sub.push(commands.registerCommand("abapfs.search", searchAdtObject))

  // create command
  sub.push(commands.registerCommand("abapfs.create", createAdtObject))

  // execute Abap command
  sub.push(commands.registerCommand("abapfs.execute", executeAbap))

  // add favourite
  sub.push(commands.registerCommand("abapfs.addfavourite", addFavourite))

  // add favourite
  sub.push(commands.registerCommand("abapfs.deletefavourite", deleteFavourite))

  const fav = FavouritesProvider.get()
  fav.storagePath = context.globalStoragePath
  sub.push(window.registerTreeDataProvider("abapfs.favorites", fav))

  startLanguageClient(context)

  commands.executeCommand("setContext", "abapfs:extensionActive", true)
  restoreLocks()

  log(`Activated,pid=${process.pid}`)
}
Example #13
0
export function activate(context: vscode.ExtensionContext) {
  // To make us VS Code agnostic outside of this file
  const pluginSettings = getExtensionSettings()
  const jestPath = pathToJest(pluginSettings)
  const configPath = pathToConfig(pluginSettings)
  const currentJestVersion = 20
  const workspace = new ProjectWorkspace(pluginSettings.rootPath, jestPath, configPath, currentJestVersion)

  // Create our own console
  const channel = vscode.window.createOutputChannel('Jest')

  // We need a singleton to represent the extension
  extensionInstance = new JestExt(workspace, channel, pluginSettings)

  const languages = [
    { language: 'javascript' },
    { language: 'javascriptreact' },
    { language: 'typescript' },
    { language: 'typescriptreact' },
  ]
  context.subscriptions.push(
    registerStatusBar(channel),
    vscode.commands.registerTextEditorCommand(`${extensionName}.start`, () => {
      vscode.window.showInformationMessage('Started Jest, press escape to hide this message.')
      extensionInstance.startProcess()
    }),
    vscode.commands.registerTextEditorCommand(`${extensionName}.stop`, () => extensionInstance.stopProcess()),
    vscode.commands.registerTextEditorCommand(`${extensionName}.show-channel`, () => {
      channel.show()
    }),
    ...registerSnapshotCodeLens(pluginSettings.enableSnapshotPreviews),
    ...registerSnapshotPreview(),
    ...registerCoverageCodeLens(extensionInstance),
    registerToggleCoverageOverlay(pluginSettings.showCoverageOnLoad),
    vscode.commands.registerCommand(`${extensionName}.run-test`, extensionInstance.runTest),
    vscode.languages.registerCodeLensProvider(languages, extensionInstance.debugCodeLensProvider),
    vscode.workspace.onDidChangeConfiguration(e => {
      if (e.affectsConfiguration('jest')) {
        const updatedSettings = getExtensionSettings()
        extensionInstance.triggerUpdateSettings(updatedSettings)
      }
    }),

    vscode.workspace.onDidCloseTextDocument(document => {
      extensionInstance.onDidCloseTextDocument(document)
    }),

    vscode.window.onDidChangeActiveTextEditor(extensionInstance.onDidChangeActiveTextEditor, extensionInstance),
    vscode.workspace.onDidChangeTextDocument(extensionInstance.onDidChangeTextDocument, extensionInstance)
  )
}
 public activate(subscriptions: vscode.Disposable[]) {
     this.diagnosticCollection = vscode.languages.createDiagnosticCollection();
     vscode.workspace.onDidOpenTextDocument(this.doBsllint, this, subscriptions);
     vscode.workspace.onDidCloseTextDocument((textDocument) => {
         this.diagnosticCollection.delete(textDocument.uri);
     }, null, subscriptions);
     vscode.workspace.onDidSaveTextDocument(this.doBsllint, this);
     if (!this.statusBarItem) {
         this.statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
     }
     this.args = ["-encoding=utf-8", "-check"];
     this.commandId = this.getCommandId();
     vscode.workspace.textDocuments.forEach(this.doBsllint, this);        
 }
    public activate(subscriptions: vscode.Disposable[]) {
        // this.command = vscode.commands.registerCommand(PuppetLintProvider.commandId, this.runCodeAction, this);
        // subscriptions.push(this);
        this.diagnosticCollection = vscode.languages.createDiagnosticCollection();

        vscode.workspace.onDidOpenTextDocument(this.doPuppetLint, this, subscriptions);
        vscode.workspace.onDidCloseTextDocument((textDocument)=> {
            this.diagnosticCollection.delete(textDocument.uri);
        }, null, subscriptions);

        vscode.workspace.onDidSaveTextDocument(this.doPuppetLint, this);

        // puppet-lint all open Puppet documents
        vscode.workspace.textDocuments.forEach(this.doPuppetLint, this);
    }
Example #16
0
async function doValidate(document: TextDocument) {
	let report = null;

	let documentWasClosed = false; // track whether the document was closed while getInstalledModules/'npm ls' runs
	const listener = workspace.onDidCloseTextDocument(doc => {
		if (doc.uri === document.uri) {
			documentWasClosed = true;
		}
	});

	try {
		report = await getInstalledModules(path.dirname(document.fileName));
	} catch (e) {
		listener.dispose();
		return;
	}
	try {
		diagnosticCollection.clear();

		if (report.invalid && report.invalid === true) {
			return;
		}
		if (!anyModuleErrors(report)) {
			return;
		}
		if (documentWasClosed || !document.getText()) {
			return;
		}
		const sourceRanges = parseSourceRanges(document.getText());
		const dependencies = report.dependencies;
		const diagnostics: Diagnostic[] = [];

		for (var moduleName in dependencies) {
			if (dependencies.hasOwnProperty(moduleName)) {
				const diagnostic = getDiagnostic(document, report, moduleName, sourceRanges);
				if (diagnostic) {
					diagnostic.source = 'npm';
					diagnostics.push(diagnostic);
				}
			}
		}
		//console.log("diagnostic count ", diagnostics.length, " ", document.uri.fsPath);
		diagnosticCollection.set(document.uri, diagnostics);
	} catch (e) {
		window.showInformationMessage(`[npm-script-runner] Cannot validate the package.json ` + e);
		console.log(`npm-script-runner: 'error while validating package.json stacktrace: ${e.stack}`);
	}
}
export function activate(context: ExtensionContext) {
	const status = window.createStatusBarItem(StatusBarAlignment.Right, 100);
	status.command = 'extension.selectedLines';
	context.subscriptions.push(status);

	context.subscriptions.push(window.onDidChangeActiveTextEditor(e => updateStatus(status)));
	context.subscriptions.push(window.onDidChangeTextEditorSelection(e => updateStatus(status)));
	context.subscriptions.push(window.onDidChangeTextEditorViewColumn(e => updateStatus(status)));
	context.subscriptions.push(workspace.onDidOpenTextDocument(e => updateStatus(status)));
	context.subscriptions.push(workspace.onDidCloseTextDocument(e => updateStatus(status)));

	context.subscriptions.push(commands.registerCommand('extension.selectedLines', () => {
		window.showInformationMessage(getSelectedLines());
	}));

	updateStatus(status);
}
Example #18
0
		return workspace.openTextDocument(Uri.parse('untitled://' + path)).then(doc => {
			assert.equal(doc.uri.scheme, 'untitled');
			assert.ok(doc.isDirty);

			let closed: TextDocument;
			let d0 = workspace.onDidCloseTextDocument(e => closed = e);

			return doc.save().then(() => {
				assert.ok(closed === doc);
				assert.ok(!doc.isDirty);
				assert.ok(fs.existsSync(path));

				d0.dispose();

				return deleteFile(Uri.file(join(workspace.rootPath, './newfile.txt')));
			});
		});
export function activate(context: ExtensionContext) {

    // Create a status bar item
    const status = window.createStatusBarItem(StatusBarAlignment.Left, 1000000);
    context.subscriptions.push(status);

    // Update status bar item based on events for multi root folder changes
    context.subscriptions.push(workspace.onDidChangeWorkspaceFolders(e => updateStatus(status)));

    // Update status bar item based on events for configuration
    context.subscriptions.push(workspace.onDidChangeConfiguration(e => this.updateStatus(status)));

    // Update status bar item based on events around the active editor
    context.subscriptions.push(window.onDidChangeActiveTextEditor(e => updateStatus(status)));
    context.subscriptions.push(window.onDidChangeTextEditorViewColumn(e => updateStatus(status)));
    context.subscriptions.push(workspace.onDidOpenTextDocument(e => updateStatus(status)));
    context.subscriptions.push(workspace.onDidCloseTextDocument(e => updateStatus(status)));

    updateStatus(status);
}
Example #20
0
    constructor()
    {
        this.delayers = Object.create(null);

        let subscriptions: vscode.Disposable[] = [];
        vscode.workspace.onDidChangeTextDocument((e) => this.onChangeTextHandler(e.document), null, subscriptions);
        vscode.workspace.onDidCloseTextDocument((textDocument)=> { delete this.delayers[textDocument.uri.toString()]; }, null, subscriptions);
        vscode.window.onDidChangeActiveTextEditor(editor => { this.onChangeEditorHandler(editor) }, null, subscriptions);
        this.disposable = vscode.Disposable.from(...subscriptions);

        this.todoCommentDecoration = vscode.window.createTextEditorDecorationType({
            overviewRulerLane: vscode.OverviewRulerLane.Right,
            color: "rgba(91, 199, 235, 1)",
            overviewRulerColor: 'rgba(144, 195, 212, 0.7)', // Light Blue
            isWholeLine: false,
            backgroundColor: 'rgba(91, 199, 235, 0.1)'
        });

        this.styleTodoComments();
    }
Example #21
0
File: crane.ts Project: ciruz/crane
    constructor(languageClient: LanguageClient)
    {
        this.langClient = languageClient;

        this.delayers = Object.create(null);

        let subscriptions: Disposable[] = [];

        workspace.onDidChangeTextDocument((e) => this.onChangeTextHandler(e.document), null, subscriptions);
        workspace.onDidCloseTextDocument((textDocument)=> { delete this.delayers[textDocument.uri.toString()]; }, null, subscriptions);
        workspace.onDidSaveTextDocument((document) => this.handleFileSave());

        this.disposable = Disposable.from(...subscriptions);

        if (!this.statusBarItem) {
            this.statusBarItem = window.createStatusBarItem(StatusBarAlignment.Left);
            this.statusBarItem.hide();
        }

        this.doInit();
    }
Example #22
0
export function activate(context: ExtensionContext)
{
  const isabelle_home = library.get_configuration<string>("home")
  const isabelle_args = library.get_configuration<Array<string>>("args")
  const cygwin_root = library.get_configuration<string>("cygwin_root")


  /* server */

  if (isabelle_home === "")
    window.showErrorMessage("Missing user settings: isabelle.home")
  else {
    const isabelle_tool = isabelle_home + "/bin/isabelle"
    const standard_args = ["-o", "vscode_unicode_symbols", "-o", "vscode_pide_extensions"]

    const server_options: ServerOptions =
      library.platform_is_windows() ?
        { command:
            (cygwin_root === "" ? path.join(isabelle_home, "contrib", "cygwin") : cygwin_root) +
            "/bin/bash",
          args: ["-l", isabelle_tool, "vscode_server"].concat(standard_args, isabelle_args) } :
        { command: isabelle_tool,
          args: ["vscode_server"].concat(standard_args, isabelle_args) };
    const language_client_options: LanguageClientOptions = {
      documentSelector: [
        { language: "isabelle", scheme: "file" },
        { language: "isabelle-ml", scheme: "file" },
        { language: "bibtex", scheme: "file" }
      ]
    };

    const language_client =
      new LanguageClient("Isabelle", server_options, language_client_options, false)


    /* decorations */

    decorations.setup(context)
    context.subscriptions.push(
      workspace.onDidChangeConfiguration(() => decorations.setup(context)),
      workspace.onDidChangeTextDocument(event => decorations.touch_document(event.document)),
      window.onDidChangeActiveTextEditor(decorations.update_editor),
      workspace.onDidCloseTextDocument(decorations.close_document))

    language_client.onReady().then(() =>
      language_client.onNotification(protocol.decoration_type, decorations.apply_decoration))


    /* caret handling */

    function update_caret()
    {
      const editor = window.activeTextEditor
      let caret_update: protocol.Caret_Update = {}
      if (editor) {
        const uri = editor.document.uri
        const cursor = editor.selection.active
        if (library.is_file(uri) && cursor)
          caret_update = { uri: uri.toString(), line: cursor.line, character: cursor.character }
      }
      if (last_caret_update !== caret_update) {
        if (caret_update.uri)
          language_client.sendNotification(protocol.caret_update_type, caret_update)
        last_caret_update = caret_update
      }
    }

    function goto_file(caret_update: protocol.Caret_Update)
    {
      function move_cursor(editor: TextEditor)
      {
        const pos = new Position(caret_update.line || 0, caret_update.character || 0)
        editor.selections = [new Selection(pos, pos)]
      }

      if (caret_update.uri) {
        workspace.openTextDocument(Uri.parse(caret_update.uri)).then(document =>
        {
          const editor = library.find_file_editor(document.uri)
          const column = editor ? editor.viewColumn : ViewColumn.One
          window.showTextDocument(document, column, !caret_update.focus).then(move_cursor)
        })
      }
    }

    language_client.onReady().then(() =>
    {
      context.subscriptions.push(
        window.onDidChangeActiveTextEditor(_ => update_caret()),
        window.onDidChangeTextEditorSelection(_ => update_caret()))
      update_caret()

      language_client.onNotification(protocol.caret_update_type, goto_file)
    })


    /* dynamic output */

    const dynamic_output = window.createOutputChannel("Isabelle Output")
    context.subscriptions.push(dynamic_output)
    dynamic_output.show(true)
    dynamic_output.hide()

    language_client.onReady().then(() =>
    {
      language_client.onNotification(protocol.dynamic_output_type,
        params => { dynamic_output.clear(); dynamic_output.appendLine(params.content) })
    })


    /* state panel */

    context.subscriptions.push(
      commands.registerCommand("isabelle.state", uri => state_panel.init(uri)),
      commands.registerCommand("_isabelle.state-locate", state_panel.locate),
      commands.registerCommand("_isabelle.state-update", state_panel.update),
      commands.registerCommand("_isabelle.state-auto-update", state_panel.auto_update),
      workspace.onDidCloseTextDocument(document => state_panel.exit_uri(document.uri)))

    language_client.onReady().then(() => state_panel.setup(context, language_client))


    /* preview panel */

    context.subscriptions.push(
      commands.registerCommand("isabelle.preview", uri => preview_panel.request(uri, false)),
      commands.registerCommand("isabelle.preview-split", uri => preview_panel.request(uri, true)),
      commands.registerCommand("isabelle.preview-source", preview_panel.source),
      commands.registerCommand("isabelle.preview-update", preview_panel.update))

    language_client.onReady().then(() => preview_panel.setup(context, language_client))


    /* Isabelle symbols */

    language_client.onReady().then(() =>
    {
      language_client.onNotification(protocol.symbols_type,
        params => symbol.setup(context, params.entries))
      language_client.sendNotification(protocol.symbols_request_type)
    })


    /* completion */

    const completion_provider = new completion.Completion_Provider
    for (const mode of ["isabelle", "isabelle-ml"]) {
      context.subscriptions.push(
        languages.registerCompletionItemProvider(mode, completion_provider))
    }


    /* spell checker */

    language_client.onReady().then(() =>
    {
      context.subscriptions.push(
        commands.registerCommand("isabelle.include-word", uri =>
          language_client.sendNotification(protocol.include_word_type)),
        commands.registerCommand("isabelle.include-word-permanently", uri =>
          language_client.sendNotification(protocol.include_word_permanently_type)),
        commands.registerCommand("isabelle.exclude-word", uri =>
          language_client.sendNotification(protocol.exclude_word_type)),
        commands.registerCommand("isabelle.exclude-word-permanently", uri =>
          language_client.sendNotification(protocol.exclude_word_permanently_type)),
        commands.registerCommand("isabelle.reset-words", uri =>
          language_client.sendNotification(protocol.reset_words_type)))
    })


    /* start server */

    context.subscriptions.push(language_client.start())
  }
}
Example #23
0
export function activate(context: ExtensionContext) {
  extensionContext = context
  outputChannel = vscode.window.createOutputChannel("Dotty");

  const sbtArtifact = "org.scala-sbt:sbt-launch:1.2.3"
  const buildSbtFile = `${vscode.workspace.rootPath}/build.sbt`
  const dottyPluginSbtFile = path.join(extensionContext.extensionPath, './out/dotty-plugin.sbt')
  const disableDottyIDEFile = `${vscode.workspace.rootPath}/.dotty-ide-disabled`
  const languageServerArtifactFile = `${vscode.workspace.rootPath}/.dotty-ide-artifact`
  const languageServerDefaultConfigFile = path.join(extensionContext.extensionPath, './out/default-dotty-ide-config')
  const coursierPath = path.join(extensionContext.extensionPath, './out/coursier');

  vscode.workspace.onWillSaveTextDocument(worksheet.prepareWorksheet)
  vscode.workspace.onDidSaveTextDocument(document => {
    if (worksheet.isWorksheet(document)) {
      worksheet.evaluateWorksheet(document)
    }
  })
  vscode.workspace.onDidCloseTextDocument(document => {
    if (worksheet.isWorksheet(document)) {
      worksheet.removeWorksheet(document)
    }
  })

  if (process.env['DLS_DEV_MODE']) {
    const portFile = `${vscode.workspace.rootPath}/.dotty-ide-dev-port`
    fs.readFile(portFile, (err, port) => {
      if (err) {
        outputChannel.appendLine(`Unable to parse ${portFile}`)
        throw err
      }

      run({
        module: context.asAbsolutePath('out/src/passthrough-server.js'),
        args: [ port.toString() ]
      }, false)
    })

  } else {
    // Check whether `.dotty-ide-artifact` exists. If it does, start the language server,
    // otherwise, try propose to start it if there's no build.sbt
    if (fs.existsSync(languageServerArtifactFile)) {
      runLanguageServer(coursierPath, languageServerArtifactFile)
    } else if (!fs.existsSync(disableDottyIDEFile) && !fs.existsSync(buildSbtFile)) {
      vscode.window.showInformationMessage(
          "This looks like an unconfigured Scala project. Would you like to start the Dotty IDE?",
          "Yes", "No"
      ).then(choice => {
        if (choice == "Yes") {
          fs.readFile(languageServerDefaultConfigFile, (err, data) => {
            if (err) throw err
            else {
              const languageServerScalaVersion = data.toString().trim()
              fetchAndConfigure(coursierPath, sbtArtifact, languageServerScalaVersion, dottyPluginSbtFile).then(() => {
                runLanguageServer(coursierPath, languageServerArtifactFile)
              })
            }
          })
        } else {
          fs.appendFile(disableDottyIDEFile, "", _ => {})
        }
      })
    }
  }
}
Example #24
0
export async function activate(context: vscode.ExtensionContext) {
  logger.debug('Extension: activating vscodevim.');

  extensionContext = context;
  let compositionState = new CompositionState();

  extensionContext.subscriptions.push(StatusBar);

  logger.debug('Extension: registering event handlers.');

  // workspace events
  vscode.workspace.onDidChangeConfiguration(() => {
    logger.debug('onDidChangeConfiguration: reloading configuration');
    configuration.reload();
  });

  vscode.workspace.onDidChangeTextDocument(event => {
    if (configuration.disableExt) {
      return;
    }

    // Change from vscode editor should set document.isDirty to true but they initially don't!
    // There is a timing issue in vscode codebase between when the isDirty flag is set and
    // when registered callbacks are fired. https://github.com/Microsoft/vscode/issues/11339
    let contentChangeHandler = (modeHandler: ModeHandler) => {
      if (modeHandler.vimState.currentMode === ModeName.Insert) {
        if (modeHandler.vimState.historyTracker.currentContentChanges === undefined) {
          modeHandler.vimState.historyTracker.currentContentChanges = [];
        }

        modeHandler.vimState.historyTracker.currentContentChanges = modeHandler.vimState.historyTracker.currentContentChanges.concat(
          event.contentChanges
        );
      }
    };

    if (Globals.isTesting) {
      contentChangeHandler(Globals.mockModeHandler as ModeHandler);
    } else {
      _.filter(
        ModeHandlerMap.getAll(),
        modeHandler => modeHandler.vimState.identity.fileName === event.document.fileName
      ).forEach(modeHandler => {
        contentChangeHandler(modeHandler);
      });
    }
    setTimeout(() => {
      if (!event.document.isDirty && !event.document.isUntitled && event.contentChanges.length) {
        handleContentChangedFromDisk(event.document);
      }
    }, 0);
  });

  vscode.workspace.onDidCloseTextDocument(async () => {
    const documents = vscode.workspace.textDocuments;

    // Delete modehandler once all tabs of this document have been closed
    for (let editorIdentity of ModeHandlerMap.getKeys()) {
      let modeHandler = await ModeHandlerMap.get(editorIdentity);

      if (
        modeHandler == null ||
        modeHandler.vimState.editor === undefined ||
        documents.indexOf(modeHandler.vimState.editor.document) === -1
      ) {
        ModeHandlerMap.delete(editorIdentity);
      }
    }
  });

  // window events
  vscode.window.onDidChangeActiveTextEditor(handleActiveEditorChange, this);

  // override vscode commands
  overrideCommand(context, 'type', async args => {
    taskQueue.enqueueTask(async () => {
      const mh = await getAndUpdateModeHandler();

      if (compositionState.isInComposition) {
        compositionState.composingText += args.text;
      } else {
        await mh.handleKeyEvent(args.text);
      }
    });
  });

  overrideCommand(context, 'replacePreviousChar', async args => {
    taskQueue.enqueueTask(async () => {
      const mh = await getAndUpdateModeHandler();

      if (compositionState.isInComposition) {
        compositionState.composingText =
          compositionState.composingText.substr(
            0,
            compositionState.composingText.length - args.replaceCharCnt
          ) + args.text;
      } else {
        await vscode.commands.executeCommand('default:replacePreviousChar', {
          text: args.text,
          replaceCharCnt: args.replaceCharCnt,
        });
        mh.vimState.cursorPosition = Position.FromVSCodePosition(
          mh.vimState.editor.selection.start
        );
        mh.vimState.cursorStartPosition = Position.FromVSCodePosition(
          mh.vimState.editor.selection.start
        );
      }
    });
  });

  overrideCommand(context, 'compositionStart', async args => {
    taskQueue.enqueueTask(async () => {
      compositionState.isInComposition = true;
    });
  });

  overrideCommand(context, 'compositionEnd', async args => {
    taskQueue.enqueueTask(async () => {
      const mh = await getAndUpdateModeHandler();
      let text = compositionState.composingText;
      compositionState.reset();
      await mh.handleMultipleKeyEvents(text.split(''));
    });
  });

  // register extension commands
  registerCommand(context, 'extension.showCmdLine', async () => {
    let [modeHandler] = await ModeHandlerMap.getOrCreate(
      new EditorIdentity(vscode.window.activeTextEditor).toString()
    );
    commandLine.PromptAndRun('', modeHandler.vimState);
    modeHandler.updateView(modeHandler.vimState);
  });

  registerCommand(context, 'vim.remap', async (args: ICodeKeybinding) => {
    taskQueue.enqueueTask(async () => {
      const mh = await getAndUpdateModeHandler();
      if (args.after) {
        for (const key of args.after) {
          await mh.handleKeyEvent(Notation.NormalizeKey(key, configuration.leader));
        }
        return;
      }

      if (args.commands) {
        for (const command of args.commands) {
          // Check if this is a vim command by looking for :
          if (command.command.slice(0, 1) === ':') {
            await commandLine.Run(command.command.slice(1, command.command.length), mh.vimState);
            await mh.updateView(mh.vimState);
          } else {
            await vscode.commands.executeCommand(command.command, command.args);
          }
        }
      }
    });
  });

  registerCommand(context, 'toggleVim', async () => {
    configuration.disableExt = !configuration.disableExt;
    toggleExtension(configuration.disableExt, compositionState);
  });

  for (const boundKey of configuration.boundKeyCombinations) {
    registerCommand(context, boundKey.command, () => handleKeyEvent(`${boundKey.key}`));
  }

  // Initialize mode handler for current active Text Editor at startup.
  if (vscode.window.activeTextEditor) {
    let mh = await getAndUpdateModeHandler();
    mh.updateView(mh.vimState, { drawSelection: false, revealRange: false });
  }

  // This is called last because getAndUpdateModeHandler() will change cursor
  toggleExtension(configuration.disableExt, compositionState);
}
export function initializeEmbeddedContentDocuments(parentDocumentSelector: string[], embeddedLanguages: { [languageId: string]: boolean }, client: LanguageClient): EmbeddedDocuments {
	let toDispose: Disposable[] = [];

	let embeddedContentChanged = new EventEmitter<Uri>();

	// remember all open virtual documents with the version of the content
	let openVirtualDocuments: { [uri: string]: number } = {};

	// documents are closed after a time out or when collected.
	toDispose.push(workspace.onDidCloseTextDocument(d => {
		if (isEmbeddedContentUri(d.uri)) {
			delete openVirtualDocuments[d.uri.toString()];
		}
	}));

	// virtual document provider
	toDispose.push(workspace.registerTextDocumentContentProvider(EMBEDDED_CONTENT_SCHEME, {
		provideTextDocumentContent: uri => {
			if (isEmbeddedContentUri(uri)) {
				let contentRequestParms = { uri: getHostDocumentUri(uri), embeddedLanguageId: getEmbeddedLanguageId(uri) };
				return client.sendRequest(EmbeddedContentRequest.type, contentRequestParms).then(content => {
					if (content) {
						openVirtualDocuments[uri.toString()] = content.version;
						return content.content;
					} else {
						delete openVirtualDocuments[uri.toString()];
						return '';
					}
				});
			}
			return '';
		},
		onDidChange: embeddedContentChanged.event
	}));

	// diagnostics for embedded contents
	client.onNotification(EmbeddedContentChangedNotification.type, p => {
		for (let languageId in embeddedLanguages) {
			if (p.embeddedLanguageIds.indexOf(languageId) !== -1) {
				// open the document so that validation is triggered in the embedded mode
				let virtualUri = getEmbeddedContentUri(p.uri, languageId);
				openEmbeddedContentDocument(virtualUri, p.version);
			}
		}
	});

	function ensureContentUpdated(virtualURI: Uri, expectedVersion: number) {
		let virtualURIString = virtualURI.toString();
		let virtualDocVersion = openVirtualDocuments[virtualURIString];
		if (isDefined(virtualDocVersion) && virtualDocVersion !== expectedVersion) {
			return new Promise<void>((resolve, reject) => {
				let subscription = workspace.onDidChangeTextDocument(d => {
					if (d.document.uri.toString() === virtualURIString) {
						subscription.dispose();
						resolve();
					}
				});
				embeddedContentChanged.fire(virtualURI);
			});
		}
		return Promise.resolve();
	};

	function openEmbeddedContentDocument(virtualURI: Uri, expectedVersion: number): Thenable<TextDocument> {
		return ensureContentUpdated(virtualURI, expectedVersion).then(_ => {
			return workspace.openTextDocument(virtualURI).then(document => {
				if (expectedVersion === openVirtualDocuments[virtualURI.toString()]) {
					return document;
				}
				return void 0;
			});
		});
	};

	return {
		getEmbeddedContentUri,
		openEmbeddedContentDocument,
		dispose: Disposable.from(...toDispose).dispose
	};

}
Example #26
0
	client.onReady().then(() => {
		disposable = client.onTelemetry(e => {
			if (telemetryReporter) {
				telemetryReporter.sendTelemetryEvent(e.key, e.data);
			}
		});

		// handle content request
		client.onRequest(VSCodeContentRequest.type, (uriPath: string) => {
			let uri = Uri.parse(uriPath);
			return workspace.openTextDocument(uri).then(doc => {
				return doc.getText();
			}, error => {
				return Promise.reject(error);
			});
		});

		let handleContentChange = (uri: Uri) => {
			if (uri.scheme === 'vscode' && uri.authority === 'schemas') {
				client.sendNotification(SchemaContentChangeNotification.type, uri.toString());
			}
		};

		let handleActiveEditorChange = (activeEditor?: TextEditor) => {
			if (!activeEditor) {
				return;
			}

			const activeDocUri = activeEditor.document.uri.toString();

			if (activeDocUri && fileSchemaErrors.has(activeDocUri)) {
				schemaResolutionErrorStatusBarItem.show();
			} else {
				schemaResolutionErrorStatusBarItem.hide();
			}
		};

		toDispose.push(workspace.onDidChangeTextDocument(e => handleContentChange(e.document.uri)));
		toDispose.push(workspace.onDidCloseTextDocument(d => {
			handleContentChange(d.uri);
			fileSchemaErrors.delete(d.uri.toString());
		}));
		toDispose.push(window.onDidChangeActiveTextEditor(handleActiveEditorChange));

		let handleRetryResolveSchemaCommand = () => {
			if (window.activeTextEditor) {
				schemaResolutionErrorStatusBarItem.text = '$(watch)';
				const activeDocUri = window.activeTextEditor.document.uri.toString();
				client.sendRequest(ForceValidateRequest.type, activeDocUri).then((diagnostics) => {
					const schemaErrorIndex = diagnostics.findIndex(candidate => candidate.code === /* SchemaResolveError */ 0x300);
					if (schemaErrorIndex !== -1) {
						// Show schema resolution errors in status bar only; ref: #51032
						const schemaResolveDiagnostic = diagnostics[schemaErrorIndex];
						fileSchemaErrors.set(activeDocUri, schemaResolveDiagnostic.message);
					} else {
						schemaResolutionErrorStatusBarItem.hide();
					}
					schemaResolutionErrorStatusBarItem.text = '$(alert)';
				});
			}
		};

		toDispose.push(commands.registerCommand('_json.retryResolveSchema', handleRetryResolveSchemaCommand));

		client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));
	});
export function initStatusBar(context: ExtensionContext, client: CSpellClient) {

    const sbCheck = window.createStatusBarItem(vscode.StatusBarAlignment.Left);

    let lastUri = '';

    function updateStatusBarWithSpellCheckStatus(document?: vscode.TextDocument) {
        sbCheck.text = '$(clock)';
        sbCheck.tooltip = 'cSpell waiting...';
        sbCheck.show();
        if (!document) return;

        const { uri, languageId = '' } = document;
        lastUri = uri.toString();
        const genOnOffIcon = (on: boolean) => on ? '$(checklist)' : '$(stop)';
        client.isSpellCheckEnabled(document)
            .then((response) => {
                const { activeTextEditor } = window;
                const document = activeTextEditor && activeTextEditor.document;
                const docUri = document && document.uri;
                if (docUri === uri || !docUri || docUri.scheme !== 'file') {
                    const { languageEnabled = true, fileEnabled = true } = response;
                    const isChecked = languageEnabled && fileEnabled;
                    const isCheckedText = isChecked ? 'is' : 'is NOT';
                    const langReason = languageEnabled ? '' : `The "${languageId}" language is not enabled.`;
                    const fileReason = fileEnabled ? '' : `The file path is excluded in settings.`;
                    const fileName = path.basename(uri.fsPath);
                    const langText = `${genOnOffIcon(languageEnabled)} ${languageId}`;
                    const fileText = `${genOnOffIcon(fileEnabled)} ${fileName}`;
                    const reason = [`"${fileName}" ${isCheckedText} spell checked.`, langReason, fileReason].filter(a => !!a).join(' ');
                    sbCheck.text = `${langText} | ${fileText}`;
                    sbCheck.tooltip = reason;
                    sbCheck.command = infoViewer.commandDisplayCSpellInfo;
                    sbCheck.show();
                }
            });
    }

    function updateStatusBar(doc?: vscode.TextDocument) {
        const document = isSupportedDoc(doc) ? doc : selectDocument();
        const settings: CSpellUserSettings = workspace.getConfiguration().get('cSpell') as CSpellUserSettings;
        const { enabled, showStatus = true } = settings;

        if (!showStatus) {
            sbCheck.hide();
            return;
        }

        if (enabled) {
            updateStatusBarWithSpellCheckStatus(document);
        } else {
            sbCheck.text = '$(stop) cSpell';
            sbCheck.tooltip = 'Enable spell checking';
            sbCheck.command = 'cSpell.enableForWorkspace';
            sbCheck.show();
        }
    }

    function onDidChangeActiveTextEditor(e: TextEditor) {
        updateStatusBar(e && e.document);
    }

    function onDidChangeConfiguration() {
        updateStatusBar();
    }

    function isViableEditor(e?: TextEditor) {
        if (!e) return false;
        const document = e.document;

        return document &&
            document.uri &&
            isSupportedUri(document.uri);
    }

    function selectDocument() {
        if (isViableEditor(window.activeTextEditor)) {
            return window.activeTextEditor!.document;
        }

        const docs = workspace.textDocuments
            .filter(isSupportedDoc);

        if (lastUri) {
            const candidate = docs
                .filter(document => document.uri.toString() === lastUri)
                .shift();
            if (candidate) return candidate;
        }

        return docs.shift();
    }

    sbCheck.text = '$(clock)';
    sbCheck.show();

    context.subscriptions.push(
        window.onDidChangeActiveTextEditor(onDidChangeActiveTextEditor),
        workspace.onDidChangeConfiguration(onDidChangeConfiguration),
        workspace.onDidCloseTextDocument(onDidChangeConfiguration),
        sbCheck
    );

    if (window.activeTextEditor) {
        onDidChangeActiveTextEditor(window.activeTextEditor);
    }

}
Example #28
0
	client.onReady().then(() => {
		disposable = client.onTelemetry(e => {
			if (telemetryReporter) {
				telemetryReporter.sendTelemetryEvent(e.key, e.data);
			}
		});

		// handle content request
		client.onRequest(VSCodeContentRequest.type, (uriPath: string) => {
			let uri = Uri.parse(uriPath);
			if (uri.scheme !== 'http' && uri.scheme !== 'https') {
				return workspace.openTextDocument(uri).then(doc => {
					return doc.getText();
				}, error => {
					return Promise.reject(error);
				});
			} else {
				const headers = { 'Accept-Encoding': 'gzip, deflate' };
				return xhr({ url: uriPath, followRedirects: 5, headers }).then(response => {
					return response.responseText;
				}, (error: XHRResponse) => {
					return Promise.reject(error.responseText || getErrorStatusDescription(error.status) || error.toString());
				});
			}
		});

		let handleContentChange = (uri: Uri) => {
			if (uri.scheme === 'vscode' && uri.authority === 'schemas') {
				client.sendNotification(SchemaContentChangeNotification.type, uri.toString());
			}
		};

		let handleActiveEditorChange = (activeEditor?: TextEditor) => {
			if (!activeEditor) {
				return;
			}

			const activeDocUri = activeEditor.document.uri.toString();

			if (activeDocUri && fileSchemaErrors.has(activeDocUri)) {
				schemaResolutionErrorStatusBarItem.show();
			} else {
				schemaResolutionErrorStatusBarItem.hide();
			}
		};

		toDispose.push(workspace.onDidChangeTextDocument(e => handleContentChange(e.document.uri)));
		toDispose.push(workspace.onDidCloseTextDocument(d => {
			handleContentChange(d.uri);
			fileSchemaErrors.delete(d.uri.toString());
		}));
		toDispose.push(window.onDidChangeActiveTextEditor(handleActiveEditorChange));

		let handleRetryResolveSchemaCommand = () => {
			if (window.activeTextEditor) {
				schemaResolutionErrorStatusBarItem.text = '$(watch)';
				const activeDocUri = window.activeTextEditor.document.uri.toString();
				client.sendRequest(ForceValidateRequest.type, activeDocUri).then((diagnostics) => {
					const schemaErrorIndex = diagnostics.findIndex(candidate => candidate.code === /* SchemaResolveError */ 0x300);
					if (schemaErrorIndex !== -1) {
						// Show schema resolution errors in status bar only; ref: #51032
						const schemaResolveDiagnostic = diagnostics[schemaErrorIndex];
						fileSchemaErrors.set(activeDocUri, schemaResolveDiagnostic.message);
					} else {
						schemaResolutionErrorStatusBarItem.hide();
					}
					schemaResolutionErrorStatusBarItem.text = '$(alert)';
				});
			}
		};

		toDispose.push(commands.registerCommand('_json.retryResolveSchema', handleRetryResolveSchemaCommand));

		client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));

		extensions.onDidChange(_ => {
			client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));
		});

		documentSelector.forEach(selector => {
			toDispose.push(languages.registerSelectionRangeProvider(selector, {
				async provideSelectionRanges(document: TextDocument, positions: Position[]): Promise<SelectionRange[]> {
					const textDocument = client.code2ProtocolConverter.asTextDocumentIdentifier(document);
					const rawResult = await client.sendRequest<SelectionRange[][]>('$/textDocument/selectionRanges', { textDocument, positions: positions.map(client.code2ProtocolConverter.asPosition) });
					if (Array.isArray(rawResult)) {
						return rawResult.map(rawSelectionRanges => {
							return rawSelectionRanges.reduceRight((parent: SelectionRange | undefined, selectionRange: SelectionRange) => {
								return {
									range: client.protocol2CodeConverter.asRange(selectionRange.range),
									parent,
								};
							}, undefined)!;
						});
					}
					return [];
				}
			}));
		});
	});
Example #29
0
export function activate(context: vs.ExtensionContext) {
	let extensionStartTime = new Date();
	sdks = util.findSdks();
	if (sdks.dart == null) {
		if (util.isFlutterProject) {
			vs.window.showErrorMessage("Could not find a Flutter SDK to use. " +
				"Please add it to your PATH or set FLUTTER_HOME and reload.",
				"Go to Flutter Downloads"
			).then(selectedItem => {
				if (selectedItem)
					util.openInBrowser(FLUTTER_DOWNLOAD_URL);
			});
		}
		else {
			vs.window.showErrorMessage("Could not find a Dart SDK to use. " +
				"Please add it to your PATH or configure the 'dart.sdkPath' setting and reload.",
				"Go to Dart Downloads"
			).then(selectedItem => {
				if (selectedItem)
					util.openInBrowser(DART_DOWNLOAD_URL);
			});
		}
		analytics.logSdkDetectionFailure();
		return; // Don't set anything else up; we can't work like this!
	}

	// Show the SDK version in the status bar.
	let sdkVersion = util.getDartSdkVersion(sdks.dart);
	if (sdkVersion) {
		let versionStatusItem = vs.window.createStatusBarItem(vs.StatusBarAlignment.Right, Number.MIN_VALUE);
		versionStatusItem.text = sdkVersion;
		versionStatusItem.tooltip = "Dart SDK Version";
		versionStatusItem.show();
		context.subscriptions.push(versionStatusItem);

		if (config.checkForSdkUpdates && !util.isFlutterProject) {
			util.getLatestSdkVersion().then(version => {
				if (util.isOutOfDate(sdkVersion, version))
					vs.window.showWarningMessage(
						`Version ${version} of the Dart SDK is available (you have ${sdkVersion}). Some features of Dart Code may not work correctly with an old SDK.`,
						"Go to Dart Downloads"
					).then(selectedItem => {
						if (selectedItem)
							util.openInBrowser(DART_DOWNLOAD_URL);
					});
			}, util.logError);
		}
		analytics.sdkVersion = sdkVersion;
	}

	// Fire up the analyzer process.
	let analyzerStartTime = new Date();
	const analyzerPath = config.analyzerPath || path.join(sdks.dart, util.analyzerPath);
	analyzer = new Analyzer(path.join(sdks.dart, util.dartVMPath), analyzerPath);
	context.subscriptions.push(analyzer);

	// Log analysis server startup time when we get the welcome message/version.
	let connectedEvents = analyzer.registerForServerConnected(sc => {
		analytics.analysisServerVersion = sc.version;
		let analyzerEndTime = new Date();
		analytics.logAnalyzerStartupTime(analyzerEndTime.getTime() - analyzerStartTime.getTime());
		connectedEvents.dispose();
	});

	// Log analysis server first analysis completion time when it completes.
	var analysisStartTime: Date;
	let analysisCompleteEvents = analyzer.registerForServerStatus(ss => {
		// Analysis started for the first time.
		if (ss.analysis && ss.analysis.isAnalyzing && !analysisStartTime)
			analysisStartTime = new Date();

		// Analysis ends for the first time.
		if (ss.analysis && !ss.analysis.isAnalyzing && analysisStartTime) {
			let analysisEndTime = new Date();
			analytics.logAnalyzerFirstAnalysisTime(analysisEndTime.getTime() - analysisStartTime.getTime());
			analysisCompleteEvents.dispose();
		}
	});

	// TODO: Check if EventEmitter<T> would be more appropriate than our own.

	// Set up providers.
	context.subscriptions.push(vs.languages.registerHoverProvider(DART_MODE, new DartHoverProvider(analyzer)));
	context.subscriptions.push(vs.languages.registerDocumentFormattingEditProvider(DART_MODE, new DartFormattingEditProvider(analyzer)));
	context.subscriptions.push(vs.languages.registerOnTypeFormattingEditProvider(DART_MODE, new DartTypeFormattingEditProvider(analyzer), "}", ";"));
	context.subscriptions.push(vs.languages.registerCompletionItemProvider(DART_MODE, new DartCompletionItemProvider(analyzer), ".", ":", " ", "=", "("));
	context.subscriptions.push(vs.languages.registerDefinitionProvider(DART_MODE, new DartDefinitionProvider(analyzer)));
	context.subscriptions.push(vs.languages.registerDocumentSymbolProvider(DART_MODE, new DartDocumentSymbolProvider(analyzer)));
	context.subscriptions.push(vs.languages.registerReferenceProvider(DART_MODE, new DartReferenceProvider(analyzer)));
	context.subscriptions.push(vs.languages.registerWorkspaceSymbolProvider(new DartWorkspaceSymbolProvider(analyzer)));
	context.subscriptions.push(vs.languages.registerDocumentHighlightProvider(DART_MODE, new DartDocumentHighlightProvider(analyzer)));
	context.subscriptions.push(vs.languages.registerCodeActionsProvider(DART_MODE, new DartCodeActionProvider(analyzer)));
	context.subscriptions.push(vs.languages.registerRenameProvider(DART_MODE, new DartRenameProvider(analyzer)));
	context.subscriptions.push(vs.languages.setLanguageConfiguration(DART_MODE.language, new DartLanguageConfiguration()));
	context.subscriptions.push(new AnalyzerStatusReporter(analyzer));

	// Set up diagnostics.
	let diagnostics = vs.languages.createDiagnosticCollection("dart");
	context.subscriptions.push(diagnostics);
	let diagnosticsProvider = new DartDiagnosticProvider(analyzer, diagnostics);

	// Set the root...
	if (vs.workspace.rootPath) {
		let packageRoots = findPackageRoots(vs.workspace.rootPath);
		analyzer.analysisSetAnalysisRoots({
			included: packageRoots,
			excluded: []
		});
	}

	// Hook editor changes to send updated contents to analyzer.
	let fileChangeHandler = new FileChangeHandler(analyzer);
	context.subscriptions.push(vs.workspace.onDidOpenTextDocument(td => fileChangeHandler.onDidOpenTextDocument(td)));
	context.subscriptions.push(vs.workspace.onDidChangeTextDocument(e => fileChangeHandler.onDidChangeTextDocument(e)));
	context.subscriptions.push(vs.workspace.onDidCloseTextDocument(td => fileChangeHandler.onDidCloseTextDocument(td)));
	vs.workspace.textDocuments.forEach(td => fileChangeHandler.onDidOpenTextDocument(td)); // Handle already-open files.

	// Hook open/active file changes so we can set priority files with the analyzer.
	let openFileTracker = new OpenFileTracker(analyzer);
	context.subscriptions.push(vs.workspace.onDidOpenTextDocument(td => openFileTracker.updatePriorityFiles()));
	context.subscriptions.push(vs.workspace.onDidCloseTextDocument(td => openFileTracker.updatePriorityFiles()));
	context.subscriptions.push(vs.window.onDidChangeActiveTextEditor(e => openFileTracker.updatePriorityFiles()));
	openFileTracker.updatePriorityFiles(); // Handle already-open files.

	// Handle config changes so we can reanalyze if necessary.
	context.subscriptions.push(vs.workspace.onDidChangeConfiguration(handleConfigurationChange));
	context.subscriptions.push(vs.workspace.onDidSaveTextDocument(td => {
		if (path.basename(td.fileName).toLowerCase() == "pubspec.yaml")
			handleConfigurationChange();
	}));

	// Register SDK commands.
	let sdkCommands = new SdkCommands(sdks);
	sdkCommands.registerCommands(context);

	// Set up commands for Dart editors.
	context.subscriptions.push(new EditCommands(context, analyzer));

	// Register misc commands.
	context.subscriptions.push(new TypeHierarchyCommand(context, analyzer));

	// Perform any required project upgrades.
	upgradeProject();

	// Prompt user for any special config we might want to set.
	promptUserForConfigs(context);

	// Turn on all the commands.	
	setCommandVisiblity(true);

	// Log how long all this startup took.
	let extensionEndTime = new Date();
	analytics.logExtensionStartup(extensionEndTime.getTime() - extensionStartTime.getTime());
}
Example #30
0
export async function activate(context: vscode.ExtensionContext) {
  logger.debug('Extension: activating vscodevim.');

  extensionContext = context;
  extensionContext.subscriptions.push(StatusBar);

  logger.debug('Extension: registering event handlers.');

  // workspace events
  vscode.workspace.onDidChangeConfiguration(() => {
    logger.debug('onDidChangeConfiguration: reloading configuration');
    configuration.reload();
  });

  const textWasDeleted = event =>
    event.contentChanges.length === 1 &&
    event.contentChanges[0].text === '' &&
    event.contentChanges[0].range.start.line !== event.contentChanges[0].range.end.line;

  const textWasAdded = event =>
    event.contentChanges.length === 1 &&
    (event.contentChanges[0].text === '\n' || event.contentChanges[0].text === '\r\n') &&
    event.contentChanges[0].range.start.line === event.contentChanges[0].range.end.line;

  vscode.workspace.onDidChangeTextDocument(async event => {
    if (configuration.disableExt) {
      return;
    }

    if (textWasDeleted(event)) {
      globalState.jumpTracker.handleTextDeleted(event.document, event.contentChanges[0].range);
    } else if (textWasAdded(event)) {
      globalState.jumpTracker.handleTextAdded(
        event.document,
        event.contentChanges[0].range,
        event.contentChanges[0].text
      );
    }

    // Change from vscode editor should set document.isDirty to true but they initially don't!
    // There is a timing issue in vscode codebase between when the isDirty flag is set and
    // when registered callbacks are fired. https://github.com/Microsoft/vscode/issues/11339
    let contentChangeHandler = (modeHandler: ModeHandler) => {
      if (!modeHandler) {
        // This can happen in tests if you don't set Globals.mockModeHandler;
        console.warn('No mode handler found');
        return;
      }

      if (modeHandler.vimState.currentMode === ModeName.Insert) {
        if (modeHandler.vimState.historyTracker.currentContentChanges === undefined) {
          modeHandler.vimState.historyTracker.currentContentChanges = [];
        }

        modeHandler.vimState.historyTracker.currentContentChanges = modeHandler.vimState.historyTracker.currentContentChanges.concat(
          event.contentChanges
        );
      }
    };

    if (Globals.isTesting) {
      contentChangeHandler(Globals.mockModeHandler as ModeHandler);
    } else {
      _.filter(
        ModeHandlerMap.getAll(),
        modeHandler => modeHandler.vimState.identity.fileName === event.document.fileName
      ).forEach(modeHandler => {
        contentChangeHandler(modeHandler);
      });
    }
    setTimeout(() => {
      if (!event.document.isDirty && !event.document.isUntitled && event.contentChanges.length) {
        handleContentChangedFromDisk(event.document);
      }
    }, 0);
  });

  vscode.workspace.onDidCloseTextDocument(async () => {
    const documents = vscode.workspace.textDocuments;

    // Delete modehandler once all tabs of this document have been closed
    for (let editorIdentity of ModeHandlerMap.getKeys()) {
      let modeHandler = await ModeHandlerMap.get(editorIdentity);

      if (
        modeHandler == null ||
        modeHandler.vimState.editor === undefined ||
        documents.indexOf(modeHandler.vimState.editor.document) === -1
      ) {
        ModeHandlerMap.delete(editorIdentity);
      }
    }
  });

  // window events
  vscode.window.onDidChangeActiveTextEditor(async () => {
    if (configuration.disableExt) {
      return;
    }

    if (Globals.isTesting) {
      return;
    }

    const mhPrevious: ModeHandler | null = previousActiveEditorId
      ? ModeHandlerMap.get(previousActiveEditorId.toString())
      : null;
    // Track the closed editor so we can use it the next time an open event occurs.
    // When vscode changes away from a temporary file, onDidChangeActiveTextEditor first twice.
    // First it fires when leaving the closed editor. Then onDidCloseTextDocument first, and we delete
    // the old ModeHandler. Then a new editor opens.
    //
    // This also applies to files that are merely closed, which allows you to jump back to that file similarly
    // once a new file is opened.
    lastClosedModeHandler = mhPrevious || lastClosedModeHandler;

    if (vscode.window.activeTextEditor === undefined) {
      return;
    }

    taskQueue.enqueueTask(async () => {
      if (vscode.window.activeTextEditor !== undefined) {
        const mh: ModeHandler = await getAndUpdateModeHandler(true);

        await mh.updateVimModeForKeybindings(mh.vimState.currentMode);

        await mh.updateView(mh.vimState, { drawSelection: false, revealRange: false });

        globalState.jumpTracker.handleFileJump(
          lastClosedModeHandler ? Jump.fromStateNow(lastClosedModeHandler.vimState) : null,
          Jump.fromStateNow(mh.vimState)
        );
      }
    });
  });

  let compositionState = new CompositionState();

  // override vscode commands
  overrideCommand(context, 'type', async args => {
    taskQueue.enqueueTask(async () => {
      const mh = await getAndUpdateModeHandler();

      if (compositionState.isInComposition) {
        compositionState.composingText += args.text;
      } else {
        await mh.handleKeyEvent(args.text);
      }
    });
  });

  overrideCommand(context, 'replacePreviousChar', async args => {
    taskQueue.enqueueTask(async () => {
      const mh = await getAndUpdateModeHandler();

      if (compositionState.isInComposition) {
        compositionState.composingText =
          compositionState.composingText.substr(
            0,
            compositionState.composingText.length - args.replaceCharCnt
          ) + args.text;
      } else {
        await vscode.commands.executeCommand('default:replacePreviousChar', {
          text: args.text,
          replaceCharCnt: args.replaceCharCnt,
        });
        mh.vimState.cursorPosition = Position.FromVSCodePosition(
          mh.vimState.editor.selection.start
        );
        mh.vimState.cursorStartPosition = Position.FromVSCodePosition(
          mh.vimState.editor.selection.start
        );
      }
    });
  });

  overrideCommand(context, 'compositionStart', async () => {
    taskQueue.enqueueTask(async () => {
      const mh = await getAndUpdateModeHandler();
      if (mh.vimState.currentMode !== ModeName.Insert) {
        compositionState.isInComposition = true;
      }
    });
  });

  overrideCommand(context, 'compositionEnd', async () => {
    taskQueue.enqueueTask(async () => {
      const mh = await getAndUpdateModeHandler();
      if (mh.vimState.currentMode !== ModeName.Insert) {
        let text = compositionState.composingText;
        compositionState.reset();
        await mh.handleMultipleKeyEvents(text.split(''));
      }
    });
  });

  // register extension commands
  registerCommand(context, 'vim.showQuickpickCmdLine', async () => {
    const modeHandler = await getAndUpdateModeHandler();
    await commandLine.PromptAndRun('', modeHandler.vimState);
    modeHandler.updateView(modeHandler.vimState);
  });

  registerCommand(context, 'vim.remap', async (args: ICodeKeybinding) => {
    taskQueue.enqueueTask(async () => {
      const mh = await getAndUpdateModeHandler();
      if (args.after) {
        for (const key of args.after) {
          await mh.handleKeyEvent(Notation.NormalizeKey(key, configuration.leader));
        }
        return;
      }

      if (args.commands) {
        for (const command of args.commands) {
          // Check if this is a vim command by looking for :
          if (command.command.slice(0, 1) === ':') {
            await commandLine.Run(command.command.slice(1, command.command.length), mh.vimState);
            await mh.updateView(mh.vimState);
          } else {
            await vscode.commands.executeCommand(command.command, command.args);
          }
        }
      }
    });
  });

  registerCommand(context, 'toggleVim', async () => {
    configuration.disableExt = !configuration.disableExt;
    toggleExtension(configuration.disableExt, compositionState);
  });

  for (const boundKey of configuration.boundKeyCombinations) {
    registerCommand(context, boundKey.command, () => handleKeyEvent(`${boundKey.key}`));
  }

  // Initialize mode handler for current active Text Editor at startup.
  if (vscode.window.activeTextEditor) {
    let mh = await getAndUpdateModeHandler();
    mh.updateView(mh.vimState, { drawSelection: false, revealRange: false });
  }

  await commandLine.load();
  // Initialize the search history
  await globalState.loadSearchHistory();

  // This is called last because getAndUpdateModeHandler() will change cursor
  toggleExtension(configuration.disableExt, compositionState);
}