Danny Tuppeny Danny Tuppeny - 4 months ago 19
Dart Question

How do I set indenting options for a language in a VSCode extension?

I'm working on a VS Code extension for Dart. The convention for Dart is to indent with 2 spaces (ugh, I hate this too) so I'd like to automatically set it when the user opens a Dart file rather than use their defaults.

There's an

insertSpaces
property in the
FormattingOptions
class but it's not clear how I can set this, nor the best way to do it (it would be nicer to set this at a language level than to keep setting it whenever a document is opened, for example).

Answer

In order to use the FormattingOptions, set up a callback for vscode.window.onDidChangeActiveTextEditor() in your extension's activate() function:

let disposable = vscode.window.onDidChangeActiveTextEditor((editor) => {
    if(!editor) {
        return;
    }

    if (editor.document.languageId != "your_id_here") {
        return;
    }

    editor.options = {
        cursorStyle: editor.options.cursorStyle,
        insertSpaces: true,
        tabSize: 2
    };
});

context.subscriptions.push(disposable);
Comments