setValue之后的Codemirror自动格式

时间:2014-08-03 22:41:55

标签: javascript jquery codemirror

http://liveweave.com/UxEJ0s

我正在为我的应用程序使用Codemirror。

我注意到如果我选择所有文本并按SHIFT + Tab键,它会自动对齐我的代码,使其更容易阅读。

以下是我的应用目前呈现的示例...

<ul>
<li>
<font color="#f90000">
  Apples
</font>
</li>
<li>
<font color="#ff9a3d">
  Oranges
</font>
</li>
</ul>

这是我试图让它渲染的内容。

<ul>
  <li>
    <font color="#f90000">
      Apples
    </font>
  </li>
  <li>
    <font color="#ff9a3d">
      Oranges
    </font>
  </li>
</ul>

编辑

有没有人知道如果没有在Codemirror中手动选择整个代码,是否有办法做到这一点?

为什么呢?我在我的应用程序后台运行了Codemirror,所有添加的代码都是动态添加的,但是当我保存最终代码时,它看起来就像上面那样。

非常感谢任何帮助。

5 个答案:

答案 0 :(得分:13)

从codemirror中删除

autoFormatRange ,因此我们应该使用其他方式,注册我们自己的扩展程序:

<强> 1。生成js

转到js生成器(只是通过插件和自定义扩展获得缩小的js的简单方法)。 <击> http://codemirror.net/doc/compress.html

版本3的更新链接:http://codemirror.net/3/doc/compress.html

<强> 2。选择所需的选项

粘贴自定义扩展程序代码并按&#34; 压缩&#34;按钮。

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;
    function newline() {
        out += "\n";
        atSol = true;
        ++lines;
    }

    for (var i = 0; i < text.length; ++i) {
        var stream = new CodeMirror.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 range
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");
        }
    });
});

第3。使用生成的.js如下

HTML:

<textarea id=code><?=$value?></textarea>

<link rel="stylesheet" href="/codemirror/codemirror.css">
<script src="/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>

找到代码here

答案 1 :(得分:7)

自Codemirror删除对autoFormatRange()的支持以来,使用它来格式化文本并不值得。我改为使用js-beautify

var beautify_js = require('js-beautify').js_beautify
var beautify_html = require('js-beautify').html

var formattedJSON = beautify_js(jsonText, { indent_size: 2 });
var formattedXML = beautify_html(xmlText, { indent_size: 2 });

答案 2 :(得分:4)

您可以使用以下代码来实现您的目标:

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

将此功能与您的事件绑定,它将自动格式化代码。

答案 3 :(得分:2)

通过使用codemirror格式化插件,您可以实现您的要求

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);
      }

来源链接

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

答案 4 :(得分:1)

这是原始的插件,包括一个小的更新,让它可以与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 == ")") return false;
        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 range
            var 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;
    function newline() {
      out += "\n";
      atSol = true;
      ++lines;
    }

    for (var i = 0; i < text.length; ++i) {
      var stream = new CodeMirror.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));
    });
});