VSCode插件开发
发现一个很好的教程系列:VSCode插件开发全攻略。
待我学完我也写一写。
update 2020/9/2
求助帖!!!
一直尝试写一个自动debug c++的插件,因为有大量的用c++写算法的需求,所以想自己开发一个这样的插件,能够自动进行对拍操作。
逻辑
- 选择有 🐛的代码文件,输入命令:对拍。
- 生成标准文件(暴力)和数据生成文件。
- 循环:
- 数据生成
- 运行标准文件
- 运行有🐛的文件
- 比对输出
实现
这里用到了vscode的许多技巧,很有学习的必要。
但是,我还没有实现完,遇到了一个棘手的问题:我希望完成在终端运行某一个文件,但是使用child_process
模块的spawn
无论如何也无法在vscode节面中运行,只能在bash中运行。如果有看官知道如何解决这个问题,或者其他能够使用node.js在bash上运行一个命令的方法,请不吝赐教。
const process = require("child_process");
context.subscriptions.push(vscode.commands.registerCommand("generation.startRun", function() {
let xx = process.spawn("echo", ["'Hello, world."]);
xx.stdout.on("data", (data) => {
vscode.window.showInformationMessage(data.toString());
});
}));
// It doesn't work on vscode. But I've got `child_process` running very well on dependent terminal. Please Help!!
下面记录一下技能点。
注册命令
每当我们要使用一个新的命令,需要在package.json
中添加:
"contributes": {
"commands": [{
"command": "test-generation.helloWorld",
"title": "Hello World"
},
{
"command": "generation.generateTests",
"title": "generation: generate tests"
},
{
"command": "generation.startRun",
"title": "generation: start running scripts"
}]
}
这是为了为唤醒命令定义输入(title)。
然后,在src/extension.js
中添加命令。
let disposable = vscode.commands.registerCommand('test-generation.helloWorld', function() {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
vscode.window.showInformationMessage('Hello World from test-generation!');
});
context.subscriptions.push(disposable);
如果你没有更改过其他的地方,那么按下F5
,应该就可以在输入命令后得到一句'Hello World from test-generation!'啦!
加载框
通过vscode.window.withProgress
可以实现一个加载框。
vscode.window.withProgress({
cancellable: true,
location: vscode.ProgressLocation.Notification,
title: "Building debug scripts..."
}, (progress, token) => {
token.onCancellationRequested(() => {
vscode.window.showInformationMessage("You have cancelled generation!");
});
return new Promise((resolve) => {
// do something during processing
resolve();
}
});
需要注意,如果有需要的话,resolve是应该放在最后的回调函数中的,否则在回调前就会退出。
终端命令
使用终端命令在这个插件中尤为重要,node.js提供了一个模块child_process
可以实现这个功能。
const process = require("child_process");
process.exec( 'ls -lh /usr' , function(err, stdout , stderr ) {
console.log( stdout );
});
let c = process.spawn("echo", ["'Hello, world.'"]);
c.stdout.on("data", (data) => {
console.log(data.toString());
})
// let compile = process.spawn("g++", ["A.cpp", "-o", "a"]);
/* let compile = process.spawn("./a.exe");
compile.stderr.on("error", (err) => {
console.error(err);
});
compile.stdout.on("data", (data) => {
console.log(data.toString());
}); */
相比而言,exec
比较简单,而spawn
对于大量输出来说,更加节省内存,因为它并非exec
那样等命令运行结束才输出全部的。
更多参考资料:
update 2020/10/29
新插件开发:online dictionary
一个人没有梦想,和咸鱼有什么区别!