Example #1
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 #2
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);
};
export function activate(context: vscode.ExtensionContext): void {
    'use strict';

    const diag = vscode.languages.createDiagnosticCollection('ruby');
    context.subscriptions.push(diag);
    const rubocop = new Rubocop(diag);
    const rubocopAutocorrect = new RubocopAutocorrect(diag);

    const disposable = vscode.commands.registerCommand('ruby.rubocop', () => {
        const document = vscode.window.activeTextEditor.document;
        rubocop.execute(document);
    });

    vscode.commands.registerCommand('ruby.rubocopAutocorrect', () => {
        const document = vscode.window.activeTextEditor.document;
        rubocopAutocorrect.execute(document);
    });

    context.subscriptions.push(disposable);

    vscode.workspace.onDidSaveTextDocument((e: vscode.TextDocument) => {
        if (rubocop.isOnSave) {
            rubocop.execute(e);
        }
    });
}
Example #4
0
export function setup(disposables, flowPath) {

  lastDiagnostics = vscode.languages.createDiagnosticCollection();

  // Do an initial call to get diagnostics from the active editor if any
  if (vscode.window.activeTextEditor) {
    console.log('INIT');
    fullDiagnostics(flowPath);
  }

  // Update diagnostics: when active text editor changes
  disposables.push(vscode.window.onDidChangeActiveTextEditor(editor => {
    console.log('CHANGE');
    fileDiagnostics(editor && editor.document, flowPath);
  }));

  // Update diagnostics when document is edited
  disposables.push(vscode.workspace.onDidChangeTextDocument(event => {
    console.log('EDIT');
    if (vscode.window.activeTextEditor) {
      fileDiagnostics(vscode.window.activeTextEditor.document, flowPath);
    }
  }));

  // Update diagnostics when document is saved
  disposables.push(vscode.workspace.onDidSaveTextDocument(event => {
    console.log('SAVE');
    if (vscode.window.activeTextEditor) {
      fullDiagnostics(flowPath);
    }
  }));

}
Example #5
0
export function activate(context: vscode.ExtensionContext) {

	console.log("Activating extension Matlab");

	var matlabConfig = workspace.getConfiguration('matlab');

	if (!matlabConfig['lintOnSave']) {
		return;
	}

	if (!matlabConfig.has('mlintpath') || matlabConfig['mlintpath'] == null) {
		window.showErrorMessage("Could not find path to the mlint executable in the configuration file.")
		return;
	}

	var mlintPath = matlabConfig['mlintpath'];

	if (!fs.existsSync(mlintPath)) {
		window.showErrorMessage("The cannot find mlint at the given path, please check your configuration file.")
		return;
	}

	diagnosticCollection = vscode.languages.createDiagnosticCollection("matlab");
	context.subscriptions.push(diagnosticCollection);

	context.subscriptions.push(workspace.onDidSaveTextDocument(document => {lintDocument(document, mlintPath)}));
	context.subscriptions.push(workspace.onDidOpenTextDocument(document => {lintDocument(document, mlintPath)}));
}
Example #6
0
export function activate(context: ExtensionContext) {
  const gist = new GistService(context.globalState);
  const cmd = new Commands({ gist });

  const subscriptions = context.subscriptions;
  const registerCommand = commands.registerCommand;

  // This will need to be removed in a future release
  const deprecatedToken = workspace.getConfiguration('gist').get<string>('oauth_token');
  if (deprecatedToken) {
    gist.setToken(deprecatedToken);
  }

  subscriptions.push(
    registerCommand('extension.openCodeBlock', cmd.openCodeBlock, cmd),
    registerCommand('extension.openFavoriteCodeBlock', cmd.openCodeBlock.bind(cmd, true)),
    registerCommand('extension.createCodeBlock', cmd.createCodeBlock, cmd),
    registerCommand('extension.openCodeBlockInBrowser', cmd.openCodeBlockInBrowser, cmd),
    registerCommand('extension.deleteCodeBlock', cmd.deleteCodeBlock, cmd),
    registerCommand('extension.removeFileFromCodeBlock', cmd.removeFileFromCodeBlock, cmd),
    registerCommand('extension.addToCodeBlock', cmd.addToCodeBlock, cmd),
    registerCommand('extension.changeCodeBlockDescription', cmd.changeCodeBlockDescription, cmd)
  );
  workspace.onDidSaveTextDocument(cmd.onSaveTextDocument, cmd);
}
Example #7
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);
}
Example #8
0
function startLintOnSaveWatcher(mlintPath: string) {

	function mapSeverityToVSCodeSeverity(sev: string) {
		switch (sev) {
			case "error": return vscode.DiagnosticSeverity.Error;
			case "warning": return vscode.DiagnosticSeverity.Warning;
			default: return vscode.DiagnosticSeverity.Error;
		}
	}

	let matlabConfig = vscode.workspace.getConfiguration('matlab');

	return workspace.onDidSaveTextDocument(document => {
		if (document.languageId != "matlab") {
			return;
		}

		check(document.uri.fsPath, matlabConfig['lintOnSave'], mlintPath).then(errors => {
			diagnosticCollection.clear();

			let diagnosticMap: Map<vscode.Uri, vscode.Diagnostic[]> = new Map();;

			errors.forEach(error => {
				let targetUri = vscode.Uri.file(error.file);

				var line = error.line - 1;
				if (line < 0) line = 0;

				var startColumn = error.column[0] - 1;
				if (startColumn < 0) startColumn = 0;

				var endColumn = error.column[1] - 1;
				if (endColumn < 0) endColumn = 0;

				let range = new vscode.Range(line, startColumn, line, endColumn);
				let diagnostic = new vscode.Diagnostic(range, error.msg, mapSeverityToVSCodeSeverity(error.severity));

				let diagnostics = diagnosticMap.get(targetUri);
				if (!diagnostics) {
					diagnostics = [];
				}

				diagnostics.push(diagnostic);
				diagnosticMap.set(targetUri, diagnostics);
			});

			let entries: [vscode.Uri, vscode.Diagnostic[]][] = [];
			diagnosticMap.forEach((diags, uri) => {
				entries.push([uri, diags]);
			});

			diagnosticCollection.set(entries);
		}).catch(err => {
			vscode.window.showErrorMessage(err);
		});
	});
}
Example #9
0
function createRsSaveWatcher() {
    if ( cmConfig.rsWatcherEnabled() ) {
        workspace.onDidSaveTextDocument( (e) => {
            if ( e.fileName.endsWith(".rs") ) {
                compilerAdapter.runIfStarted( `{ cm.rs.loadRs( cm.io.Url("${e.fileName.replace( /\\/g, "/" )}"), force=true ); }` );
            }
        });
    }
}
			return await new Promise(resolve => {
				let saveCount = 0;
				workspace.onDidSaveTextDocument(savedDoc => {
					if (++saveCount === (options.saves || 1)) {
						resolve(savedDoc.getText());
					}
				});
				doc.save();
			});
Example #11
0
export function activate(context: vscode.ExtensionContext) {
    diagnosticCollection = vscode.languages.createDiagnosticCollection('lua');
    context.subscriptions.push(diagnosticCollection);

    vscode.workspace.onDidSaveTextDocument(document => lintDocument(document, true));
    vscode.workspace.onDidChangeTextDocument(event => lintDocument(event.document));
    vscode.workspace.onDidOpenTextDocument(document => lintDocument(document));
    vscode.window.onDidChangeActiveTextEditor((editor: vscode.TextEditor) => lintDocument(editor.document));
}
Example #12
0
export function activate(context: ExtensionContext) {

	// The server is implemented in node
	let serverModule = context.asAbsolutePath(path.join('server', 'server.js'));

	// The debug options for the server
	let debugOptions = { execArgv: ["--nolazy", "--debug=6004"] };

	// If the extension is launch in debug mode the debug server options are use
	// Otherwise the run options are used
	let serverOptions: ServerOptions = {
		run : { module: serverModule },
		debug: { module: serverModule, options: debugOptions }
	};

	// Options to control the language client
	let clientOptions: LanguageClientOptions = {
		// Register the server for php documents
		documentSelector: ['php'],
		synchronize: {
			// Synchronize the setting section 'phpcs' to the server
			configurationSection: 'phpcs',
			// Notify the server about file changes to 'phpcs.xml' files contain in the workspace
			fileEvents: workspace.createFileSystemWatcher('**/phpcs.xml')
		}
	};

	// Create the language client the client.
	let client = new LanguageClient('PHP CodeSniffer Linter', serverOptions, clientOptions);

	// Create the save handler.
	let saveHandler = workspace.onDidSaveTextDocument(document => {
		if (document.languageId != `php`) {
			return;
		}
		let params: proto.TextDocumentIdentifier = { uri: document.uri.toString() };
		client.sendNotification<proto.TextDocumentIdentifier>(proto.DidSaveTextDocumentNotification.type, params);
	});

	let status = new PhpcsStatus();
	client.onNotification( proto.DidStartValidateTextDocumentNotification.type, (document) => {
		status.startProcessing(document.uri);
	});
	client.onNotification( proto.DidEndValidateTextDocumentNotification.type, (document) => {
		status.endProcessing(document.uri);
	});

	context.subscriptions.push(saveHandler);

	// Create the settings monitor and start the monitor for the client.
	let monitor = new SettingMonitor(client, 'phpcs.enable').start();

	// Push the monitor to the context's subscriptions so that the
	// client can be deactivated on extension deactivation
	context.subscriptions.push(monitor);
	context.subscriptions.push(status);
}
  constructor(newLineHandler: NewLineHandler) {
    this._newLineHandler = newLineHandler;

    // subscribe to events
    let subscriptions: Disposable[] = [];
    workspace.onDidSaveTextDocument(this._onEvent, this, subscriptions);

    this._disposable = Disposable.from(...subscriptions);
  }
Example #14
0
export function activate(context: vscode.ExtensionContext): any {
  'use strict';
  // Use the console to output diagnostic information (console.log) and errors (console.error)
  // This line of code will only be executed once when your extension is activated
  try {
    vscode.window.forceCode = new ForceService(context);
    vscode.window.showInformationMessage('ForceCode is now active for user ' + vscode.window.forceCode.username);
  } catch (error) {
    console.error(error);
    vscode.window.showErrorMessage('OH NO FORCECODE FAILED');
    vscode.window.showErrorMessage(error);
  }

  if (vscode.window.forceCode !== undefined) {
    context.subscriptions.push(vscode.commands.registerCommand('ForceCode.showMenu', () => {
      commands.showMenu(context);
    }));

    context.subscriptions.push(vscode.commands.registerCommand('ForceCode.executeAnonymous', () => {
      commands.executeAnonymous(vscode.window.activeTextEditor.document, context);
    }));

    context.subscriptions.push(vscode.commands.registerCommand('ForceCode.getLog', () => {
      commands.getLog(context);
    }));

    context.subscriptions.push(vscode.commands.registerCommand('ForceCode.compile', () => {
      commands.compile(vscode.window.activeTextEditor.document, context);
    }));

    context.subscriptions.push(vscode.commands.registerCommand('ForceCode.open', () => {
      commands.open(context);
    }));

    context.subscriptions.push(vscode.commands.registerCommand('ForceCode.exportPackage', () => {
      commands.retrieve();
    }));

    context.subscriptions.push(vscode.commands.registerCommand('ForceCode.staticResource', () => {
      commands.staticResource(context);
    }));

    context.subscriptions.push(vscode.workspace.onDidSaveTextDocument((textDocument: vscode.TextDocument) => {
      const toolingType: string = parsers.getToolingType(textDocument);
      if (toolingType && vscode.window.forceCode.config && vscode.window.forceCode.config.autoCompile === true) {
        commands.compile(textDocument, context);
      }
    }));
  }


  // // // Peek Provider Setup
  // // const peekProvider: any = new commands.PeekFileDefinitionProvider();
  // // const definitionProvider: any = vscode.languages.registerDefinitionProvider(constants.PEEK_FILTER, peekProvider);
  // // context.subscriptions.push(definitionProvider);
}
Example #15
0
	registerCommands(context: vs.ExtensionContext) {
		// Debug commands.
		context.subscriptions.push(vs.commands.registerCommand("dart.startDebugSession", debugConfig => {
			if (Object.keys(debugConfig).length === 0) {
				return {
					status: 'initialConfiguration'
				};
			}

			analytics.logDebuggerStart();

			// Attach any properties that weren't explicitly set.			
			debugConfig.cwd = debugConfig.cwd || "${workspaceRoot}";
			debugConfig.args = debugConfig.args || [];
			debugConfig.sdkPath = debugConfig.sdkPath || this.sdks.dart;
			debugConfig.debugSdkLibraries = debugConfig.debugSdkLibraries || config.debugSdkLibraries;
			debugConfig.debugExternalLibraries = debugConfig.debugExternalLibraries || config.debugExternalLibraries;
			if (debugConfig.checkedMode === undefined)
				debugConfig.checkedMode = true;

			vs.commands.executeCommand('vscode.startDebug', debugConfig);
			return {
				status: 'ok'
			};
		}));

		// Pub commands.
		context.subscriptions.push(vs.commands.registerCommand("pub.get", selection => {
			if (isFlutterProject) {
				vs.commands.executeCommand("flutter.packages.get");
			} else {
				this.runPub("get", selection);
			}
		}));
		context.subscriptions.push(vs.commands.registerCommand("pub.upgrade", selection => {
			if (isFlutterProject) {
				vs.commands.executeCommand("flutter.packages.upgrade");
			} else {
				this.runPub("upgrade", selection);
			}
		}));

		context.subscriptions.push(vs.commands.registerCommand("flutter.packages.get", selection => {
			this.runFlutter("packages get");
		}));
		context.subscriptions.push(vs.commands.registerCommand("flutter.packages.upgrade", selection => {
			this.runFlutter("packages upgrade", selection);
		}));

		// Hook saving pubspec to run pub.get.
		context.subscriptions.push(vs.workspace.onDidSaveTextDocument(td => {
			if (config.runPubGetOnPubspecChanges && path.basename(td.fileName).toLowerCase() == "pubspec.yaml")
				vs.commands.executeCommand("pub.get", td.uri);
		}));
	}
Example #16
0
function realActivation(): void {
    if (new CppSettings().intelliSenseEngine === "Disabled") {
        throw new Error(intelliSenseDisabledError);
    } else {
        console.log("activating extension");
        let checkForConflictingExtensions: PersistentState<boolean> = new PersistentState<boolean>("CPP." + util.packageJson.version + ".checkForConflictingExtensions", true);
        if (checkForConflictingExtensions.Value) {
            checkForConflictingExtensions.Value = false;
            let clangCommandAdapterActive: boolean = vscode.extensions.all.some((extension: vscode.Extension<any>, index: number, array: vscode.Extension<any>[]): boolean => {
                return extension.isActive && extension.id === "mitaki28.vscode-clang";
            });
            if (clangCommandAdapterActive) {
                telemetry.logLanguageServerEvent("conflictingExtension");
            }
        }
    }

    realActivationOccurred = true;
    console.log("starting language server");
    clients = new ClientCollection();
    ui = getUI();

    // Check for files left open from the previous session. We won't get events for these until they gain focus,
    // so we manually activate the visible file.
    if (vscode.workspace.textDocuments !== undefined && vscode.workspace.textDocuments.length > 0) {
        onDidChangeActiveTextEditor(vscode.window.activeTextEditor);
    }

    // There may have already been registered CustomConfigurationProviders.
    // Request for configurations from those providers.
    clients.forEach(client => {
        getCustomConfigProviders().forEach(provider => client.onRegisterCustomConfigurationProvider(provider));
    });

    disposables.push(vscode.workspace.onDidChangeConfiguration(onDidChangeSettings));
    disposables.push(vscode.workspace.onDidSaveTextDocument(onDidSaveTextDocument));
    disposables.push(vscode.window.onDidChangeActiveTextEditor(onDidChangeActiveTextEditor));
    disposables.push(vscode.window.onDidChangeTextEditorSelection(onDidChangeTextEditorSelection));
    disposables.push(vscode.window.onDidChangeVisibleTextEditors(onDidChangeVisibleTextEditors));

    updateLanguageConfigurations();

    reportMacCrashes();
    
    const settings: CppSettings = new CppSettings(clients.ActiveClient.RootUri);
    
    if (settings.updateChannel === 'Default') {
        suggestInsidersChannel();
    } else if (settings.updateChannel === 'Insiders') {
        insiderUpdateTimer = setInterval(checkAndApplyUpdate, insiderUpdateTimerInterval, settings.updateChannel);
        checkAndApplyUpdate(settings.updateChannel);
    }

    intervalTimer = setInterval(onInterval, 2500);
}
Example #17
0
export function activate(ctx: vscode.ExtensionContext) {
  ctx.subscriptions.push(vscode.workspace.onDidSaveTextDocument((document: vscode.TextDocument) => {
    runLinter(document);
  }));
  ctx.subscriptions.push(vscode.workspace.onDidSaveTextDocument((document: vscode.TextDocument) => {
    runFormatOnSave(document);
  }));
  activateRepl().forEach((d: vscode.Disposable) => ctx.subscriptions.push(d));
  activateReactor().forEach((d: vscode.Disposable) => ctx.subscriptions.push(d));
  activateMake().forEach((d: vscode.Disposable) => ctx.subscriptions.push(d));
  activatePackage().forEach((d: vscode.Disposable) => ctx.subscriptions.push(d));
  activateClean().forEach((d: vscode.Disposable) => ctx.subscriptions.push(d));

  ctx.subscriptions.push(vscode.languages.setLanguageConfiguration('elm', configuration))
  ctx.subscriptions.push(vscode.languages.registerHoverProvider(ELM_MODE, new ElmHoverProvider()));
  ctx.subscriptions.push(vscode.languages.registerCompletionItemProvider(ELM_MODE, new ElmCompletionProvider(), '.'));
  ctx.subscriptions.push(vscode.languages.registerDocumentSymbolProvider(ELM_MODE, new ElmSymbolProvider()));
  ctx.subscriptions.push(vscode.languages.registerDocumentFormattingEditProvider(ELM_MODE, new ElmFormatProvider()))

  // ctx.subscriptions.push(vscode.languages.registerDefinitionProvider(ELM_MODE, new ElmDefinitionProvider()));
}
export function activate(context: vscode.ExtensionContext) {
  const conf = vscode.workspace.getConfiguration('emptyIndent');

  const removeIndent = conf.get<boolean>('removeIndent');
  const highlightIndent = conf.get<boolean>('highlightIndent');
  const highlightColor = conf.get<string>('highlightColor');
  const exclude = conf.get<Array<string>>('exclude');

  let activeEditor = vscode.window.activeTextEditor;

  if (removeIndent) {
    vscode.workspace.onDidSaveTextDocument(event => {
      if (checkExclude(event.fileName, exclude)) {
        return;
      }

      vscode.commands.executeCommand('editor.action.trimTrailingWhitespace');
      vscode.window.activeTextEditor.document.save();
    });
  }

  if (highlightIndent) {

     let decoration = vscode.window.createTextEditorDecorationType({
       backgroundColor: highlightColor
     });

     vscode.window.onDidChangeActiveTextEditor(editor => {
      activeEditor = editor;
      if (editor && !checkExclude(activeEditor.document.fileName, exclude)) {
        updateDecorations(editor, decoration);
      }
    }, null, context.subscriptions);

    vscode.workspace.onDidChangeTextDocument(event => {
      if (
        activeEditor &&
        event.document === activeEditor.document &&
        !checkExclude(activeEditor.document.fileName, exclude)
      ) {
        updateDecorations(activeEditor, decoration);
      }
    }, null, context.subscriptions);

    vscode.window.onDidChangeTextEditorSelection(event => {
        const line = event.selections.length === 1 ? event.selections[0].active : null;
        if (activeEditor && !checkExclude(activeEditor.document.fileName, exclude)) {
          updateDecorations(activeEditor, decoration, line);
        }
    }, null, context.subscriptions);
  }

}
Example #19
0
export function activate(context: vscode.ExtensionContext) {

    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('Congratulations, your extension "code-gnu-global" is now active!'); 

    const global = new Global("global");
    context.subscriptions.push(vscode.languages.registerCompletionItemProvider(['cpp', 'c'], new CompletionItemProvider(global), '.', '>'));
    context.subscriptions.push(vscode.languages.registerDefinitionProvider(['cpp', 'c'], new DefinitionProvider(global)));
    context.subscriptions.push(vscode.languages.registerDocumentSymbolProvider(['cpp', 'c'], new DocumentSymbolProvider(global)));
    context.subscriptions.push(vscode.languages.registerReferenceProvider(['cpp', 'c'], new ReferenceProvider(global)));
    context.subscriptions.push(vscode.workspace.onDidSaveTextDocument(d => global.updateTags()));
}
Example #20
0
    activate(context: vscode.ExtensionContext) {
        if (this.save) {
            this.saveCommand = vscode.workspace.onDidSaveTextDocument((document: vscode.TextDocument) => {
                this.fix(document);
            });
        }

        this.command = vscode.commands.registerTextEditorCommand('phpcsfixer.fix', (textEditor: vscode.TextEditor) => {
            this.fix(textEditor.document);
        });

        context.subscriptions.push(this);
    }
Example #21
0
export function activate(context: vscode.ExtensionContext) {

    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('Congratulations, your extension "lua-luachecker" is now active!');

    diagnosticCollection = vscode.languages.createDiagnosticCollection('lua');
context.subscriptions.push(diagnosticCollection);

    vscode.workspace.onDidSaveTextDocument(document => lintDocument(document, true));
    vscode.workspace.onDidChangeTextDocument(event => lintDocument(event.document));
    vscode.workspace.onDidOpenTextDocument(document => lintDocument(document));
    vscode.window.onDidChangeActiveTextEditor((editor: vscode.TextEditor) => lintDocument(editor.document));
}
    activate() {
        let subscriptions: vscode.Disposable[] = [];
        vscode.window.onDidChangeTextEditorSelection(this.onTextEditorSelectionChanged, this, subscriptions);
        vscode.window.onDidChangeActiveTextEditor(this.onActiveTextEditorChanged, this, subscriptions);
        vscode.workspace.onDidSaveTextDocument(this.onTextDocumentSaved, this, subscriptions);
        vscode.workspace.onDidChangeTextDocument(this.onTextDocumentChanged, this, subscriptions);

        this._disposable = vscode.Disposable.from(...subscriptions);

        var activeEditor = vscode.window.activeTextEditor;
        if (activeEditor != null && activeEditor.document != null) {
            this._activeDocumentPath = vscode.window.activeTextEditor.document.fileName;            
        }
    }
 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);        
 }
export function activate(context: ExtensionContext) {

    let provider = new CssCompletionItemProvider();

    context.subscriptions.push(workspace.onDidSaveTextDocument((e) => {
        if (e.languageId === 'css') {
            provider.refreshCompletionItems();
        }
    }));

    context.subscriptions.push(languages.registerCompletionItemProvider('html', provider));
    context.subscriptions.push(languages.registerCompletionItemProvider('php', provider));
    context.subscriptions.push(languages.registerCompletionItemProvider('vue', provider));

}
Example #25
0
			return new Promise<string>(async resolve => {
				const doc = await createDoc(options.contents);
				workspace.onDidChangeTextDocument(doc.save);
				workspace.onDidSaveTextDocument(savedDoc => {
					assert.strictEqual(savedDoc.isDirty, false, 'dirty saved doc');
					resolve(savedDoc.getText());
				});
				const edit = new WorkspaceEdit();
				edit.insert(doc.uri, new Position(0, 0), text);
				assert.strictEqual(
					await workspace.applyEdit(edit),
					true,
					'editor fails to apply edit'
				);
			});
    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);
    }
	constructor() {
		const subscriptions: Disposable[] = [];

		// Listen for changes in the active text editor
		subscriptions.push(window.onDidChangeActiveTextEditor(textEditor => {
			if (textEditor && textEditor.document) {
				this._onDidOpenDocument(textEditor.document);
			}
		}));

		// Listen for changes in the configuration
		subscriptions.push(workspace.onDidChangeConfiguration(
			this._onConfigChanged.bind(this)
		));

		// Listen for saves to ".editorconfig" files and rebuild the map
		subscriptions.push(workspace.onDidSaveTextDocument(savedDocument => {
			if (path.basename(savedDocument.fileName) === '.editorconfig') {
				// Saved an .editorconfig file => rebuild map entirely and then
				// apply the changes to the .editorconfig file itself
				this._rebuildConfigMap();
				// TODO The transformations should be applied to the `.editorconfig` file as well after the config
				// has been rebuilt
				// this._rebuildConfigMap().then(applyOnSaveTransformations.bind(
				// 	undefined,
				// 	savedDocument,
				// 	this
				// ));
				return;
			}
		}));

		subscriptions.push(workspace.onWillSaveTextDocument(e => {
			const edits = calculatePreSaveTransformations(e.document, this);

			e.waitUntil(Promise.resolve(edits));
		}));

		// dispose event subscriptons upon disposal
		this._disposable = Disposable.from.apply(this, subscriptions);

		// Build the map (cover the case that documents were opened before
		// my activation)
		this._rebuildConfigMap();

		// Load the initial workspace configuration
		this._onConfigChanged();
	}
    subscribeToEvents(){
        let saveEvent = vscode.workspace.onDidSaveTextDocument((textDocument) => {
            let compileOnSaveConfigured = getConfiguration('mavensMate.compileOnSave');
            let isApexScript = textDocument.fileName.includes('apex-scripts');

            if (!compileOnSaveConfigured) {
                console.info('MavensMate: compileOnSave is not configured.');
            } else if (isApexScript) {
                console.info('MavensMate: silently ignoring the saving of a local apex script. (OK you got me, this isn\'t necessarily silence)');
            } else {
                return vscode.commands.executeCommand('mavensmate.compileFile', textDocument.uri);
            }
        });
        this.context.subscriptions.push(saveEvent);

        this.mavensMateChannel.appendStatus('Subscribed to events');
    }
export function activate(context: vscode.ExtensionContext) {
    if (vscode.workspace && vscode.workspace.rootPath) {
        var tasksOutputChannel = new OutputChannel;
        tasksOutputChannel.addOutputChannel('Status Bar Tasks');
        var saveContext = vscode.workspace.onDidSaveTextDocument((textDocument : vscode.TextDocument) => {
            if (textDocument.fileName.endsWith('tasks.json')) {
                statusBarItems.forEach((i: vscode.StatusBarItem) => {
                    i.hide();
                });
                statusBarItems = [];
                LoadTasks(context, tasksOutputChannel);
            }
        });
        context.subscriptions.push(saveContext);
        LoadTasks(context, tasksOutputChannel);
    }
}
export function activateFormatOnSaveProvider(languageFilter: vscode.DocumentFilter, settings: settings.IPythonSettings, outputChannel: vscode.OutputChannel, workspaceRootPath: string): vscode.Disposable {
    let formatters = new Map<string, BaseFormatter>();
    let pythonSettings = settings;

    let yapfFormatter = new YapfFormatter(outputChannel, settings, workspaceRootPath);
    let autoPep8 = new AutoPep8Formatter(outputChannel, settings, workspaceRootPath);

    formatters.set(yapfFormatter.Id, yapfFormatter);
    formatters.set(autoPep8.Id, autoPep8);

    // This is really ugly.  I'm not sure we can do better until
    // Code supports a pre-save event where we can do the formatting before
    // the file is written to disk.	
    let ignoreNextSave = new WeakSet<vscode.TextDocument>();

    let subscription = vscode.workspace.onDidSaveTextDocument(document => {
        if (document.languageId !== languageFilter.language || ignoreNextSave.has(document)) {
            return;
        }
        let textEditor = vscode.window.activeTextEditor;
        if (pythonSettings.formatting.formatOnSave && textEditor.document === document) {
            let formatter = formatters.get(pythonSettings.formatting.provider);
            let delays = new telemetryHelper.Delays();

            formatter.formatDocument(document, null, null).then(edits => {
                if (edits.length === 0) return false;
                return textEditor.edit(editBuilder => {
                    edits.forEach(edit => editBuilder.replace(edit.range, edit.newText));
                });
            }).then(applied => {
                delays.stop();
                telemetryHelper.sendTelemetryEvent(telemetryContracts.IDE.Format, { Format_Provider: formatter.Id, Format_OnSave: "true" }, delays.toMeasures());
                ignoreNextSave.add(document);
                return applied ? document.save() : true;
            }).then(() => {
                ignoreNextSave.delete(document);
            }, () => {
                // Catch any errors and ignore so that we still trigger 
                // the file save.
            });
        }
    }, null, null);

    return subscription;
}