changemode.html 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <!doctype html>
  2. <title>CodeMirror: Mode-Changing Demo</title>
  3. <meta charset="utf-8"/>
  4. <link rel=stylesheet href="../doc/docs.css">
  5. <link rel="stylesheet" href="../lib/codemirror.css">
  6. <script src="../lib/codemirror.js"></script>
  7. <script src="../mode/javascript/javascript.js"></script>
  8. <script src="../mode/scheme/scheme.js"></script>
  9. <style>
  10. .CodeMirror {border: 1px solid black;}
  11. </style>
  12. <div id=nav>
  13. <a href="https://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../doc/logo.png"></a>
  14. <ul>
  15. <li><a href="../index.html">Home</a>
  16. <li><a href="../doc/manual.html">Manual</a>
  17. <li><a href="https://github.com/codemirror/codemirror">Code</a>
  18. </ul>
  19. <ul>
  20. <li><a class=active href="#">Mode-Changing</a>
  21. </ul>
  22. </div>
  23. <article>
  24. <h2>Mode-Changing Demo</h2>
  25. <form><textarea id="code" name="code">
  26. ;; If there is Scheme code in here, the editor will be in Scheme mode.
  27. ;; If you put in JS instead, it'll switch to JS mode.
  28. (define (double x)
  29. (* x x))
  30. </textarea></form>
  31. <p>On changes to the content of the above editor, a (crude) script
  32. tries to auto-detect the language used, and switches the editor to
  33. either JavaScript or Scheme mode based on that.</p>
  34. <script>
  35. var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  36. mode: "scheme",
  37. lineNumbers: true
  38. });
  39. var pending;
  40. editor.on("change", function() {
  41. clearTimeout(pending);
  42. pending = setTimeout(update, 400);
  43. });
  44. function looksLikeScheme(code) {
  45. return !/^\s*\(\s*function\b/.test(code) && /^\s*[;\(]/.test(code);
  46. }
  47. function update() {
  48. editor.setOption("mode", looksLikeScheme(editor.getValue()) ? "scheme" : "javascript");
  49. }
  50. </script>
  51. </article>