show-hint.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://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. this.data = data;
  106. if (data && data.list.length) {
  107. if (picked && data.list.length == 1) {
  108. this.pick(data, 0);
  109. } else {
  110. this.widget = new Widget(this, data);
  111. CodeMirror.signal(data, "shown");
  112. }
  113. }
  114. }
  115. };
  116. function parseOptions(cm, pos, options) {
  117. var editor = cm.options.hintOptions;
  118. var out = {};
  119. for (var prop in defaultOptions) out[prop] = defaultOptions[prop];
  120. if (editor) for (var prop in editor)
  121. if (editor[prop] !== undefined) out[prop] = editor[prop];
  122. if (options) for (var prop in options)
  123. if (options[prop] !== undefined) out[prop] = options[prop];
  124. if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos)
  125. return out;
  126. }
  127. function getText(completion) {
  128. if (typeof completion == "string") return completion;
  129. else return completion.text;
  130. }
  131. function buildKeyMap(completion, handle) {
  132. var baseMap = {
  133. Up: function() {handle.moveFocus(-1);},
  134. Down: function() {handle.moveFocus(1);},
  135. PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
  136. PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
  137. Home: function() {handle.setFocus(0);},
  138. End: function() {handle.setFocus(handle.length - 1);},
  139. Enter: handle.pick,
  140. Tab: handle.pick,
  141. Esc: handle.close
  142. };
  143. var custom = completion.options.customKeys;
  144. var ourMap = custom ? {} : baseMap;
  145. function addBinding(key, val) {
  146. var bound;
  147. if (typeof val != "string")
  148. bound = function(cm) { return val(cm, handle); };
  149. // This mechanism is deprecated
  150. else if (baseMap.hasOwnProperty(val))
  151. bound = baseMap[val];
  152. else
  153. bound = val;
  154. ourMap[key] = bound;
  155. }
  156. if (custom)
  157. for (var key in custom) if (custom.hasOwnProperty(key))
  158. addBinding(key, custom[key]);
  159. var extra = completion.options.extraKeys;
  160. if (extra)
  161. for (var key in extra) if (extra.hasOwnProperty(key))
  162. addBinding(key, extra[key]);
  163. return ourMap;
  164. }
  165. function getHintElement(hintsElement, el) {
  166. while (el && el != hintsElement) {
  167. if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el;
  168. el = el.parentNode;
  169. }
  170. }
  171. function Widget(completion, data) {
  172. this.completion = completion;
  173. this.data = data;
  174. this.picked = false;
  175. var widget = this, cm = completion.cm;
  176. var hints = this.hints = document.createElement("ul");
  177. var theme = completion.cm.options.theme;
  178. hints.className = "CodeMirror-hints " + theme;
  179. this.selectedHint = data.selectedHint || 0;
  180. var completions = data.list;
  181. for (var i = 0; i < completions.length; ++i) {
  182. var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
  183. var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
  184. if (cur.className != null) className = cur.className + " " + className;
  185. elt.className = className;
  186. if (cur.render) cur.render(elt, data, cur);
  187. else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
  188. elt.hintId = i;
  189. }
  190. var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);
  191. var left = pos.left, top = pos.bottom, below = true;
  192. hints.style.left = left + "px";
  193. hints.style.top = top + "px";
  194. // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
  195. var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
  196. var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
  197. (completion.options.container || document.body).appendChild(hints);
  198. var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
  199. var scrolls = hints.scrollHeight > hints.clientHeight + 1
  200. var startScroll = cm.getScrollInfo();
  201. if (overlapY > 0) {
  202. var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
  203. if (curTop - height > 0) { // Fits above cursor
  204. hints.style.top = (top = pos.top - height) + "px";
  205. below = false;
  206. } else if (height > winH) {
  207. hints.style.height = (winH - 5) + "px";
  208. hints.style.top = (top = pos.bottom - box.top) + "px";
  209. var cursor = cm.getCursor();
  210. if (data.from.ch != cursor.ch) {
  211. pos = cm.cursorCoords(cursor);
  212. hints.style.left = (left = pos.left) + "px";
  213. box = hints.getBoundingClientRect();
  214. }
  215. }
  216. }
  217. var overlapX = box.right - winW;
  218. if (overlapX > 0) {
  219. if (box.right - box.left > winW) {
  220. hints.style.width = (winW - 5) + "px";
  221. overlapX -= (box.right - box.left) - winW;
  222. }
  223. hints.style.left = (left = pos.left - overlapX) + "px";
  224. }
  225. if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling)
  226. node.style.paddingRight = cm.display.nativeBarWidth + "px"
  227. cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
  228. moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
  229. setFocus: function(n) { widget.changeActive(n); },
  230. menuSize: function() { return widget.screenAmount(); },
  231. length: completions.length,
  232. close: function() { completion.close(); },
  233. pick: function() { widget.pick(); },
  234. data: data
  235. }));
  236. if (completion.options.closeOnUnfocus) {
  237. var closingOnBlur;
  238. cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
  239. cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
  240. }
  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[this.selectedHint], hints.childNodes[this.selectedHint]);
  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. disable: function() {
  281. this.completion.cm.removeKeyMap(this.keyMap);
  282. var widget = this;
  283. this.keyMap = {Enter: function() { widget.picked = true; }};
  284. this.completion.cm.addKeyMap(this.keyMap);
  285. },
  286. pick: function() {
  287. this.completion.pick(this.data, this.selectedHint);
  288. },
  289. changeActive: function(i, avoidWrap) {
  290. if (i >= this.data.list.length)
  291. i = avoidWrap ? this.data.list.length - 1 : 0;
  292. else if (i < 0)
  293. i = avoidWrap ? 0 : this.data.list.length - 1;
  294. if (this.selectedHint == i) return;
  295. var node = this.hints.childNodes[this.selectedHint];
  296. if (node) node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
  297. node = this.hints.childNodes[this.selectedHint = i];
  298. node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
  299. if (node.offsetTop < this.hints.scrollTop)
  300. this.hints.scrollTop = node.offsetTop - 3;
  301. else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
  302. this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
  303. CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
  304. },
  305. screenAmount: function() {
  306. return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
  307. }
  308. };
  309. function applicableHelpers(cm, helpers) {
  310. if (!cm.somethingSelected()) return helpers
  311. var result = []
  312. for (var i = 0; i < helpers.length; i++)
  313. if (helpers[i].supportsSelection) result.push(helpers[i])
  314. return result
  315. }
  316. function fetchHints(hint, cm, options, callback) {
  317. if (hint.async) {
  318. hint(cm, callback, options)
  319. } else {
  320. var result = hint(cm, options)
  321. if (result && result.then) result.then(callback)
  322. else callback(result)
  323. }
  324. }
  325. function resolveAutoHints(cm, pos) {
  326. var helpers = cm.getHelpers(pos, "hint"), words
  327. if (helpers.length) {
  328. var resolved = function(cm, callback, options) {
  329. var app = applicableHelpers(cm, helpers);
  330. function run(i) {
  331. if (i == app.length) return callback(null)
  332. fetchHints(app[i], cm, options, function(result) {
  333. if (result && result.list.length > 0) callback(result)
  334. else run(i + 1)
  335. })
  336. }
  337. run(0)
  338. }
  339. resolved.async = true
  340. resolved.supportsSelection = true
  341. return resolved
  342. } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
  343. return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) }
  344. } else if (CodeMirror.hint.anyword) {
  345. return function(cm, options) { return CodeMirror.hint.anyword(cm, options) }
  346. } else {
  347. return function() {}
  348. }
  349. }
  350. CodeMirror.registerHelper("hint", "auto", {
  351. resolve: resolveAutoHints
  352. });
  353. CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
  354. var cur = cm.getCursor(), token = cm.getTokenAt(cur)
  355. var term, from = CodeMirror.Pos(cur.line, token.start), to = cur
  356. if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) {
  357. term = token.string.substr(0, cur.ch - token.start)
  358. } else {
  359. term = ""
  360. from = cur
  361. }
  362. var found = [];
  363. for (var i = 0; i < options.words.length; i++) {
  364. var word = options.words[i];
  365. if (word.slice(0, term.length) == term)
  366. found.push(word);
  367. }
  368. if (found.length) return {list: found, from: from, to: to};
  369. });
  370. CodeMirror.commands.autocomplete = CodeMirror.showHint;
  371. var defaultOptions = {
  372. hint: CodeMirror.hint.auto,
  373. completeSingle: true,
  374. alignWithWord: true,
  375. closeCharacters: /[\s()\[\]{};:>,]/,
  376. closeOnUnfocus: true,
  377. completeOnSingleClick: true,
  378. container: null,
  379. customKeys: null,
  380. extraKeys: null
  381. };
  382. CodeMirror.defineOption("hintOptions", null);
  383. });