Search code examples
javascriptmonaco-editor

Can the Monaco Editor use different line numbering based on the model?


I'm using the Monaco Editor to display some custom file types.
For these files, I need to customize the displayed line numbers based on the models. This is fine for a single model but not when I want to peek to the definition in another model/file. (For the content, the displayed line numbers don't always start at the same number and some physical lines in the file don't count as a line and so shouldn't have a line number displayed next to them.)

I'm setting the custom line numbers as per the example at https://microsoft.github.io/monaco-editor/playground.html?source=v0.49.0#example-interacting-with-the-editor-customizing-the-line-numbers

This lineNumbersFunc is always the same for every file/model that is displayed, but that's not what I want.

Is there another way to specify the line numbers? (based on models)
or
Is there a way to get the model that the line number relates to in lineNumbersFunc?

I've tried using editor.getModel() inside the function but this always returns the initial model, not the one being shown in the inline/peeked view.

--- edit ---

See an example of what I'm trying to do in the playground

It produces this when the code lens is clicked Image showing other file/model being peeked but with the wrong line numbering


Solution

  • I found a way to do this with onDidCreateEditor.

    When that event is fired, I look at the uri of the new model and use an appropriate method to set the different line number.

    Like this:

    const customLineNumbersAlpha = (num) => {
        const map = [ '', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
        return (num < map.length) ? map[num] : ' ';
    }
    
    const customLineNumbersFrom10 = (num) => {
        const map = [ '', '10', '11', '12', '13', '14', '15', '16'];
        return (num < map.length) ? map[num] : ' ';
    }
    
    
    monaco.editor.onDidCreateEditor(newEditor => {
        newEditor.onDidChangeModel(e => {
    
            if (e.newModelUrl == model1.uri)
            {
                    newEditor.updateOptions({ lineNumbers: customLineNumbersAlpha });
            }
            else if (e.newModelUrl == model2.uri)
            {
                    newEditor.updateOptions({ lineNumbers: customLineNumbersFrom10 });
            }
        });
    });
    

    See it working in the playground

    which enables output like this:

    partial screenshot showing the peeked file using different line numbers