complete.html 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>CodeMirror 2: Autocomplete Demo</title>
  5. <link rel="stylesheet" href="../lib/codemirror.css">
  6. <script src="../lib/codemirror.js"></script>
  7. <link rel="stylesheet" href="../theme/night.css">
  8. <script src="../mode/javascript/javascript.js"></script>
  9. <link rel="stylesheet" href="../css/docs.css">
  10. <style type="text/css">
  11. .completions {
  12. position: absolute;
  13. z-index: 10;
  14. overflow: hidden;
  15. -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
  16. -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
  17. box-shadow: 2px 3px 5px rgba(0,0,0,.2);
  18. }
  19. .completions select {
  20. background: #fafafa;
  21. outline: none;
  22. border: none;
  23. padding: 0;
  24. margin: 0;
  25. font-family: monospace;
  26. }
  27. .CodeMirror {
  28. border: 1px solid #eee;
  29. }
  30. </style>
  31. </head>
  32. <body>
  33. <h1>CodeMirror 2: Autocomplete demo</h1>
  34. <form><textarea id="code" name="code">
  35. function getCompletions(token, context) {
  36. var found = [], start = token.string;
  37. function maybeAdd(str) {
  38. if (str.indexOf(start) == 0) found.push(str);
  39. }
  40. function gatherCompletions(obj) {
  41. if (typeof obj == "string") forEach(stringProps, maybeAdd);
  42. else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
  43. else if (obj instanceof Function) forEach(funcProps, maybeAdd);
  44. for (var name in obj) maybeAdd(name);
  45. }
  46. if (context) {
  47. // If this is a property, see if it belongs to some object we can
  48. // find in the current environment.
  49. var obj = context.pop(), base;
  50. if (obj.className == "js-variable")
  51. base = window[obj.string];
  52. else if (obj.className == "js-string")
  53. base = "";
  54. else if (obj.className == "js-atom")
  55. base = 1;
  56. while (base != null && context.length)
  57. base = base[context.pop().string];
  58. if (base != null) gatherCompletions(base);
  59. }
  60. else {
  61. // If not, just look in the window object and any local scope
  62. // (reading into JS mode internals to get at the local variables)
  63. for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
  64. gatherCompletions(window);
  65. forEach(keywords, maybeAdd);
  66. }
  67. return found;
  68. }
  69. </textarea></form>
  70. <p>Press <strong>ctrl-space</strong> to activate autocompletion. See
  71. the <a href="complete.js">code</a> to figure out how it works.</p>
  72. <script src="complete.js"></script>
  73. </body>
  74. </html>