show-hint.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. (function(mod) {
  4. if (typeof exports == "object" && typeof module == "object") // CommonJS
  5. mod(require("../../lib/codemirror"));
  6. else if (typeof define == "function" && define.amd) // AMD
  7. define(["../../lib/codemirror"], mod);
  8. else // Plain browser env
  9. mod(CodeMirror);
  10. })(function(CodeMirror) {
  11. "use strict";
  12. var HINT_ELEMENT_CLASS = "CodeMirror-hint";
  13. var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active";
  14. // This is the old interface, kept around for now to stay
  15. // backwards-compatible.
  16. CodeMirror.showHint = function(cm, getHints, options) {
  17. if (!getHints) return cm.showHint(options);
  18. if (options && options.async) getHints.async = true;
  19. var newOpts = {hint: getHints};
  20. if (options) for (var prop in options) newOpts[prop] = options[prop];
  21. return cm.showHint(newOpts);
  22. };
  23. CodeMirror.defineExtension("showHint", function(options) {
  24. // We want a single cursor position.
  25. if (this.listSelections().length > 1 || this.somethingSelected()) return;
  26. if (this.state.completionActive) this.state.completionActive.close();
  27. var completion = this.state.completionActive = new Completion(this, options);
  28. if (!completion.options.hint) return;
  29. CodeMirror.signal(this, "startCompletion", this);
  30. completion.update(true);
  31. });
  32. function Completion(cm, options) {
  33. this.cm = cm;
  34. this.options = this.buildOptions(options);
  35. this.widget = null;
  36. this.debounce = 0;
  37. this.tick = 0;
  38. this.startPos = this.cm.getCursor();
  39. this.startLen = this.cm.getLine(this.startPos.line).length;
  40. var self = this;
  41. cm.on("cursorActivity", this.activityFunc = function() { self.cursorActivity(); });
  42. }
  43. var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
  44. return setTimeout(fn, 1000/60);
  45. };
  46. var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
  47. Completion.prototype = {
  48. close: function() {
  49. if (!this.active()) return;
  50. this.cm.state.completionActive = null;
  51. this.tick = null;
  52. this.cm.off("cursorActivity", this.activityFunc);
  53. if (this.widget && this.data) CodeMirror.signal(this.data, "close");
  54. if (this.widget) this.widget.close();
  55. CodeMirror.signal(this.cm, "endCompletion", this.cm);
  56. },
  57. active: function() {
  58. return this.cm.state.completionActive == this;
  59. },
  60. pick: function(data, i) {
  61. var completion = data.list[i];
  62. if (completion.hint) completion.hint(this.cm, data, completion);
  63. else this.cm.replaceRange(getText(completion), completion.from || data.from,
  64. completion.to || data.to, "complete");
  65. CodeMirror.signal(data, "pick", completion);
  66. this.close();
  67. },
  68. cursorActivity: function() {
  69. if (this.debounce) {
  70. cancelAnimationFrame(this.debounce);
  71. this.debounce = 0;
  72. }
  73. var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line);
  74. if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch ||
  75. pos.ch < this.startPos.ch || this.cm.somethingSelected() ||
  76. (pos.ch && this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) {
  77. this.close();
  78. } else {
  79. var self = this;
  80. this.debounce = requestAnimationFrame(function() {self.update();});
  81. if (this.widget) this.widget.disable();
  82. }
  83. },
  84. update: function(first) {
  85. if (this.tick == null) return;
  86. if (this.data) CodeMirror.signal(this.data, "update");
  87. if (!this.options.hint.async) {
  88. this.finishUpdate(this.options.hint(this.cm, this.options), first);
  89. } else {
  90. var myTick = ++this.tick, self = this;
  91. this.options.hint(this.cm, function(data) {
  92. if (self.tick == myTick) self.finishUpdate(data, first);
  93. }, this.options);
  94. }
  95. },
  96. finishUpdate: function(data, first) {
  97. this.data = data;
  98. var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle);
  99. if (this.widget) this.widget.close();
  100. if (data && data.list.length) {
  101. if (picked && data.list.length == 1) {
  102. this.pick(data, 0);
  103. } else {
  104. this.widget = new Widget(this, data);
  105. CodeMirror.signal(data, "shown");
  106. }
  107. }
  108. },
  109. buildOptions: function(options) {
  110. var editor = this.cm.options.hintOptions;
  111. var out = {};
  112. for (var prop in defaultOptions) out[prop] = defaultOptions[prop];
  113. if (editor) for (var prop in editor)
  114. if (editor[prop] !== undefined) out[prop] = editor[prop];
  115. if (options) for (var prop in options)
  116. if (options[prop] !== undefined) out[prop] = options[prop];
  117. return out;
  118. }
  119. };
  120. function getText(completion) {
  121. if (typeof completion == "string") return completion;
  122. else return completion.text;
  123. }
  124. function buildKeyMap(completion, handle) {
  125. var baseMap = {
  126. Up: function() {handle.moveFocus(-1);},
  127. Down: function() {handle.moveFocus(1);},
  128. PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
  129. PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
  130. Home: function() {handle.setFocus(0);},
  131. End: function() {handle.setFocus(handle.length - 1);},
  132. Enter: handle.pick,
  133. Tab: handle.pick,
  134. Esc: handle.close
  135. };
  136. var custom = completion.options.customKeys;
  137. var ourMap = custom ? {} : baseMap;
  138. function addBinding(key, val) {
  139. var bound;
  140. if (typeof val != "string")
  141. bound = function(cm) { return val(cm, handle); };
  142. // This mechanism is deprecated
  143. else if (baseMap.hasOwnProperty(val))
  144. bound = baseMap[val];
  145. else
  146. bound = val;
  147. ourMap[key] = bound;
  148. }
  149. if (custom)
  150. for (var key in custom) if (custom.hasOwnProperty(key))
  151. addBinding(key, custom[key]);
  152. var extra = completion.options.extraKeys;
  153. if (extra)
  154. for (var key in extra) if (extra.hasOwnProperty(key))
  155. addBinding(key, extra[key]);
  156. return ourMap;
  157. }
  158. function getHintElement(hintsElement, el) {
  159. while (el && el != hintsElement) {
  160. if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el;
  161. el = el.parentNode;
  162. }
  163. }
  164. function Widget(completion, data) {
  165. this.completion = completion;
  166. this.data = data;
  167. this.picked = false;
  168. var widget = this, cm = completion.cm;
  169. var hints = this.hints = document.createElement("ul");
  170. hints.className = "CodeMirror-hints";
  171. this.selectedHint = data.selectedHint || 0;
  172. var completions = data.list;
  173. for (var i = 0; i < completions.length; ++i) {
  174. var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
  175. var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
  176. if (cur.className != null) className = cur.className + " " + className;
  177. elt.className = className;
  178. if (cur.render) cur.render(elt, data, cur);
  179. else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
  180. elt.hintId = i;
  181. }
  182. var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);
  183. var left = pos.left, top = pos.bottom, below = true;
  184. hints.style.left = left + "px";
  185. hints.style.top = top + "px";
  186. // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
  187. var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
  188. var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
  189. (completion.options.container || document.body).appendChild(hints);
  190. var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
  191. if (overlapY > 0) {
  192. var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
  193. if (curTop - height > 0) { // Fits above cursor
  194. hints.style.top = (top = pos.top - height) + "px";
  195. below = false;
  196. } else if (height > winH) {
  197. hints.style.height = (winH - 5) + "px";
  198. hints.style.top = (top = pos.bottom - box.top) + "px";
  199. var cursor = cm.getCursor();
  200. if (data.from.ch != cursor.ch) {
  201. pos = cm.cursorCoords(cursor);
  202. hints.style.left = (left = pos.left) + "px";
  203. box = hints.getBoundingClientRect();
  204. }
  205. }
  206. }
  207. var overlapX = box.right - winW;
  208. if (overlapX > 0) {
  209. if (box.right - box.left > winW) {
  210. hints.style.width = (winW - 5) + "px";
  211. overlapX -= (box.right - box.left) - winW;
  212. }
  213. hints.style.left = (left = pos.left - overlapX) + "px";
  214. }
  215. cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
  216. moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
  217. setFocus: function(n) { widget.changeActive(n); },
  218. menuSize: function() { return widget.screenAmount(); },
  219. length: completions.length,
  220. close: function() { completion.close(); },
  221. pick: function() { widget.pick(); },
  222. data: data
  223. }));
  224. if (completion.options.closeOnUnfocus) {
  225. var closingOnBlur;
  226. cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
  227. cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
  228. }
  229. var startScroll = cm.getScrollInfo();
  230. cm.on("scroll", this.onScroll = function() {
  231. var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
  232. var newTop = top + startScroll.top - curScroll.top;
  233. var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
  234. if (!below) point += hints.offsetHeight;
  235. if (point <= editor.top || point >= editor.bottom) return completion.close();
  236. hints.style.top = newTop + "px";
  237. hints.style.left = (left + startScroll.left - curScroll.left) + "px";
  238. });
  239. CodeMirror.on(hints, "dblclick", function(e) {
  240. var t = getHintElement(hints, e.target || e.srcElement);
  241. if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
  242. });
  243. CodeMirror.on(hints, "click", function(e) {
  244. var t = getHintElement(hints, e.target || e.srcElement);
  245. if (t && t.hintId != null) {
  246. widget.changeActive(t.hintId);
  247. if (completion.options.completeOnSingleClick) widget.pick();
  248. }
  249. });
  250. CodeMirror.on(hints, "mousedown", function() {
  251. setTimeout(function(){cm.focus();}, 20);
  252. });
  253. CodeMirror.signal(data, "select", completions[0], hints.firstChild);
  254. return true;
  255. }
  256. Widget.prototype = {
  257. close: function() {
  258. if (this.completion.widget != this) return;
  259. this.completion.widget = null;
  260. this.hints.parentNode.removeChild(this.hints);
  261. this.completion.cm.removeKeyMap(this.keyMap);
  262. var cm = this.completion.cm;
  263. if (this.completion.options.closeOnUnfocus) {
  264. cm.off("blur", this.onBlur);
  265. cm.off("focus", this.onFocus);
  266. }
  267. cm.off("scroll", this.onScroll);
  268. },
  269. disable: function() {
  270. this.completion.cm.removeKeyMap(this.keyMap);
  271. var widget = this;
  272. this.keyMap = {Enter: function() { widget.picked = true; }};
  273. this.completion.cm.addKeyMap(this.keyMap);
  274. },
  275. pick: function() {
  276. this.completion.pick(this.data, this.selectedHint);
  277. },
  278. changeActive: function(i, avoidWrap) {
  279. if (i >= this.data.list.length)
  280. i = avoidWrap ? this.data.list.length - 1 : 0;
  281. else if (i < 0)
  282. i = avoidWrap ? 0 : this.data.list.length - 1;
  283. if (this.selectedHint == i) return;
  284. var node = this.hints.childNodes[this.selectedHint];
  285. node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
  286. node = this.hints.childNodes[this.selectedHint = i];
  287. node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
  288. if (node.offsetTop < this.hints.scrollTop)
  289. this.hints.scrollTop = node.offsetTop - 3;
  290. else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
  291. this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
  292. CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
  293. },
  294. screenAmount: function() {
  295. return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
  296. }
  297. };
  298. CodeMirror.registerHelper("hint", "auto", function(cm, options) {
  299. var helpers = cm.getHelpers(cm.getCursor(), "hint"), words;
  300. if (helpers.length) {
  301. for (var i = 0; i < helpers.length; i++) {
  302. var cur = helpers[i](cm, options);
  303. if (cur && cur.list.length) return cur;
  304. }
  305. } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
  306. if (words) return CodeMirror.hint.fromList(cm, {words: words});
  307. } else if (CodeMirror.hint.anyword) {
  308. return CodeMirror.hint.anyword(cm, options);
  309. }
  310. });
  311. CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
  312. var cur = cm.getCursor(), token = cm.getTokenAt(cur);
  313. var found = [];
  314. for (var i = 0; i < options.words.length; i++) {
  315. var word = options.words[i];
  316. if (word.slice(0, token.string.length) == token.string)
  317. found.push(word);
  318. }
  319. if (found.length) return {
  320. list: found,
  321. from: CodeMirror.Pos(cur.line, token.start),
  322. to: CodeMirror.Pos(cur.line, token.end)
  323. };
  324. });
  325. CodeMirror.commands.autocomplete = CodeMirror.showHint;
  326. var defaultOptions = {
  327. hint: CodeMirror.hint.auto,
  328. completeSingle: true,
  329. alignWithWord: true,
  330. closeCharacters: /[\s()\[\]{};:>,]/,
  331. closeOnUnfocus: true,
  332. completeOnSingleClick: false,
  333. container: null,
  334. customKeys: null,
  335. extraKeys: null
  336. };
  337. CodeMirror.defineOption("hintOptions", null);
  338. });