github copilot 用来突出显示文本的元素的名称是什么?

问题描述

我想做一个类似于github copilot使用的控件。我的意思是突出显示提议的文本。实时共享扩展使用非常相似的方法。这个控件叫什么名字?

实时预览扩展中的控制:

control in live preview extension

副驾驶扩展中的控制:

control in copilot extension

我猜它可能是 TextEditordecorationType?但是,我不知道如何设置样式以便作者绝对定位:/

解决方法

您可以使用文本编辑器装饰器创造类似的体验。这些装饰器允许您为文档中的任何文本(包括前景色和背景色)使用自定义样式模式。

您在上面可视化的文本突出显示示例只是向用户选择或扩展程序建议的文本范围添加背景颜色。

例如:如果您想为 console.log 添加自定义突出显示:

然后您可以使用以下内容:

import * as vscode from 'vscode'

const decorationType = vscode.window.createTextEditorDecorationType({
  backgroundColor: 'green',border: '2px solid white',})

export function activate(context: vscode.ExtensionContext) {
  vscode.workspace.onWillSaveTextDocument(event => {
    const openEditor = vscode.window.visibleTextEditors.filter(
      editor => editor.document.uri === event.document.uri
    )[0]
    decorate(openEditor)
  })
}

function decorate(editor: vscode.TextEditor) {
  let sourceCode = editor.document.getText()
  let regex = /(console\.log)/

  let decorationsArray: vscode.DecorationOptions[] = []

  const sourceCodeArr = sourceCode.split('\n')

  for (let line = 0; line < sourceCodeArr.length; line++) {
    let match = sourceCodeArr[line].match(regex)

    if (match !== null && match.index !== undefined) {
      let range = new vscode.Range(
        new vscode.Position(line,match.index),new vscode.Position(line,match.index + match[1].length)
      )

      let decoration = { range }

      decorationsArray.push(decoration)
    }
  }

  editor.setDecorations(decorationType,decorationsArray)
}

Reference Link