Search code examples
codemirror

codemirror 3.0 format preloaded textarea code


I am using CodeMirror to create an editor in an HTML5 based presentation. In it's simplest form, the html looks something like this.

 <section class="pattern">
      <textarea id='pattern-view' class='codemirror' data-mode='javascript'>
           var myModule = function(){
              //code goes here
           }
      </textarea>
 </section>

and down in a document ready I have the code

 $(function(){
     var tAreas = document.querySelectorAll('.codemirror');
        for (var i = 0; i < tAreas.length; i++) {
           CodeMirror.fromTextArea(tAreas[i], { theme: 'monokai',  mode: tAreas[i].dataset.mode });
        }
 });

This works as expected, the textarea is replaced with the editor. The trouble is the indentation is maintained and not properly formatted. It only highlights the code, does not re-format the contents.

Is there something I need to add to this? I did find code for formatting.js addon, which is no longer part of codemirror 3.0.

Is there someway to auto-format the code inside the textarea?


Solution

  • Answering my own question. For those who might chance upon this. Get the formatting.js from the old codemirror and put it where you like. Add this to your dom ready function

     var tAreas = document.querySelectorAll('.codemirror'); //assuming all textareas have the class codemirror
    
            for (var i = 0; i < tAreas.length; i++) {
                var editor = CodeMirror.fromTextArea(tAreas[i], {theme: 'monokai',mode: tAreas[i].dataset.mode, tabMode: 'indent' });
                CodeMirror.commands["selectAll"](editor);
                autoFormatSelection(editor);
                $(tAreas[i]).trigger({type: 'keypress', which: 13});
            }
    
            function getSelectedRange(editor) {
                return { from: editor.getCursor(true), to: editor.getCursor(false) };
            }
    
            function autoFormatSelection(editor) {
                var range = getSelectedRange(editor);
                editor.autoFormatRange(range.from, range.to);
                CodeMirror.commands['goPageUp'](editor);
    
            }