Skip to content Skip to sidebar Skip to footer

Codemirror Auto Format After Setvalue

http://liveweave.com/UxEJ0s I'm using Codemirror for my app. I noticed if I select all the text and press SHIFT+Tab it will auto align my code making it easier to read. Here's an

Solution 1:

autoFormatRangewas removed from codemirror, so we should use another way, register our own extension:

1. generate js

Go to js generator (just an easy way to get minified js with plugins and custom extensions). http://codemirror.net/doc/compress.html

Updated link for version 3: http://codemirror.net/3/doc/compress.html

2. Select options desired

Paste custom extension code and press "Compress" button.

CodeMirror.defineExtension("autoFormatRange", function (from, to) {
    var cm = this;
    var outer = cm.getMode(), text = cm.getRange(from, to).split("\n");
    var state = CodeMirror.copyState(outer, cm.getTokenAt(from).state);
    var tabSize = cm.getOption("tabSize");

    var out = "", lines = 0, atSol = from.ch == 0;
    functionnewline() {
        out += "\n";
        atSol = true;
        ++lines;
    }

    for (var i = 0; i < text.length; ++i) {
        var stream = newCodeMirror.StringStream(text[i], tabSize);
        while (!stream.eol()) {
            var inner = CodeMirror.innerMode(outer, state);
            var style = outer.token(stream, state), cur = stream.current();
            stream.start = stream.pos;
            if (!atSol || /\S/.test(cur)) {
                out += cur;
                atSol = false;
            }
            if (!atSol && inner.mode.newlineAfterToken &&
                inner.mode.newlineAfterToken(style, cur, stream.string.slice(stream.pos) || text[i+1] || "", inner.state))
                newline();
        }
        if (!stream.pos && outer.blankLine) outer.blankLine(state);
        if (!atSol) newline();
    }

    cm.operation(function () {
        cm.replaceRange(out, from, to);
        for (var cur = from.line + 1, end = from.line + lines; cur <= end; ++cur)
            cm.indentLine(cur, "smart");
    });
});

// Applies automatic mode-aware indentation to the specified rangeCodeMirror.defineExtension("autoIndentRange", function (from, to) {
    var cmInstance = this;
    this.operation(function () {
        for (var i = from.line; i <= to.line; i++) {
            cmInstance.indentLine(i, "smart");
        }
    });
});

3. Use generated .js as follows

Html:

<textareaid=code><?=$value?></textarea><linkhref="/codemirror/codemirror.css"><scriptsrc="/codemirror/codemirror-compressed.js"></script><script>var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
    lineNumbers: true,
    mode: "text/html"
});
var totalLines = editor.lineCount();  
editor.autoFormatRange({line:0, ch:0}, {line:totalLines});
</script>

Code was found here

Solution 2:

Ever since Codemirror has removed support for autoFormatRange() it's not worth the trouble to use it for formatting text. I use js-beautify instead.

var beautify_js = require('js-beautify').js_beautifyvar beautify_html = require('js-beautify').htmlvar formattedJSON = beautify_js(jsonText, { indent_size: 2 });
var formattedXML = beautify_html(xmlText, { indent_size: 2 });

Solution 3:

You can use the following code to achieve what you want :

function format() {
    var totalLines = editor.lineCount();  
    editor.autoFormatRange({line:0, ch:0}, {line:totalLines});
}

Bind this function with your events, and it will auto-format the code.

Solution 4:

By using codemirror formatting add-on you can achieve your requirement

JSFiddle Demo

var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
        lineNumbers: true,
        mode: "htmlmixed",
        extraKeys:{"Shift-Tab":autoFormatSelection}
      });


      function getSelectedRange() {
        return { from: editor.getCursor(true), to: editor.getCursor(false) };
      }

      function autoFormatSelection() {
        var range = getSelectedRange();
        editor.autoFormatRange(range.from, range.to);
      }

Source Link

http://codemirror.net/2/demo/formatting.html

Solution 5:

Here is the original addon including a small update to let it work with CodeMirror V3 :

CodeMirror.extendMode("css", {
    commentStart: "/*",
    commentEnd: "*/",
    newlineAfterToken: function(type, content) {
        return/^[;{}]$/.test(content);
    }
});

CodeMirror.extendMode("javascript", {
    commentStart: "/*",
    commentEnd: "*/",    
    newlineAfterToken: function(type, content, textAfter, state) {
        if (this.jsonMode) {
            return/^[\[,{]$/.test(content) || /^}/.test(textAfter);
        } else {
            if (content == ";" && state.lexical && state.lexical.type == ")") returnfalse;
        return/^[;{}]$/.test(content) && !/^;/.test(textAfter);
        }
    }
});

CodeMirror.extendMode("xml", {
    commentStart: "<!--",
    commentEnd: "-->",
    newlineAfterToken: function(type, content, textAfter) {    
        return ( type == "tag" && />$/.test(content) || /^</.test(textAfter) ) || (  type == "tag bracket" && />$/.test(content) );
    }
});


CodeMirror.defineExtension("commentRange", function (isComment, from, to) {
    var cm = this, curMode = CodeMirror.innerMode(cm.getMode(), cm.getTokenAt(from).state).mode;
    cm.operation(function() {
        if (isComment) { // Comment range
            cm.replaceRange(curMode.commentEnd, to);
            cm.replaceRange(curMode.commentStart, from);
        if (from.line == to.line && from.ch == to.ch) // An empty comment inserted - put cursor inside
            cm.setCursor(from.line, from.ch + curMode.commentStart.length);
        } else { // Uncomment rangevar selText = cm.getRange(from, to);
            var startIndex = selText.indexOf(curMode.commentStart);
            var endIndex = selText.lastIndexOf(curMode.commentEnd);
            if (startIndex > -1 && endIndex > -1 && endIndex > startIndex) {
                // Take string till comment start
                selText = selText.substr(0, startIndex)
                // From comment start till comment end
                + selText.substring(startIndex + curMode.commentStart.length, endIndex)
                // From comment end till string end
                + selText.substr(endIndex + curMode.commentEnd.length);
            }
            cm.replaceRange(selText, from, to);
        }
    });
});


CodeMirror.defineExtension("autoIndentRange", function (from, to) {
    var cmInstance = this;
    this.operation(function () {
        for (var i = from.line; i <= to.line; i++) {
            cmInstance.indentLine(i, "smart");
        }
    });
});


CodeMirror.defineExtension("autoFormatRange", function (from, to) {
    var cm = this;
    var outer = cm.getMode(), text = cm.getRange(from, to).split("\n");        
    var state = CodeMirror.copyState(outer, cm.getTokenAt(from).state);
    var tabSize = cm.getOption("tabSize");

    var out = "", lines = 0, atSol = from.ch == 0;
    functionnewline() {
      out += "\n";
      atSol = true;
      ++lines;
    }

    for (var i = 0; i < text.length; ++i) {
      var stream = newCodeMirror.StringStream(text[i], tabSize);      
      while (!stream.eol()) {
        var inner = CodeMirror.innerMode(outer, state);   
        var style = outer.token(stream, state), cur = stream.current();
        stream.start = stream.pos;
        if (!atSol || /\S/.test(cur)) {
          out += cur;
          atSol = false;
        }

        if (!atSol && inner.mode.newlineAfterToken &&
            inner.mode.newlineAfterToken(style, cur, stream.string.slice(stream.pos) || text[i+1] || "", inner.state))
          newline();        
      }
      if (!stream.pos && outer.blankLine) outer.blankLine(state);
      if (!atSol)newline();
    }

    cm.operation(function () {
      cm.replaceRange(out, from, to);
      for (var cur = from.line + 1, end = from.line + lines; cur <= end; ++cur)
        cm.indentLine(cur, "smart");
      cm.setSelection(from, cm.getCursor(false));
    });
});

Post a Comment for "Codemirror Auto Format After Setvalue"