Code View

fson / vscode-fson / extension / extension.js
// SPDX-License-Identifier: MIT
// FSON VS Code extension — activation.
//
// Registers a document formatter for the `fson` language. The formatter is
// a faithful JavaScript port of FFS's canonical FsonWriter (Fson dialect):
// it parses the whole document into a model with attached comments, then
// re-emits it in canonical form, losing nothing (comments, --disabled
// members, exact number lexemes, |-block strings, key form).

const vscode = require('vscode');
const { format } = require('./formatter');

function activate(context) {
  const selector = { language: 'fson', scheme: 'file' };
  const alsoUntitled = { language: 'fson', scheme: 'untitled' };

  const provider = {
    provideDocumentFormattingEdits(document) {
      const original = document.getText();
      let result;
      try {
        result = format(original, {
          preferBareKeys: vscode.workspace
            .getConfiguration('fson.format')
            .get('preferBareKeys', false),
        });
      } catch (err) {
        vscode.window.showErrorMessage(
          'FSON: could not format document — ' + (err && err.message)
        );
        return [];
      }

      // If the parser reported hard errors, refuse to format rather than
      // risk mangling a file the user is mid-edit on.
      if (result.errors && result.errors.length > 0) {
        vscode.window.showWarningMessage(
          'FSON: not formatting — the document has ' +
            result.errors.length +
            ' parse error(s). Fix them and try again.'
        );
        return [];
      }

      if (result.output === original) return [];

      const fullRange = new vscode.Range(
        document.positionAt(0),
        document.positionAt(original.length)
      );
      return [vscode.TextEdit.replace(fullRange, result.output)];
    },
  };

  context.subscriptions.push(
    vscode.languages.registerDocumentFormattingEditProvider(selector, provider),
    vscode.languages.registerDocumentFormattingEditProvider(alsoUntitled, provider)
  );
}

function deactivate() {}

module.exports = { activate, deactivate };