1.replace by**.#**

发布时间 2023-03-27 21:44:03作者: 月夜魂归

该条笔记由Elder在2023/3/27 21:31:30推送

注册命令、绑定快捷键

//package.json
"activationEvents": [
	"onCommand:hello.log"
],
"main": "./extension.js",
"contributes": {
	"commands": [
		{
			"command": "hello.log",
			"title": "Hello World"
		}
	],
	"keybindings": [
		{
			"key": "ctrl+shift+h",
			"command": "hello.log",
			"when": "editorTextFocus"
		}
	]
},

文本替换实现

//extension.js
function activate(context) {

	let disposable = vscode.commands.registerCommand('hello.log', function () {
		// 获得当前编辑器
		const currentEditor = vscode.window.activeTextEditor;
		if (!currentEditor) {
			return;
		}
		// 正则表达式匹配.#结尾的文本
		const reg =/(\S+)(#)$/;
		// 获得选中内容和当前document
		const {selection,document} = currentEditor;
		// 获得选中内容的光标位置,正则匹配后的位置包含开始位置,结束位置
		const position = document.getWordRangeAtPosition(selection.anchor,reg);
		console.log(position);
		if(!position){
			return vscode.window.showInformationMessage('请输入#结尾');
		}
		// 获得文本内容
		const docText = document.getText(position);
		// 文本正则化  返回数组比如 ['//实现乘法表#', '//实现乘法表', '#', index: 0, input: '//实现乘法表#', groups: undefined]
		const tempArr = reg.exec(docText);
		console.log(tempArr);
		const prefix = tempArr && tempArr[1];
		console.log(prefix); ////实现乘法表
		const replaceText = `${prefix}`+"\t模板添加时间:"+`${new Date().toLocaleDateString()}`+'#';

		// 替换文本
		currentEditor.edit(editBuilder => {
			editBuilder.replace(position,replaceText);
		})
		.then(()=>{
			//修改光标位置
			const line = position.start.line;
			const index = document.lineAt(line).firstNonWhitespaceCharacterIndex;
			currentEditor.selection = new vscode.Selection(
				new vscode.Position(line,replaceText.length+index),
				new vscode.Position(line,replaceText.length+index)
			);
			vscode.window.showInformationMessage('写入成功');
		})
	});

	context.subscriptions.push(disposable);
}