[英]VSCode Open a File In a Specific Line Number Using JS
我在我的 VSCode 中添加了一个新按钮,这样当我单击它时 - 它会编译当前文件夹,并使用vscode.window.showInformationMessage
显示对话框。
每个框显示一个编译错误,并在其中有一个按钮。 一旦用户单击按钮 - 它会使用vscode.workspace.openTextDocument
在选项卡中打开有问题的文件。
我想让按钮也将我导航到有问题的文件中的有问题的行。
我的问题是:
给定一个数字,是否可以导航到文件中的特定行号?
到目前为止我取得的示例代码:
// Bullshit to give some context
const pattern = /(In \w+.jack)/g;
var i = s.search(pattern);
var substring = s.substring(i + 1)
var j = substring.search(pattern);
var s = "bsadsdbla In main.jack (line 55) sqdwqe blasdsd wq qqweq"
let GoToFile = 'Go to File';
var k = s.search(/(\w+.jack)/);
var l = s.search(/(.jack)/)
var fileName = s.substring(k, l);
// ---------> This is the important part <----------------
vscode.window.showInformationMessage(s.substring(i, j), GoToFile).then(selection => {
if (selection === GoToFile) {
vscode.workspace.openTextDocument(currentDirectory + '\\' + fileName + '.jack')
.then(document => vscode.window.showTextDocument(document));
}
});
我假设您有一些代码/正则表达式可以为您提供行号。 每当有人单击您的 GoToFile 方法时,都会调用以下代码:
activeEditor.selections = [new vscode.Selection(lineToGo, lineToGo)];
var range = new vscode.Range(lineToGo, lineToGo);
activeEditor.revealRange(range);
一些背景:
正如@rioV8 所提到的, revealRange
是通往 go 的方法,但问题是我无法理解如何使用 VSCode API 来使用它,所以这里@Shahriar Hossain 出现了。 @Shahriar Hossain 的代码有效,但是缺少一个重要的声明,我还必须弄清楚当用户单击按钮时如何运行代码。
这是完整的解决方案:
vscode.window.showInformationMessage(s.substring(i), GoToFile).then(selection => {
if (selection === GoToFile) {
vscode.workspace.openTextDocument(currentDirectory + '\\' + fileName + '.jack')
.then(document => vscode.window.showTextDocument(document))
// Whatever code inside this "then" block
// will be executed on button click
.then(x => {
let m = s.substring(i, j).search(/\(line \d+\)/);
let subStr = s.substring(m + 6);
let n = subStr.search(/\)/);
subStr = subStr.substring(0, n);
let lineToGo = parseInt(subStr.match(/\d+/));
// The missing declaration of the activeEditor
let activeEditor = vscode.window.activeTextEditor;
let range = activeEditor.document.lineAt(lineToGo - 1).range;
activeEditor.selection = new vscode.Selection(range.start, range.end);
activeEditor.revealRange(range);
})
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.