Codemirror Auto Format after setValue - Javascript CodeMirror

Javascript examples for CodeMirror:Configuration

Description

Codemirror Auto Format after setValue

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <link rel="stylesheet" type="text/css" href="https://codemirror.net/2/lib/codemirror.css"> 
      <script type="text/javascript" src="https://codemirror.net/2/lib/codemirror.js"></script> 
      <script type="text/javascript" src="https://codemirror.net/2/lib/util/formatting.js"></script> 
      <script type="text/javascript" src="https://codemirror.net/2/mode/css/css.js"></script> 
      <script type="text/javascript" src="https://codemirror.net/2/mode/xml/xml.js"></script> 
      <script type="text/javascript" src="https://codemirror.net/2/mode/htmlmixed/htmlmixed.js"></script> 
      <script type="text/javascript" src="https://codemirror.net/2/mode/javascript/javascript.js"></script> 
      <link rel="stylesheet" type="text/css" href="https://codemirror.net/2/doc/docs.css"> 
      <style id="compiled-css" type="text/css">

.CodeMirror {/* w  ww. j a v  a 2s.  com*/
   border: 1px solid #eee;
}
td {
   padding-right: 20px;
}


      </style> 
   </head> 
   <body> 
      <input type="button" onclick="autoFormatSelection()" value="autoFormatSelection"> 
      <input type="button" onclick="commentSelection(true)" value="commentSelection"> 
      <form>
         <textarea id="code" name="code">
&lt;script&gt; function (s,e){ for(var i=0; i &lt; 1; i++) test("test();a=1");} &lt;/script&gt;
&lt;script&gt;
function test(c){  for (var i = 0; i &lt; 10; i++){             process("a.b();c = null;", 300);}
}
&lt;/script&gt;
&lt;table&gt;&lt;tr&gt;&lt;td&gt;test 1&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;test 2&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;script&gt; function test() { return 1;} &lt;/script&gt;
&lt;style&gt; .test { font-size: medium; font-family: monospace; }
&lt;/style&gt;</textarea>
      </form> 
      <script type="text/javascript">
  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);
      }
      function commentSelection(isComment) {
        var range = getSelectedRange();
        editor.commentRange(isComment, range.from, range.to);
      }

      </script>  
   </body>
</html>

Related Tutorials