codeMirror實現Json編輯器的代碼格式化

1、首先安裝codeMirror的依賴js和css,順便引入jQuery包。javascript

    <link rel="stylesheet" href="codemirror-5.31.0/lib/codemirror.css">
    <script src="jquery.1.11.min.js"></script>
    <script src="codemirror-5.31.0/lib/codemirror.js"></script>

2、因爲json屬於JavaScript的一種,因此也得引入JavaScript。css

 <script src="codemirror-5.31.0/mode/javascript/javascript.js"></script>

3、安裝一些須要的樣式,好比我引入的以下樣式,其實能夠本身選擇引入,也能夠不引入。html

<!--引入js,綁定Vim-->
<script src="codemirror-5.31.0/keymap/vim.js"></script>
<!--引入css文件,用以支持主題-->
<link rel="stylesheet" href="codemirror-5.31.0/theme/eclipse.css">

4、body代碼,編輯器就是textarea,可自定義樣式,在head中引入便可。java

<body>
<textarea id="code"></textarea>
</body>

5、最重要的就在頭部引用如下代碼,表示json格式化。jquery

<!--格式化-->
 <script src="codemirror-5.31.0/lib/formatting.js"></script>

 我是將自定義的格式化代碼存到了codeMirror的lib下新建了一個formatting.js,如下是我新建的js的源碼。json

(function() {

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

  CodeMirror.extendMode("javascript", {
    commentStart: "/*",
    commentEnd: "*/",
    // FIXME semicolons inside of for
    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);
    }
  });

  // Comment/uncomment the specified range
  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);
      }
    });
  });

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

  // Applies automatic formatting to the specified range
  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));
    });
  });
})();

6、使用方法vim

使用方式是在html頁面中的JavaScript中寫入如下代碼:app

<script type="text/javascript">
    var editor=CodeMirror.fromTextArea(document.getElementById("code"),{
    //Js高亮顯示
        mode:"application/json",
         //設置主題
        theme:"eclipse",
        //快捷鍵
        extraKeys:{
             "F7": function autoFormat(editor) {
                var totalLines = editor.lineCount();
                      editor.autoFormatRange({line:0, ch:0}, {line:totalLines});
            }//代碼格式化
        },
     });
</script>

  運行項目,寫入json格式代碼,點擊F7就可實現對代碼的格式化eclipse

相關文章
相關標籤/搜索