show-hint.js 14 KB

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