complete.html 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>CodeMirror: Autocomplete Demo</title>
  6. <link rel="stylesheet" href="../lib/codemirror.css">
  7. <script src="../lib/codemirror.js"></script>
  8. <script src="../addon/hint/show-hint.js"></script>
  9. <link rel="stylesheet" href="../addon/hint/show-hint.css">
  10. <script src="../addon/hint/javascript-hint.js"></script>
  11. <script src="../mode/javascript/javascript.js"></script>
  12. <link rel="stylesheet" href="../doc/docs.css">
  13. </head>
  14. <body>
  15. <h1>CodeMirror: Autocomplete demo</h1>
  16. <form><textarea id="code" name="code">
  17. function getCompletions(token, context) {
  18. var found = [], start = token.string;
  19. function maybeAdd(str) {
  20. if (str.indexOf(start) == 0) found.push(str);
  21. }
  22. function gatherCompletions(obj) {
  23. if (typeof obj == "string") forEach(stringProps, maybeAdd);
  24. else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
  25. else if (obj instanceof Function) forEach(funcProps, maybeAdd);
  26. for (var name in obj) maybeAdd(name);
  27. }
  28. if (context) {
  29. // If this is a property, see if it belongs to some object we can
  30. // find in the current environment.
  31. var obj = context.pop(), base;
  32. if (obj.className == "js-variable")
  33. base = window[obj.string];
  34. else if (obj.className == "js-string")
  35. base = "";
  36. else if (obj.className == "js-atom")
  37. base = 1;
  38. while (base != null && context.length)
  39. base = base[context.pop().string];
  40. if (base != null) gatherCompletions(base);
  41. }
  42. else {
  43. // If not, just look in the window object and any local scope
  44. // (reading into JS mode internals to get at the local variables)
  45. for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
  46. gatherCompletions(window);
  47. forEach(keywords, maybeAdd);
  48. }
  49. return found;
  50. }
  51. </textarea></form>
  52. <p>Press <strong>ctrl-space</strong> to activate autocompletion. See
  53. the code (<a href="../addon/hint/show-hint.js">here</a>
  54. and <a href="../addon/hint/javascript-hint.js">here</a>) to figure out
  55. how it works.</p>
  56. <script>
  57. CodeMirror.commands.autocomplete = function(cm) {
  58. CodeMirror.showHint(cm, CodeMirror.javascriptHint);
  59. }
  60. var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  61. lineNumbers: true,
  62. extraKeys: {"Ctrl-Space": "autocomplete"}
  63. });
  64. </script>
  65. </body>
  66. </html>