skip to Main Content

I want to build a custom editor following this guide: https://code.visualstudio.com/api/extension-guides/custom-editors

My editor is also backed by JSON, but when studying the example it says

// Just replace the entire document every time for this example extension.
// A more complete extension should compute minimal edits instead.

https://github.com/microsoft/vscode-extension-samples/blob/bb473a1724d7595006760a9dfdc31e2429fa6cc7/custom-editor-sample/src/catScratchEditor.ts#L196-L197

How do I actually concretely do this?

Since the VSCode settings editor is also a GUI for a JSON file, is there some API to turn JSON changes into document edits?

Or are there JSON parsers that have some sort of red-green tree based structure to relate JSON data back to source location?

2

Answers


  1. Chosen as BEST ANSWER

    I found jsonc-parser which has an API for applying modifications to a JSON document and generating text offsets and such. It is authored by Microsoft and seems widely used within VSCode

    /**
     * Computes the edit operations needed to modify a value in the JSON document.
     * 
     * @param documentText The input text 
     * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
     * If the path points to an non-existing property or item, it will be created. 
     * @param value The new value for the specified property or item. If the value is undefined,
     * the property or item will be removed.
     * @param options Options
     * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.
     * To apply the edit operations to the input, use {@linkcode applyEdits}.
     */
    export function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): EditResult;
    

  2. To compute minimal edits to a JSON document for a VSCode WorkspaceEdit, you can follow these general steps:
    Parse the original JSON document and the desired modified JSON document into their respective data structures.
    Compare the two data structures to identify the differences between them. This can be done by recursively traversing the structures and comparing each element.
    As you identify differences, keep track of the read more

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search