Search code examples
javascripteditormonaco-editor

How to add, remove and change glyphs in Monaco Editor


I am able to add glyph to the editor but I am not able to remove and edit the glyph. Can you please give me the right way of doing it.

<h2>Monaco Editor Sample</h2>
<div id="container" style="width:80%;height:600px;border:1px solid grey"></div>

<!-- OR ANY OTHER AMD LOADER HERE INSTEAD OF loader.js -->
<script src="../node_modules/monaco-editor/min/vs/loader.js"></script>
<script>
    var editor,decorations;
    require.config({ paths: { 'vs': '../node_modules/monaco-editor/min/vs' }});
    require(['vs/editor/editor.main'], function() {
         editor = monaco.editor.create(document.getElementById('container'), {
            value: [
                'function x() {',
                '\tconsole.log("Hello world!");',
                '}',
            ].join('\n'),
            language: 'javascript',
            theme: "myCustomTheme",
            automaticLayout: true,
            readOnly: false,
            mouseWheelZoom:true,
            glyphMargin:true,
            fontSize:'20px'
        });
   //below is the glyph I am calling
    var decorations = editor.deltaDecorations([], [     
    {
        range: new monaco.Range(3,1,3,1),
        options: {
            isWholeLine: true,
            className: 'myContentClass',
            glyphMarginClassName: 'glyph-error',
        }
    }
    ]);
    });
</script>

I am trying to delete or modify the range and style of the glyph using decorations variable but it is a string object.

This is the how my editor looks with a squared glyph:

enter image description here


Solution

  • The return value of deltaDecorations is an array of strings. Each string is an identifier of a decoration that was created by the last deltaDecorations call.

    To modify an existing decoration you must replace it with a new one as shown below.

    var decorations = editor.deltaDecorations([], [     
        {
            range: new monaco.Range(3,1,3,1),
            options: {
                isWholeLine: true,
                className: 'myContentClass',
                glyphMarginClassName: 'glyph-error',
            }
        }
    ]);
    
    // Now move the previously created decoration to line 2
    var targetId = decorations[0];
    editor.deltaDecorations([targetId], [     
        {
            range: new monaco.Range(2,1,2,1),
            options: {
                isWholeLine: true,
                className: 'myContentClass',
                glyphMarginClassName: 'glyph-error',
            }
        }
    ]);