show-hint.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. options = parseOptions(this, this.getCursor("start"), options);
  25. var selections = this.listSelections()
  26. if (selections.length > 1) return;
  27. // By default, don't allow completion when something is selected.
  28. // A hint function can have a `supportsSelection` property to
  29. // indicate that it can handle selections.
  30. if (this.somethingSelected()) {
  31. if (!options.hint.supportsSelection) return;
  32. // Don't try with cross-line selections
  33. for (var i = 0; i < selections.length; i++)
  34. if (selections[i].head.line != selections[i].anchor.line) return;
  35. }
  36. if (this.state.completionActive) this.state.completionActive.close();
  37. var completion = this.state.completionActive = new Completion(this, options);
  38. if (!completion.options.hint) return;
  39. CodeMirror.signal(this, "startCompletion", this);
  40. completion.update(true);
  41. });
  42. function Completion(cm, options) {
  43. this.cm = cm;
  44. this.options = options;
  45. this.widget = null;
  46. this.debounce = 0;
  47. this.tick = 0;
  48. this.startPos = this.cm.getCursor("start");
  49. this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length;
  50. var self = this;
  51. cm.on("cursorActivity", this.activityFunc = function() { self.cursorActivity(); });
  52. }
  53. var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
  54. return setTimeout(fn, 1000/60);
  55. };
  56. var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
  57. Completion.prototype = {
  58. close: function() {
  59. if (!this.active()) return;
  60. this.cm.state.completionActive = null;
  61. this.tick = null;
  62. this.cm.off("cursorActivity", this.activityFunc);
  63. if (this.widget && this.data) CodeMirror.signal(this.data, "close");
  64. if (this.widget) this.widget.close();
  65. CodeMirror.signal(this.cm, "endCompletion", this.cm);
  66. },
  67. active: function() {
  68. return this.cm.state.completionActive == this;
  69. },
  70. pick: function(data, i) {
  71. var completion = data.list[i];
  72. if (completion.hint) completion.hint(this.cm, data, completion);
  73. else this.cm.replaceRange(getText(completion), completion.from || data.from,
  74. completion.to || data.to, "complete");
  75. CodeMirror.signal(data, "pick", completion);
  76. this.close();
  77. },
  78. cursorActivity: function() {
  79. if (this.debounce) {
  80. cancelAnimationFrame(this.debounce);
  81. this.debounce = 0;
  82. }
  83. var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line);
  84. if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch ||
  85. pos.ch < this.startPos.ch || this.cm.somethingSelected() ||
  86. (pos.ch && this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) {
  87. this.close();
  88. } else {
  89. var self = this;
  90. this.debounce = requestAnimationFrame(function() {self.update();});
  91. if (this.widget) this.widget.disable();
  92. }
  93. },
  94. update: function(first) {
  95. if (this.tick == null) return
  96. var self = this, myTick = ++this.tick
  97. fetchHints(this.options.hint, this.cm, this.options, function(data) {
  98. if (self.tick == myTick) self.finishUpdate(data, first)
  99. })
  100. },
  101. finishUpdate: function(data, first) {
  102. if (this.data) CodeMirror.signal(this.data, "update");
  103. var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle);
  104. if (this.widget) this.widget.close();
  105. if (data && this.data && isNewCompletion(this.data, data)) return;
  106. this.data = data;
  107. if (data && data.list.length) {
  108. if (picked && data.list.length == 1) {
  109. this.pick(data, 0);
  110. } else {
  111. this.widget = new Widget(this, data);
  112. CodeMirror.signal(data, "shown");
  113. }
  114. }
  115. }
  116. };
  117. function isNewCompletion(old, nw) {
  118. var moved = CodeMirror.cmpPos(nw.from, old.from)
  119. return moved > 0 && old.to.ch - old.from.ch != nw.to.ch - nw.from.ch
  120. }
  121. function parseOptions(cm, pos, options) {
  122. var editor = 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. if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos)
  130. return out;
  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. this.picked = false;
  180. var widget = this, cm = completion.cm;
  181. var hints = this.hints = document.createElement("ul");
  182. hints.className = "CodeMirror-hints";
  183. this.selectedHint = data.selectedHint || 0;
  184. var completions = data.list;
  185. for (var i = 0; i < completions.length; ++i) {
  186. var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
  187. var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
  188. if (cur.className != null) className = cur.className + " " + className;
  189. elt.className = className;
  190. if (cur.render) cur.render(elt, data, cur);
  191. else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
  192. elt.hintId = i;
  193. }
  194. var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);
  195. var left = pos.left, top = pos.bottom, below = true;
  196. hints.style.left = left + "px";
  197. hints.style.top = top + "px";
  198. // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
  199. var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
  200. var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
  201. (completion.options.container || document.body).appendChild(hints);
  202. var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
  203. var scrolls = hints.scrollHeight > hints.clientHeight + 1
  204. var startScroll = cm.getScrollInfo();
  205. if (overlapY > 0) {
  206. var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
  207. if (curTop - height > 0) { // Fits above cursor
  208. hints.style.top = (top = pos.top - height) + "px";
  209. below = false;
  210. } else if (height > winH) {
  211. hints.style.height = (winH - 5) + "px";
  212. hints.style.top = (top = pos.bottom - box.top) + "px";
  213. var cursor = cm.getCursor();
  214. if (data.from.ch != cursor.ch) {
  215. pos = cm.cursorCoords(cursor);
  216. hints.style.left = (left = pos.left) + "px";
  217. box = hints.getBoundingClientRect();
  218. }
  219. }
  220. }
  221. var overlapX = box.right - winW;
  222. if (overlapX > 0) {
  223. if (box.right - box.left > winW) {
  224. hints.style.width = (winW - 5) + "px";
  225. overlapX -= (box.right - box.left) - winW;
  226. }
  227. hints.style.left = (left = pos.left - overlapX) + "px";
  228. }
  229. if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling)
  230. node.style.paddingRight = cm.display.nativeBarWidth + "px"
  231. cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
  232. moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
  233. setFocus: function(n) { widget.changeActive(n); },
  234. menuSize: function() { return widget.screenAmount(); },
  235. length: completions.length,
  236. close: function() { completion.close(); },
  237. pick: function() { widget.pick(); },
  238. data: data
  239. }));
  240. if (completion.options.closeOnUnfocus) {
  241. var closingOnBlur;
  242. cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
  243. cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
  244. }
  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. disable: function() {
  285. this.completion.cm.removeKeyMap(this.keyMap);
  286. var widget = this;
  287. this.keyMap = {Enter: function() { widget.picked = true; }};
  288. this.completion.cm.addKeyMap(this.keyMap);
  289. },
  290. pick: function() {
  291. this.completion.pick(this.data, this.selectedHint);
  292. },
  293. changeActive: function(i, avoidWrap) {
  294. if (i >= this.data.list.length)
  295. i = avoidWrap ? this.data.list.length - 1 : 0;
  296. else if (i < 0)
  297. i = avoidWrap ? 0 : this.data.list.length - 1;
  298. if (this.selectedHint == i) return;
  299. var node = this.hints.childNodes[this.selectedHint];
  300. node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
  301. node = this.hints.childNodes[this.selectedHint = i];
  302. node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
  303. if (node.offsetTop < this.hints.scrollTop)
  304. this.hints.scrollTop = node.offsetTop - 3;
  305. else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
  306. this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
  307. CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
  308. },
  309. screenAmount: function() {
  310. return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
  311. }
  312. };
  313. function applicableHelpers(cm, helpers) {
  314. if (!cm.somethingSelected()) return helpers
  315. var result = []
  316. for (var i = 0; i < helpers.length; i++)
  317. if (helpers[i].supportsSelection) result.push(helpers[i])
  318. return result
  319. }
  320. function fetchHints(hint, cm, options, callback) {
  321. if (hint.async) {
  322. hint(cm, callback, options)
  323. } else {
  324. var result = hint(cm, options)
  325. if (result && result.then) result.then(callback)
  326. else callback(result)
  327. }
  328. }
  329. function resolveAutoHints(cm, pos) {
  330. var helpers = cm.getHelpers(pos, "hint"), words
  331. if (helpers.length) {
  332. var resolved = function(cm, callback, options) {
  333. var app = applicableHelpers(cm, helpers);
  334. function run(i) {
  335. if (i == app.length) return callback(null)
  336. fetchHints(app[i], cm, options, function(result) {
  337. if (result && result.list.length > 0) callback(result)
  338. else run(i + 1)
  339. })
  340. }
  341. run(0)
  342. }
  343. resolved.async = true
  344. resolved.supportsSelection = true
  345. return resolved
  346. } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
  347. return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) }
  348. } else if (CodeMirror.hint.anyword) {
  349. return function(cm, options) { return CodeMirror.hint.anyword(cm, options) }
  350. } else {
  351. return function() {}
  352. }
  353. }
  354. CodeMirror.registerHelper("hint", "auto", {
  355. resolve: resolveAutoHints
  356. });
  357. CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
  358. var cur = cm.getCursor(), token = cm.getTokenAt(cur);
  359. var to = CodeMirror.Pos(cur.line, token.end);
  360. if (token.string && /\w/.test(token.string[token.string.length - 1])) {
  361. var term = token.string, from = CodeMirror.Pos(cur.line, token.start);
  362. } else {
  363. var term = "", from = to;
  364. }
  365. var found = [];
  366. for (var i = 0; i < options.words.length; i++) {
  367. var word = options.words[i];
  368. if (word.slice(0, term.length) == term)
  369. found.push(word);
  370. }
  371. if (found.length) return {list: found, from: from, to: to};
  372. });
  373. CodeMirror.commands.autocomplete = CodeMirror.showHint;
  374. var defaultOptions = {
  375. hint: CodeMirror.hint.auto,
  376. completeSingle: true,
  377. alignWithWord: true,
  378. closeCharacters: /[\s()\[\]{};:>,]/,
  379. closeOnUnfocus: true,
  380. completeOnSingleClick: true,
  381. container: null,
  382. customKeys: null,
  383. extraKeys: null
  384. };
  385. CodeMirror.defineOption("hintOptions", null);
  386. });