【问题标题】:How to remove selection after replace in vscode API如何在 vscode API 中替换后删除选择
【发布时间】:2018-01-19 05:12:16
【问题描述】:

在为 vscode 创建扩展时,我卡在了选择中,现在的问题是,当我通过 api 替换某些范围的 textEditor 时,它会替换该范围并选择该范围。对于 sn-ps 这是一个好主意,但我的扩展要求不是选择替换文本,我在 api 中搜索但没有找到与删除文本选择相关的任何内容(当文档为空时发生选择)

editor.edit((editBuilder)=>{ //editor is an object of active text editor
        editBuilder.replace(textRange,text)   // text = 'dummydummydummy'
    }) //after this I got the following output

【问题讨论】:

    标签: visual-studio-code vscode-extensions


    【解决方案1】:
    editor.edit(builder => {
        builder.replace(selection, newStr);
    })
    // The edit call returns a promise. When that resolves you can set 
    // the selection otherwise you interfere with the edit itself. 
    // So use "then" to sure edit call is done; 
    .then(success => {
        console.log("success:", success);
        // Change the selection: start and end position of the new
        // selection is same, so it is not to select replaced text;
        var postion = editor.selection.end; 
        editor.selection = new vscode.Selection(postion, postion);
    });
    

    【讨论】:

      【解决方案2】:

      我相信发生这种情况是因为编辑正在应用于当前选择。 edit 返回一个在应用编辑时解析的promise,您可以在编辑成功后使用它来设置选择:

      editor.edit((editBuilder) => {
          editBuilder.replace(textRange, text)
      }).then(success => {
          if (success) {
              // make selection empty
              editor.selection.active = editor.selection.anchor
          }
      })
      

      【讨论】:

      • 这没用,我还想补充一点,只要文档为空,在其他情况下选择就会正常工作
      • 我猜这是在编辑器中未定义范围时发生的,我只想知道 vscode 中是否有类似缓冲区更改之类的东西可以通过 api 访问,以便我可以跟踪以前的选择
      【解决方案3】:
      let editor = vscode.window.activeTextEditor;
      let selection = editor.selection;
      editor.edit(builder => {
          builder.replace(selection, newStr);
      });
      

      见:TextEditorEdit API Doc

      【讨论】:

      • 您能否解释一下这段代码的作用,以及为什么它可以解决问题?它可以帮助其他来访问问题和答案的人。
      • 不知道这是怎么投票的。它似乎只是重复了 OP 从问题开始时所做的事情。
      猜你喜欢
      • 1970-01-01
      • 2013-12-12
      • 2011-03-27
      • 2021-03-03
      • 1970-01-01
      • 2018-03-14
      • 2019-10-07
      • 1970-01-01
      • 2022-12-07
      相关资源
      最近更新 更多