在 VsCode 编辑器中获取光标前的所有文本
Get all text before cursor in VsCode editor
我正在为 VsCode 开发自动完成扩展,我想要光标前的用户文件的所有文本。我知道我们可以使用以下方法获取文件中的所有文本:
var editor = vscode.window.activeTextEditor;
var text= editor.document.getText();
但是我很困惑如何获取光标的位置并获取光标之前的文本?
const editor = vscode.window.activeTextEditor;
const cursorPosition = editor.selection.active; // a vscode.Position
// for text on line up to cursor
// const lineText = editor.document.lineAt(cursorPosition.line).text;
// const textBeforeCursor = lineText.substring(0, cursorPosition.character);
// for text in the file up to cursor
const fileTextToCursor = editor.document.getText(new vscode.Range(0, 0, cursorPosition.line, cursorPosition.character));
文件中到光标为止的文本:
getText()
需要一个 vscode.Range
,它可以从光标位置构造。以0,0
为起点point/Position,光标位置为终点即可。
对于光标所在行的文本:
您从选择中获取光标位置。该变量有一个 line
属性,您可以使用它来获取该行的文本。
然后一个字符串操作substring
得到光标前的文字。 cursorPosition.character
returns 光标在行中的列位置的数字。
[如果你有多个光标,你将不得不修改它。此代码适用于文件中的主光标。更改它很容易 - 在所有选择中添加一个循环。]
我正在为 VsCode 开发自动完成扩展,我想要光标前的用户文件的所有文本。我知道我们可以使用以下方法获取文件中的所有文本:
var editor = vscode.window.activeTextEditor;
var text= editor.document.getText();
但是我很困惑如何获取光标的位置并获取光标之前的文本?
const editor = vscode.window.activeTextEditor;
const cursorPosition = editor.selection.active; // a vscode.Position
// for text on line up to cursor
// const lineText = editor.document.lineAt(cursorPosition.line).text;
// const textBeforeCursor = lineText.substring(0, cursorPosition.character);
// for text in the file up to cursor
const fileTextToCursor = editor.document.getText(new vscode.Range(0, 0, cursorPosition.line, cursorPosition.character));
文件中到光标为止的文本:
getText()
需要一个 vscode.Range
,它可以从光标位置构造。以0,0
为起点point/Position,光标位置为终点即可。
对于光标所在行的文本:
您从选择中获取光标位置。该变量有一个 line
属性,您可以使用它来获取该行的文本。
然后一个字符串操作substring
得到光标前的文字。 cursorPosition.character
returns 光标在行中的列位置的数字。
[如果你有多个光标,你将不得不修改它。此代码适用于文件中的主光标。更改它很容易 - 在所有选择中添加一个循环。]