VS代码API:如何将文本插入行底部

发布于 2025-01-30 17:24:02 字数 554 浏览 3 评论 0原文

我开始创建VS代码的扩展名,并面临问题。

如您在标题中所见,我想将某些文本插入行的底部。为了意识到这一点,我尝试了这一点:

let moveBy = {to: 'wrappedLineEnd', by: 'line'};
vscode.commands.executeCommand('cursorMove', moveBy);
editor.edit(editBuilder =>{
    if (editor !== undefined){
    editBuilder.insert(editor.selection.active, "test");
    }

});

但是,它运行不佳。结果是:

//Before: this is the text.
//cursor is between 'h' and 'i'(from 'this')
//After: thtestis is the text
//Omg 'test' is inserted here

在我看来,光标没有移动,最终将字符串插入到那里。 有什么解决方案吗?

I started to create an extension of VS Code and am facing a problem.

As you see in the title, I want to insert the certain text in the bottom of line. To realize this, I tried this:

let moveBy = {to: 'wrappedLineEnd', by: 'line'};
vscode.commands.executeCommand('cursorMove', moveBy);
editor.edit(editBuilder =>{
    if (editor !== undefined){
    editBuilder.insert(editor.selection.active, "test");
    }

});

However, it does not work well; it resulted in this:

//Before: this is the text.
//cursor is between 'h' and 'i'(from 'this')
//After: thtestis is the text
//Omg 'test' is inserted here

It seems to me that the cursor did not move and it ended up inserting the string there.
Is there any solution to this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风渺 2025-02-06 17:24:02

虽然您可以等待cursormove命令,但我认为最好在行末尾简单地计算范围自己。您不必等待将光标移至要编辑的位置。

您只需要知道要在哪里进行编辑(如果您不知道可以在文档中的任何位置进行编辑,那么已经不需要一个光标了)。

const editor = vscode.window.activeTextEditor;

// let moveBy = {to: 'wrappedLineEnd', by: 'line'};
// await vscode.commands.executeCommand('cursorMove', moveBy);

// get range at end of line
const editRange = editor.document.lineAt(editor.selection.end.line).range.end;

editor.edit(editBuilder =>{
    if (editor !== undefined){
    // editBuilder.insert(editor.selection.active, "test");
    editBuilder.insert(editRange, "test");
    }

});

While you can await the cursorMove command, I think it is better practice to simply compute the range at the end of the line yourself. You do not have to await moving a cursor to where you want to make an edit.

You just have to know where you want to make an edit (in case you didn't know you can make an edit anywhere in the document, there doesn't need to be a cursor there already).

const editor = vscode.window.activeTextEditor;

// let moveBy = {to: 'wrappedLineEnd', by: 'line'};
// await vscode.commands.executeCommand('cursorMove', moveBy);

// get range at end of line
const editRange = editor.document.lineAt(editor.selection.end.line).range.end;

editor.edit(editBuilder =>{
    if (editor !== undefined){
    // editBuilder.insert(editor.selection.active, "test");
    editBuilder.insert(editRange, "test");
    }

});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文