show-hint.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. CodeMirror.defineExtension("closeHint", function() {
  43. if (this.state.completionActive) this.state.completionActive.close()
  44. })
  45. function Completion(cm, options) {
  46. this.cm = cm;
  47. this.options = options;
  48. this.widget = null;
  49. this.debounce = 0;
  50. this.tick = 0;
  51. this.startPos = this.cm.getCursor("start");
  52. this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length;
  53. var self = this;
  54. cm.on("cursorActivity", this.activityFunc = function() { self.cursorActivity(); });
  55. }
  56. var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
  57. return setTimeout(fn, 1000/60);
  58. };
  59. var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
  60. Completion.prototype = {
  61. close: function() {
  62. if (!this.active()) return;
  63. this.cm.state.completionActive = null;
  64. this.tick = null;
  65. this.cm.off("cursorActivity", this.activityFunc);
  66. if (this.widget && this.data) CodeMirror.signal(this.data, "close");
  67. if (this.widget) this.widget.close();
  68. CodeMirror.signal(this.cm, "endCompletion", this.cm);
  69. },
  70. active: function() {
  71. return this.cm.state.completionActive == this;
  72. },
  73. pick: function(data, i) {
  74. var completion = data.list[i], self = this;
  75. this.cm.operation(function() {
  76. if (completion.hint)
  77. completion.hint(self.cm, data, completion);
  78. else
  79. self.cm.replaceRange(getText(completion), completion.from || data.from,
  80. completion.to || data.to, "complete");
  81. CodeMirror.signal(data, "pick", completion);
  82. self.cm.scrollIntoView();
  83. })
  84. this.close();
  85. },
  86. cursorActivity: function() {
  87. if (this.debounce) {
  88. cancelAnimationFrame(this.debounce);
  89. this.debounce = 0;
  90. }
  91. var identStart = this.startPos;
  92. if(this.data) {
  93. identStart = this.data.from;
  94. }
  95. var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line);
  96. if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch ||
  97. pos.ch < identStart.ch || this.cm.somethingSelected() ||
  98. (!pos.ch || this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) {
  99. this.close();
  100. } else {
  101. var self = this;
  102. this.debounce = requestAnimationFrame(function() {self.update();});
  103. if (this.widget) this.widget.disable();
  104. }
  105. },
  106. update: function(first) {
  107. if (this.tick == null) return
  108. var self = this, myTick = ++this.tick
  109. fetchHints(this.options.hint, this.cm, this.options, function(data) {
  110. if (self.tick == myTick) self.finishUpdate(data, first)
  111. })
  112. },
  113. finishUpdate: function(data, first) {
  114. if (this.data) CodeMirror.signal(this.data, "update");
  115. var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle);
  116. if (this.widget) this.widget.close();
  117. this.data = data;
  118. if (data && data.list.length) {
  119. if (picked && data.list.length == 1) {
  120. this.pick(data, 0);
  121. } else {
  122. this.widget = new Widget(this, data);
  123. CodeMirror.signal(data, "shown");
  124. }
  125. }
  126. }
  127. };
  128. function parseOptions(cm, pos, options) {
  129. var editor = cm.options.hintOptions;
  130. var out = {};
  131. for (var prop in defaultOptions) out[prop] = defaultOptions[prop];
  132. if (editor) for (var prop in editor)
  133. if (editor[prop] !== undefined) out[prop] = editor[prop];
  134. if (options) for (var prop in options)
  135. if (options[prop] !== undefined) out[prop] = options[prop];
  136. if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos)
  137. return out;
  138. }
  139. function getText(completion) {
  140. if (typeof completion == "string") return completion;
  141. else return completion.text;
  142. }
  143. function buildKeyMap(completion, handle) {
  144. var baseMap = {
  145. Up: function() {handle.moveFocus(-1);},
  146. Down: function() {handle.moveFocus(1);},
  147. PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
  148. PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
  149. Home: function() {handle.setFocus(0);},
  150. End: function() {handle.setFocus(handle.length - 1);},
  151. Enter: handle.pick,
  152. Tab: handle.pick,
  153. Esc: handle.close
  154. };
  155. var mac = /Mac/.test(navigator.platform);
  156. if (mac) {
  157. baseMap["Ctrl-P"] = function() {handle.moveFocus(-1);};
  158. baseMap["Ctrl-N"] = function() {handle.moveFocus(1);};
  159. }
  160. var custom = completion.options.customKeys;
  161. var ourMap = custom ? {} : baseMap;
  162. function addBinding(key, val) {
  163. var bound;
  164. if (typeof val != "string")
  165. bound = function(cm) { return val(cm, handle); };
  166. // This mechanism is deprecated
  167. else if (baseMap.hasOwnProperty(val))
  168. bound = baseMap[val];
  169. else
  170. bound = val;
  171. ourMap[key] = bound;
  172. }
  173. if (custom)
  174. for (var key in custom) if (custom.hasOwnProperty(key))
  175. addBinding(key, custom[key]);
  176. var extra = completion.options.extraKeys;
  177. if (extra)
  178. for (var key in extra) if (extra.hasOwnProperty(key))
  179. addBinding(key, extra[key]);
  180. return ourMap;
  181. }
  182. function getHintElement(hintsElement, el) {
  183. while (el && el != hintsElement) {
  184. if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el;
  185. el = el.parentNode;
  186. }
  187. }
  188. function Widget(completion, data) {
  189. this.completion = completion;
  190. this.data = data;
  191. this.picked = false;
  192. var widget = this, cm = completion.cm;
  193. var ownerDocument = cm.getInputField().ownerDocument;
  194. var parentWindow = ownerDocument.defaultView || ownerDocument.parentWindow;
  195. var hints = this.hints = ownerDocument.createElement("ul");
  196. var theme = completion.cm.options.theme;
  197. hints.className = "CodeMirror-hints " + theme;
  198. this.selectedHint = data.selectedHint || 0;
  199. var completions = data.list;
  200. for (var i = 0; i < completions.length; ++i) {
  201. var elt = hints.appendChild(ownerDocument.createElement("li")), cur = completions[i];
  202. var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
  203. if (cur.className != null) className = cur.className + " " + className;
  204. elt.className = className;
  205. if (cur.render) cur.render(elt, data, cur);
  206. else elt.appendChild(ownerDocument.createTextNode(cur.displayText || getText(cur)));
  207. elt.hintId = i;
  208. }
  209. var container = completion.options.container || ownerDocument.body;
  210. var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);
  211. var left = pos.left, top = pos.bottom, below = true;
  212. var offsetLeft = 0, offsetTop = 0;
  213. if (container !== ownerDocument.body) {
  214. // We offset the cursor position because left and top are relative to the offsetParent's top left corner.
  215. var isContainerPositioned = ['absolute', 'relative', 'fixed'].indexOf(parentWindow.getComputedStyle(container).position) !== -1;
  216. var offsetParent = isContainerPositioned ? container : container.offsetParent;
  217. var offsetParentPosition = offsetParent.getBoundingClientRect();
  218. var bodyPosition = ownerDocument.body.getBoundingClientRect();
  219. offsetLeft = (offsetParentPosition.left - bodyPosition.left - offsetParent.scrollLeft);
  220. offsetTop = (offsetParentPosition.top - bodyPosition.top - offsetParent.scrollTop);
  221. }
  222. hints.style.left = (left - offsetLeft) + "px";
  223. hints.style.top = (top - offsetTop) + "px";
  224. // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
  225. var winW = parentWindow.innerWidth || Math.max(ownerDocument.body.offsetWidth, ownerDocument.documentElement.offsetWidth);
  226. var winH = parentWindow.innerHeight || Math.max(ownerDocument.body.offsetHeight, ownerDocument.documentElement.offsetHeight);
  227. container.appendChild(hints);
  228. var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
  229. var scrolls = hints.scrollHeight > hints.clientHeight + 1
  230. var startScroll = cm.getScrollInfo();
  231. if (overlapY > 0) {
  232. var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
  233. if (curTop - height > 0) { // Fits above cursor
  234. hints.style.top = (top = pos.top - height - offsetTop) + "px";
  235. below = false;
  236. } else if (height > winH) {
  237. hints.style.height = (winH - 5) + "px";
  238. hints.style.top = (top = pos.bottom - box.top - offsetTop) + "px";
  239. var cursor = cm.getCursor();
  240. if (data.from.ch != cursor.ch) {
  241. pos = cm.cursorCoords(cursor);
  242. hints.style.left = (left = pos.left - offsetLeft) + "px";
  243. box = hints.getBoundingClientRect();
  244. }
  245. }
  246. }
  247. var overlapX = box.right - winW;
  248. if (overlapX > 0) {
  249. if (box.right - box.left > winW) {
  250. hints.style.width = (winW - 5) + "px";
  251. overlapX -= (box.right - box.left) - winW;
  252. }
  253. hints.style.left = (left = pos.left - overlapX - offsetLeft) + "px";
  254. }
  255. if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling)
  256. node.style.paddingRight = cm.display.nativeBarWidth + "px"
  257. cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
  258. moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
  259. setFocus: function(n) { widget.changeActive(n); },
  260. menuSize: function() { return widget.screenAmount(); },
  261. length: completions.length,
  262. close: function() { completion.close(); },
  263. pick: function() { widget.pick(); },
  264. data: data
  265. }));
  266. if (completion.options.closeOnUnfocus) {
  267. var closingOnBlur;
  268. cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
  269. cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
  270. }
  271. cm.on("scroll", this.onScroll = function() {
  272. var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
  273. var newTop = top + startScroll.top - curScroll.top;
  274. var point = newTop - (parentWindow.pageYOffset || (ownerDocument.documentElement || ownerDocument.body).scrollTop);
  275. if (!below) point += hints.offsetHeight;
  276. if (point <= editor.top || point >= editor.bottom) return completion.close();
  277. hints.style.top = newTop + "px";
  278. hints.style.left = (left + startScroll.left - curScroll.left) + "px";
  279. });
  280. CodeMirror.on(hints, "dblclick", function(e) {
  281. var t = getHintElement(hints, e.target || e.srcElement);
  282. if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
  283. });
  284. CodeMirror.on(hints, "click", function(e) {
  285. var t = getHintElement(hints, e.target || e.srcElement);
  286. if (t && t.hintId != null) {
  287. widget.changeActive(t.hintId);
  288. if (completion.options.completeOnSingleClick) widget.pick();
  289. }
  290. });
  291. CodeMirror.on(hints, "mousedown", function() {
  292. setTimeout(function(){cm.focus();}, 20);
  293. });
  294. this.scrollToActive()
  295. CodeMirror.signal(data, "select", completions[this.selectedHint], hints.childNodes[this.selectedHint]);
  296. return true;
  297. }
  298. Widget.prototype = {
  299. close: function() {
  300. if (this.completion.widget != this) return;
  301. this.completion.widget = null;
  302. this.hints.parentNode.removeChild(this.hints);
  303. this.completion.cm.removeKeyMap(this.keyMap);
  304. var cm = this.completion.cm;
  305. if (this.completion.options.closeOnUnfocus) {
  306. cm.off("blur", this.onBlur);
  307. cm.off("focus", this.onFocus);
  308. }
  309. cm.off("scroll", this.onScroll);
  310. },
  311. disable: function() {
  312. this.completion.cm.removeKeyMap(this.keyMap);
  313. var widget = this;
  314. this.keyMap = {Enter: function() { widget.picked = true; }};
  315. this.completion.cm.addKeyMap(this.keyMap);
  316. },
  317. pick: function() {
  318. this.completion.pick(this.data, this.selectedHint);
  319. },
  320. changeActive: function(i, avoidWrap) {
  321. if (i >= this.data.list.length)
  322. i = avoidWrap ? this.data.list.length - 1 : 0;
  323. else if (i < 0)
  324. i = avoidWrap ? 0 : this.data.list.length - 1;
  325. if (this.selectedHint == i) return;
  326. var node = this.hints.childNodes[this.selectedHint];
  327. if (node) node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
  328. node = this.hints.childNodes[this.selectedHint = i];
  329. node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
  330. this.scrollToActive()
  331. CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
  332. },
  333. scrollToActive: function() {
  334. var margin = this.completion.options.scrollMargin || 0;
  335. var node1 = this.hints.childNodes[Math.max(0, this.selectedHint - margin)];
  336. var node2 = this.hints.childNodes[Math.min(this.data.list.length - 1, this.selectedHint + margin)];
  337. var firstNode = this.hints.firstChild;
  338. if (node1.offsetTop < this.hints.scrollTop)
  339. this.hints.scrollTop = node1.offsetTop - firstNode.offsetTop;
  340. else if (node2.offsetTop + node2.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
  341. this.hints.scrollTop = node2.offsetTop + node2.offsetHeight - this.hints.clientHeight + firstNode.offsetTop;
  342. },
  343. screenAmount: function() {
  344. return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
  345. }
  346. };
  347. function applicableHelpers(cm, helpers) {
  348. if (!cm.somethingSelected()) return helpers
  349. var result = []
  350. for (var i = 0; i < helpers.length; i++)
  351. if (helpers[i].supportsSelection) result.push(helpers[i])
  352. return result
  353. }
  354. function fetchHints(hint, cm, options, callback) {
  355. if (hint.async) {
  356. hint(cm, callback, options)
  357. } else {
  358. var result = hint(cm, options)
  359. if (result && result.then) result.then(callback)
  360. else callback(result)
  361. }
  362. }
  363. function resolveAutoHints(cm, pos) {
  364. var helpers = cm.getHelpers(pos, "hint"), words
  365. if (helpers.length) {
  366. var resolved = function(cm, callback, options) {
  367. var app = applicableHelpers(cm, helpers);
  368. function run(i) {
  369. if (i == app.length) return callback(null)
  370. fetchHints(app[i], cm, options, function(result) {
  371. if (result && result.list.length > 0) callback(result)
  372. else run(i + 1)
  373. })
  374. }
  375. run(0)
  376. }
  377. resolved.async = true
  378. resolved.supportsSelection = true
  379. return resolved
  380. } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
  381. return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) }
  382. } else if (CodeMirror.hint.anyword) {
  383. return function(cm, options) { return CodeMirror.hint.anyword(cm, options) }
  384. } else {
  385. return function() {}
  386. }
  387. }
  388. CodeMirror.registerHelper("hint", "auto", {
  389. resolve: resolveAutoHints
  390. });
  391. CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
  392. var cur = cm.getCursor(), token = cm.getTokenAt(cur)
  393. var term, from = CodeMirror.Pos(cur.line, token.start), to = cur
  394. if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) {
  395. term = token.string.substr(0, cur.ch - token.start)
  396. } else {
  397. term = ""
  398. from = cur
  399. }
  400. var found = [];
  401. for (var i = 0; i < options.words.length; i++) {
  402. var word = options.words[i];
  403. if (word.slice(0, term.length) == term)
  404. found.push(word);
  405. }
  406. if (found.length) return {list: found, from: from, to: to};
  407. });
  408. CodeMirror.commands.autocomplete = CodeMirror.showHint;
  409. var defaultOptions = {
  410. hint: CodeMirror.hint.auto,
  411. completeSingle: true,
  412. alignWithWord: true,
  413. closeCharacters: /[\s()\[\]{};:>,]/,
  414. closeOnUnfocus: true,
  415. completeOnSingleClick: true,
  416. container: null,
  417. customKeys: null,
  418. extraKeys: null
  419. };
  420. CodeMirror.defineOption("hintOptions", null);
  421. });