[英]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.