D.Diniz
D.Diniz

Reputation: 41

Maintain screen position always centered on cursor

I'm trying to write an extension for VSCode where the editor screen is always centered on the cursor. There are other extensions that add a command to center the screen onto the cursor, but you have to press the command to activate it.

Currently the only way I've found to implement this is to rewrite the cursorUp, cursorDown, enter, pageUp, pageDown -- any command that moves the cursor up and down basically, and then use the "revealLine" command with the cursor line position and with the "at" attribute as "center".

Is there a better way? Reimplementing the default editor commands seems very inefficient.

Here's what I've got currently:

"use strict";
import * as vscode from "vscode";

export function activate(context: vscode.ExtensionContext) {
    let disposable1 = vscode.commands.registerCommand("cursorUp",() => {
            centralizar();
            vscode.commands.executeCommand("cursorMove", {
                to: "up",
            });
        }
    );

    let disposable2 = vscode.commands.registerCommand("cursorDown",() => {
            centralizar();
            vscode.commands.executeCommand("cursorMove", {
                to: "down",
            });
        }
    );

    context.subscriptions.push(disposable1);
    context.subscriptions.push(disposable2);
}

function centralizar() {
    let currentLineNumber = vscode.window.activeTextEditor.selection.start.line;
    vscode.commands.executeCommand("revealLine", {
        lineNumber: currentLineNumber,
        at: "center"
    });
}

export function deactivate() {}

Upvotes: 3

Views: 3165

Answers (3)

Jervis
Jervis

Reputation: 124

You can use Typewriter Auto-scroll VSCode Extension

Upvotes: 1

Mark
Mark

Reputation: 180815

Perhaps you can utilize the new (v1.38) command editor.cursorSurroundingLines. See scrollOff release notes.

scrollOff demo

It takes a number, but if you can get the number of visible lines in an editor window, then set editor.cursorSurroundingLines to the appropriate midpoint that may work. It seems you would not have to listen for scroll events. But would have to update the value if the editor window was resized.

Upvotes: 10

Scott McPeak
Scott McPeak

Reputation: 12749

The Scrolloff extension implements this functionality when its "alwaysCenter" option is enabled. It works by listening to window.onDidChangeTextEditorSelection, which fires when the cursor moves.

Upvotes: 0

Related Questions