Get Formatter for a Language

Viewed 168

I want to make a relatively simple formatter in VS Code. Essentially, I have a bunch of *.md.j2 files (Jinja2 templates that ultimately become Markdown). I have the Better Jinja extension to render these, with the language jinja-md in VS Code.

I started off just wanting to use prettier's Markdown formatting and call it a day. I tried adding this to settings.json:

"[jinja-md]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true,
},

This does not work because esbenp.prettier-vscode does not register itself for the jinja-md type; it seems to have no "break glass" option to configure that.

This got me to thinking that it would be nice to make a formatter that ignored Jinja tag lines (e.g. {% if foo == 'bar' %}\n and then passed on the fragments to whatever the underlying file type formatter was. So basically I want to do something like:

vscode.languages.registerDocumentFormattingEditProvider('jinja-md', {
  provideDocumentFormattingEdits(document: vscode.TextDocument): vscode.TextEdit[] {
    // THIS IS THE QUESTION:
    // vscode.languages.getFormatter is not a real method. I want to know
    // how to pull off this concept.
    mdFormatter = vscode.languages.getFormatter('md');

    // Get segments between %}\n and \n{% and route them to the
    // `mdFormatter` -- I think I know how to do this and am not bothering
    // to write the code here.
  }
});

Is this a thing I can do -- can I programmatically get from VSCode "the formatter user-configured for language X"?

0 Answers
Related