43

Microsoft recently open sourced their monaco editor (similar to ace/codemirror).

https://github.com/Microsoft/monaco-editor

I've got it up and running in the browser, but still can't figure out how to get the current text of the editor, like if I wanted to save it.

Example:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
</head>
<body>

<div id="container" style="width:800px;height:600px;border:1px solid grey"></div>

<script src="monaco-editor/min/vs/loader.js"></script>
<script>
    require.config({ paths: { 'vs': 'monaco-editor/min/vs' }});
    require(['vs/editor/editor.main'], function() {
        var editor = monaco.editor.create(document.getElementById('container'),                 {
            value: [
                'function x() {',
                '\tconsole.log("Hello world!");',
                '}'
            ].join('\n'),
            language: 'javascript'
        });
    });

    function save() {
       // how do I get the value/code inside the editor?
       var value = "";
       saveValueSomewhere(value);     
    }
</script>
</body>
</html>
Kyle Gobel
  • 5,530
  • 9
  • 45
  • 68

3 Answers3

42
require.config({ paths: { 'vs': 'monaco-editor/min/vs' }});
require(['vs/editor/editor.main'], function() {
    window.editor = monaco.editor.create(document.getElementById('container'),                 {
        value: [
            'function x() {',
            '\tconsole.log("Hello world!");',
            '}'
        ].join('\n'),
        language: 'javascript'
    });
});

function save() {
   // get the value of the data
   var value = window.editor.getValue()
   saveValueSomewhere(value);     
}
Jonathan
  • 544
  • 5
  • 4
22

Both the editor and the model support getting the contents:

So as long as you keep a reference to the editor or model you can query the contents:

var editor = monaco.editor.create(...);
var text = editor.getValue();

Or in case of the model:

var model = monaco.editor.createModel(...);
var text = model.getValue();

If you have a diff-editor you cannot access the text directly on the editor but you can access them on the individual models (i.e. through IStandaloneDiffEditor.getModel()):

var diffEditor = monaco.editor.createDiffEditor(...);
var originalText = diffEditor.getModel().original.getValue();
var modifiedText = diffEditor.getModel().modified.getValue();

Or through the different editors (getModifiedEditor() and getOriginalEditor()):

var originalText = diffEditor.getModifiedEditor().getValue();
var modifiedText = diffEditor.getOriginalEditor().getValue();

Just in case you're interested in a part of the text, the model also supports getValueInRange() which gives you the text in a specified range, delimited by a starting and ending column and linenumber, for example:

var editor = monaco.editor.create(...);
var model = editor.getModel();
var partOfTheText = model.getValueInRange({
  startLineNumber: 1,
  startColumn: 2,

  endLineNumber: 3,
  endColumn: 10,
})
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • I know this is a long shot since the answer is 3 years old, but would you know why I cannot get a reference to editor outside the "require" ? If I assign it to a variable (defined outside the require), then when I try to access it, it is simply undefined. I am using electron btw, and embedding the monaco editor in renderer.js – Frotaur Jan 31 '23 at 14:05
  • @Frotaur I think you should ask a new question because it requires more context. Also I haven't worked with monaco in years. – MSeifert Feb 15 '23 at 15:28
  • No problem, I actually figure out why, it is because the amdloader "require" is evaluated asynchronously, so I was trying to access its reference before it was defined. Thanks for taking the time to answer ! – Frotaur Feb 15 '23 at 22:56
3

for me this window.editor.getValue() didn't work but below code worked.

<div id="container" style="width:950px;height:700px;"></div>
<script src="./monaco-editor/dev/vs/loader.js"></script>
<script>
    require.config({ paths: { 'vs': 'monaco-editor/min/vs' }});
    require(['vs/editor/editor.main'], function() {
        var editor = monaco.editor.create(document.getElementById('container'), {
            value: [
                'print "Hello World!"',
                '# python'
            ].join('\n'),
            language: 'python',
            theme: "vs-dark"
        });

        function saveI() 
        {
            getVal = editor.getValue()
            // get the value of the data
            alert(getVal)
        }
        document.getElementById('container').onclick = saveI;

    });
    // Themes: vs-dark , hc-black
    // language: text/html , javascript
</script>

you can change 'container' to your 'htmlButton' and then save the code by using jQuery ajax in the saveI() function.

cyera
  • 285
  • 2
  • 5