當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript workspace.onDidSaveTextDocument方法代碼示例

本文整理匯總了TypeScript中vscode.workspace.onDidSaveTextDocument方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript workspace.onDidSaveTextDocument方法的具體用法?TypeScript workspace.onDidSaveTextDocument怎麽用?TypeScript workspace.onDidSaveTextDocument使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在vscode.workspace的用法示例。


在下文中一共展示了workspace.onDidSaveTextDocument方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: loadConfiguration

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();
	}
}
開發者ID:scytalezero,項目名稱:vscode-npm-scripts,代碼行數:30,代碼來源:main.ts

示例2: getDiagnostics

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);
};
開發者ID:feosuna1,項目名稱:dotfiles,代碼行數:26,代碼來源:extension.ts

示例3: activate

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);
        }
    });
}
開發者ID:sergey-kintsel,項目名稱:vscode-ruby-rubocop,代碼行數:26,代碼來源:extension.ts

示例4: setup

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);
    }
  }));

}
開發者ID:rtorr,項目名稱:vscode-flow,代碼行數:33,代碼來源:diagnostics.ts

示例5: activate

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);
}
開發者ID:browniefed,項目名稱:vscode-gist,代碼行數:25,代碼來源:extension.ts

示例6: activate

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)}));
}
開發者ID:miladkh7,項目名稱:vscode-matlab,代碼行數:28,代碼來源:matlabMain.ts

示例7: activate

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);
}
開發者ID:Huachao,項目名稱:vscode-restclient,代碼行數:59,代碼來源:extension.ts

示例8: startLintOnSaveWatcher

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);
		});
	});
}
開發者ID:ShH-Chen,項目名稱:vscode-matlab,代碼行數:57,代碼來源:matlabMain.ts

示例9: createRsSaveWatcher

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 ); }` );
            }
        });
    }
}
開發者ID:acauan,項目名稱:vscode-cm,代碼行數:9,代碼來源:extension.ts

示例10: Promise

			return await new Promise(resolve => {
				let saveCount = 0;
				workspace.onDidSaveTextDocument(savedDoc => {
					if (++saveCount === (options.saves || 1)) {
						resolve(savedDoc.getText());
					}
				});
				doc.save();
			});
開發者ID:SamVerschueren,項目名稱:editorconfig-vscode,代碼行數:9,代碼來源:index.test.ts

示例11: activate

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));
}
開發者ID:karai17,項目名稱:vscode-lualinter,代碼行數:9,代碼來源:extension.ts

示例12: activate

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);
}
開發者ID:mizunashi-mana,項目名稱:vscode-phpcs,代碼行數:57,代碼來源:extension.ts

示例13: constructor

  constructor(newLineHandler: NewLineHandler) {
    this._newLineHandler = newLineHandler;

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

    this._disposable = Disposable.from(...subscriptions);
  }
開發者ID:jdforsythe,項目名稱:vscode-add-new-line-to-files,代碼行數:9,代碼來源:extension.ts

示例14: activate

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);
}
開發者ID:rebornix,項目名稱:ForceCode,代碼行數:56,代碼來源:extension.ts

示例15: registerCommands

	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);
		}));
	}
開發者ID:devoncarew,項目名稱:Dart-Code,代碼行數:55,代碼來源:sdk.ts


注:本文中的vscode.workspace.onDidSaveTextDocument方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。