show-hint.js 14 KB

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