Vscode: Extension API: cursor position (determining current location and moving it)

Created on 18 Nov 2015  路  7Comments  路  Source: microsoft/vscode

Seems like the only way to get the current cursor position is if the user explicitly selects something.

Most helpful comment

:heart_eyes: Perfect!

        const editor = vscode.window.activeTextEditor;
        const position = editor.selection.active;

        var newPosition = position.with(position.line, 0);
        var newSelection = new vscode.Selection(newPosition, newPosition);
        editor.selection = newSelection;

+1 on the docs to denote setters.

All 7 comments

Hi @jpoon,

Even if there is no selected text, you have to use the selection object. Something like this:

    // current editor
    const editor = vscode.window.activeTextEditor;

    // check if there is no selection
    if (editor.selection.isEmpty) {
      // the Position object gives you the line and character where the cursor is
      const position = editor.selection.active;
    }

Hope this helps

@alefragnani perfect. I'm going to close this issue :+1:

@alefragnani one more question, is there a way to move the cursor?

Say for the sample code you posted:

    // current editor
    const editor = vscode.window.activeTextEditor;

    // check if there is no selection
    if (editor.selection.isEmpty) {
      // the Position object gives you the line and character where the cursor is
      const position = editor.selection.active;

      // move cursor to this new position?
      var newPosition = position.with(position.line, 0);
    }

@jrieken The API should probably indicate in the doc comments what can be set.

:heart_eyes: Perfect!

        const editor = vscode.window.activeTextEditor;
        const position = editor.selection.active;

        var newPosition = position.with(position.line, 0);
        var newSelection = new vscode.Selection(newPosition, newPosition);
        editor.selection = newSelection;

+1 on the docs to denote setters.

All properties that don't have the @readonly tag can be set.

Was this page helpful?
0 / 5 - 0 ratings