autocomplete.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. /* ***** BEGIN LICENSE BLOCK *****
  2. * Distributed under the BSD license:
  3. *
  4. * Copyright (c) 2012, Ajax.org B.V.
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * * Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * * Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * * Neither the name of Ajax.org B.V. nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * ***** END LICENSE BLOCK ***** */
  30. define(function(require, exports, module) {
  31. "use strict";
  32. var HashHandler = require("./keyboard/hash_handler").HashHandler;
  33. var AcePopup = require("./autocomplete/popup").AcePopup;
  34. var util = require("./autocomplete/util");
  35. var event = require("./lib/event");
  36. var lang = require("./lib/lang");
  37. var dom = require("./lib/dom");
  38. var snippetManager = require("./snippets").snippetManager;
  39. var Autocomplete = function() {
  40. this.autoInsert = false;
  41. this.autoSelect = true;
  42. this.exactMatch = false;
  43. this.gatherCompletionsId = 0;
  44. this.keyboardHandler = new HashHandler();
  45. this.keyboardHandler.bindKeys(this.commands);
  46. this.blurListener = this.blurListener.bind(this);
  47. this.changeListener = this.changeListener.bind(this);
  48. this.mousedownListener = this.mousedownListener.bind(this);
  49. this.mousewheelListener = this.mousewheelListener.bind(this);
  50. this.changeTimer = lang.delayedCall(function() {
  51. this.updateCompletions(true);
  52. }.bind(this));
  53. this.tooltipTimer = lang.delayedCall(this.updateDocTooltip.bind(this), 50);
  54. };
  55. (function() {
  56. this.$init = function() {
  57. this.popup = new AcePopup(document.body || document.documentElement);
  58. this.popup.on("click", function(e) {
  59. this.insertMatch();
  60. e.stop();
  61. }.bind(this));
  62. this.popup.focus = this.editor.focus.bind(this.editor);
  63. this.popup.on("show", this.tooltipTimer.bind(null, null));
  64. this.popup.on("select", this.tooltipTimer.bind(null, null));
  65. this.popup.on("changeHoverMarker", this.tooltipTimer.bind(null, null));
  66. return this.popup;
  67. };
  68. this.getPopup = function() {
  69. return this.popup || this.$init();
  70. };
  71. this.openPopup = function(editor, prefix, keepPopupPosition) {
  72. if (!this.popup)
  73. this.$init();
  74. this.popup.setData(this.completions.filtered);
  75. editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
  76. var renderer = editor.renderer;
  77. this.popup.setRow(this.autoSelect ? 0 : -1);
  78. if (!keepPopupPosition) {
  79. this.popup.setTheme(editor.getTheme());
  80. this.popup.setFontSize(editor.getFontSize());
  81. var lineHeight = renderer.layerConfig.lineHeight;
  82. var pos = renderer.$cursorLayer.getPixelPosition(this.base, true);
  83. pos.left -= this.popup.getTextLeftOffset();
  84. var rect = editor.container.getBoundingClientRect();
  85. pos.top += rect.top - renderer.layerConfig.offset;
  86. pos.left += rect.left - editor.renderer.scrollLeft;
  87. pos.left += renderer.gutterWidth;
  88. this.popup.show(pos, lineHeight);
  89. } else if (keepPopupPosition && !prefix) {
  90. this.detach();
  91. }
  92. };
  93. this.detach = function() {
  94. this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
  95. this.editor.off("changeSelection", this.changeListener);
  96. this.editor.off("blur", this.blurListener);
  97. this.editor.off("mousedown", this.mousedownListener);
  98. this.editor.off("mousewheel", this.mousewheelListener);
  99. this.changeTimer.cancel();
  100. this.hideDocTooltip();
  101. this.gatherCompletionsId += 1;
  102. if (this.popup && this.popup.isOpen)
  103. this.popup.hide();
  104. if (this.base)
  105. this.base.detach();
  106. this.activated = false;
  107. this.completions = this.base = null;
  108. };
  109. this.changeListener = function(e) {
  110. var cursor = this.editor.selection.lead;
  111. if (cursor.row != this.base.row || cursor.column < this.base.column) {
  112. this.detach();
  113. }
  114. if (this.activated)
  115. this.changeTimer.schedule();
  116. else
  117. this.detach();
  118. };
  119. this.blurListener = function(e) {
  120. // we have to check if activeElement is a child of popup because
  121. // on IE preventDefault doesn't stop scrollbar from being focussed
  122. var el = document.activeElement;
  123. var text = this.editor.textInput.getElement();
  124. var fromTooltip = e.relatedTarget && e.relatedTarget == this.tooltipNode;
  125. var container = this.popup && this.popup.container;
  126. if (el != text && el.parentNode != container && !fromTooltip
  127. && el != this.tooltipNode && e.relatedTarget != text
  128. ) {
  129. this.detach();
  130. }
  131. };
  132. this.mousedownListener = function(e) {
  133. this.detach();
  134. };
  135. this.mousewheelListener = function(e) {
  136. this.detach();
  137. };
  138. this.goTo = function(where) {
  139. var row = this.popup.getRow();
  140. var max = this.popup.session.getLength() - 1;
  141. switch(where) {
  142. case "up": row = row <= 0 ? max : row - 1; break;
  143. case "down": row = row >= max ? -1 : row + 1; break;
  144. case "start": row = 0; break;
  145. case "end": row = max; break;
  146. }
  147. this.popup.setRow(row);
  148. };
  149. this.insertMatch = function(data, options) {
  150. if (!data)
  151. data = this.popup.getData(this.popup.getRow());
  152. if (!data)
  153. return false;
  154. if (data.completer && data.completer.insertMatch) {
  155. data.completer.insertMatch(this.editor, data);
  156. } else {
  157. // TODO add support for options.deleteSuffix
  158. if (this.completions.filterText) {
  159. var ranges = this.editor.selection.getAllRanges();
  160. for (var i = 0, range; range = ranges[i]; i++) {
  161. range.start.column -= this.completions.filterText.length;
  162. this.editor.session.remove(range);
  163. }
  164. }
  165. if (data.snippet) {
  166. snippetManager.insertSnippet(this.editor, data.snippet);
  167. } else if (data.upperCaseMatch) {
  168. this.editor.execCommand("insertstring", data.upperCaseValue);
  169. } else {
  170. this.editor.execCommand("insertstring", data.value || data);
  171. }
  172. }
  173. this.detach();
  174. };
  175. this.commands = {
  176. "Up": function(editor) { editor.completer.goTo("up"); },
  177. "Down": function(editor) { editor.completer.goTo("down"); },
  178. "Ctrl-Up|Ctrl-Home": function(editor) { editor.completer.goTo("start"); },
  179. "Ctrl-Down|Ctrl-End": function(editor) { editor.completer.goTo("end"); },
  180. "Esc": function(editor) { editor.completer.detach(); },
  181. "Return": function(editor) { return editor.completer.insertMatch(); },
  182. "Shift-Return": function(editor) { editor.completer.insertMatch(null, {deleteSuffix: true}); },
  183. "Tab": function(editor) {
  184. var result = editor.completer.insertMatch();
  185. if (!result && !editor.tabstopManager)
  186. editor.completer.goTo("down");
  187. else
  188. return result;
  189. },
  190. "PageUp": function(editor) { editor.completer.popup.gotoPageUp(); },
  191. "PageDown": function(editor) { editor.completer.popup.gotoPageDown(); }
  192. };
  193. this.gatherCompletions = function(editor, callback) {
  194. var session = editor.getSession();
  195. var pos = editor.getCursorPosition();
  196. var line = session.getLine(pos.row);
  197. var prefix = util.retrievePrecedingIdentifier(line, pos.column);
  198. this.base = session.doc.createAnchor(pos.row, pos.column - prefix.length);
  199. this.base.$insertRight = true;
  200. var matches = [];
  201. var total = editor.completers.length + session.getCompleters().length;
  202. editor.completers.concat(session.getCompleters()).forEach(function(completer, i) {
  203. completer.getCompletions(editor, session, pos, prefix, function(err, results) {
  204. if (!err)
  205. matches = matches.concat(results);
  206. // Fetch prefix again, because they may have changed by now
  207. var pos = editor.getCursorPosition();
  208. var line = session.getLine(pos.row);
  209. callback(null, {
  210. prefix: util.retrievePrecedingIdentifier(line, pos.column, results[0] && results[0].identifierRegex),
  211. matches: matches,
  212. finished: (--total === 0)
  213. });
  214. });
  215. });
  216. return true;
  217. };
  218. this.showPopup = function(editor) {
  219. if (this.editor)
  220. this.detach();
  221. this.activated = true;
  222. this.editor = editor;
  223. if (editor.completer != this) {
  224. if (editor.completer)
  225. editor.completer.detach();
  226. editor.completer = this;
  227. }
  228. editor.on("changeSelection", this.changeListener);
  229. editor.on("blur", this.blurListener);
  230. editor.on("mousedown", this.mousedownListener);
  231. editor.on("mousewheel", this.mousewheelListener);
  232. this.updateCompletions();
  233. };
  234. this.updateCompletions = function(keepPopupPosition) {
  235. if (keepPopupPosition && this.base && this.completions) {
  236. var pos = this.editor.getCursorPosition();
  237. var prefix = this.editor.session.getTextRange({start: this.base, end: pos});
  238. if (prefix == this.completions.filterText)
  239. return;
  240. this.completions.setFilter(prefix);
  241. if (!this.completions.filtered.length)
  242. return this.detach();
  243. if (this.completions.filtered.length == 1
  244. && this.completions.filtered[0].value == prefix
  245. && !this.completions.filtered[0].snippet)
  246. return this.detach();
  247. this.openPopup(this.editor, prefix, keepPopupPosition);
  248. return;
  249. }
  250. // Save current gatherCompletions session, session is close when a match is insert
  251. var _id = this.gatherCompletionsId;
  252. this.gatherCompletions(this.editor, function(err, results) {
  253. // Only detach if result gathering is finished
  254. var detachIfFinished = function() {
  255. if (!results.finished) return;
  256. return this.detach();
  257. }.bind(this);
  258. var prefix = results.prefix;
  259. var matches = results && results.matches;
  260. if (!matches || !matches.length)
  261. return detachIfFinished();
  262. // Wrong prefix or wrong session -> ignore
  263. if (prefix.indexOf(results.prefix) !== 0 || _id != this.gatherCompletionsId)
  264. return;
  265. this.completions = new FilteredList(matches);
  266. if (this.exactMatch)
  267. this.completions.exactMatch = true;
  268. this.completions.setFilter(prefix);
  269. var filtered = this.completions.filtered;
  270. // No results
  271. if (!filtered.length)
  272. return detachIfFinished();
  273. // One result equals to the prefix
  274. if (filtered.length == 1 && filtered[0].value == prefix && !filtered[0].snippet)
  275. return detachIfFinished();
  276. // Autoinsert if one result
  277. if (this.autoInsert && filtered.length == 1 && results.finished)
  278. return this.insertMatch(filtered[0]);
  279. this.openPopup(this.editor, prefix, keepPopupPosition);
  280. }.bind(this));
  281. };
  282. this.cancelContextMenu = function() {
  283. this.editor.$mouseHandler.cancelContextMenu();
  284. };
  285. this.updateDocTooltip = function() {
  286. var popup = this.popup;
  287. var all = popup.data;
  288. var selected = all && (all[popup.getHoveredRow()] || all[popup.getRow()]);
  289. var doc = null;
  290. if (!selected || !this.editor || !this.popup.isOpen)
  291. return this.hideDocTooltip();
  292. this.editor.completers.some(function(completer) {
  293. if (completer.getDocTooltip)
  294. doc = completer.getDocTooltip(selected);
  295. return doc;
  296. });
  297. if (!doc)
  298. doc = selected;
  299. if (typeof doc == "string")
  300. doc = {docText: doc};
  301. if (!doc || !(doc.docHTML || doc.docText))
  302. return this.hideDocTooltip();
  303. this.showDocTooltip(doc);
  304. };
  305. this.showDocTooltip = function(item) {
  306. if (!this.tooltipNode) {
  307. this.tooltipNode = dom.createElement("div");
  308. this.tooltipNode.className = "autocomplete-tooltip";
  309. this.tooltipNode.style.margin = 0;
  310. this.tooltipNode.style.pointerEvents = "auto";
  311. this.tooltipNode.tabIndex = -1;
  312. this.tooltipNode.onblur = this.blurListener.bind(this);
  313. }
  314. var tooltipNode = this.tooltipNode;
  315. if (item.docHTML) {
  316. tooltipNode.innerHTML = item.docHTML;
  317. } else if (item.docText) {
  318. tooltipNode.textContent = item.docText;
  319. }
  320. if (!tooltipNode.parentNode)
  321. document.body.appendChild(tooltipNode);
  322. var popup = this.popup;
  323. var rect = popup.container.getBoundingClientRect();
  324. tooltipNode.style.top = popup.container.style.top;
  325. tooltipNode.style.bottom = popup.container.style.bottom;
  326. if (window.innerWidth - rect.right < 320) {
  327. tooltipNode.style.right = window.innerWidth - rect.left + "px";
  328. tooltipNode.style.left = "";
  329. } else {
  330. tooltipNode.style.left = (rect.right + 1) + "px";
  331. tooltipNode.style.right = "";
  332. }
  333. tooltipNode.style.display = "block";
  334. };
  335. this.hideDocTooltip = function() {
  336. this.tooltipTimer.cancel();
  337. if (!this.tooltipNode) return;
  338. var el = this.tooltipNode;
  339. if (!this.editor.isFocused() && document.activeElement == el)
  340. this.editor.focus();
  341. this.tooltipNode = null;
  342. if (el.parentNode)
  343. el.parentNode.removeChild(el);
  344. };
  345. }).call(Autocomplete.prototype);
  346. Autocomplete.startCommand = {
  347. name: "startAutocomplete",
  348. exec: function(editor) {
  349. if (!editor.completer)
  350. editor.completer = new Autocomplete();
  351. editor.completer.autoInsert = false;
  352. editor.completer.autoSelect = true;
  353. editor.completer.showPopup(editor);
  354. // prevent ctrl-space opening context menu on firefox on mac
  355. editor.completer.cancelContextMenu();
  356. },
  357. bindKey: "Ctrl-Space|Ctrl-Shift-Space|Alt-Space"
  358. };
  359. var FilteredList = function(array, filterText) {
  360. this.all = array;
  361. this.filtered = array;
  362. this.filterText = filterText || "";
  363. this.exactMatch = false;
  364. };
  365. (function(){
  366. this.setFilter = function(str) {
  367. if (str.length > this.filterText && str.lastIndexOf(this.filterText, 0) === 0)
  368. var matches = this.filtered;
  369. else
  370. var matches = this.all;
  371. this.filterText = str;
  372. matches = this.filterCompletions(matches, this.filterText);
  373. matches = matches.sort(function (a, b) {
  374. if (a.completeMatch && ! b.completeMatch) {
  375. return -1;
  376. } else if (! a.completeMatch && b.completeMatch) {
  377. return 1;
  378. } else if (a.completeMatch && b.completeMatch && a.weight && b.weight && b.weight !== a.weight) {
  379. return b.weight - a.weight;
  380. } else if (a.completeMatch && b.completeMatch && a.startsWith && ! b.startsWith) {
  381. return -1;
  382. } else if (a.completeMatch && b.completeMatch && ! a.startsWith && b.startsWith) {
  383. return 1;
  384. }
  385. if (a.prioritizeScore && b.prioritizeScore) {
  386. return b.score - a.score
  387. } else if (a.prioritizeScore) {
  388. return -1;
  389. } else if (b.prioritizeScore) {
  390. return 1;
  391. }
  392. var alpha = 0;
  393. if (a.caption > b.caption) {
  394. alpha = 1;
  395. }
  396. if (a.caption < b.caption) {
  397. alpha = -1;
  398. }
  399. return alpha + b.exactMatch - a.exactMatch || alpha + b.score - a.score;
  400. });
  401. // make unique
  402. var prev = null;
  403. matches = matches.filter(function(item){
  404. var caption = item.snippet || item.caption || item.value;
  405. if (caption === prev) return false;
  406. prev = caption;
  407. return true;
  408. });
  409. this.filtered = matches;
  410. };
  411. this.filterCompletions = function(items, needle) {
  412. var results = [];
  413. var upper = needle.toUpperCase();
  414. var lower = needle.toLowerCase();
  415. loop: for (var i = 0, item; item = items[i]; i++) {
  416. var caption = item.value || item.caption || item.snippet;
  417. if (!caption) continue;
  418. var lastIndex = -1;
  419. var matchMask = 0;
  420. var penalty = 0;
  421. var index, distance;
  422. var completeIndex = 0;
  423. if (this.exactMatch && item.ignoreCase) {
  424. if (upper !== item.upperCaseValue.substr(0, needle.length)) {
  425. continue loop;
  426. }
  427. item.upperCaseMatch = needle === upper;
  428. item.caption = item.upperCaseMatch ? item.upperCaseValue : item.value;
  429. } else if (this.exactMatch && needle !== caption.substr(0, needle.length)) {
  430. continue loop;
  431. } else {
  432. completeIndex = caption.toUpperCase().indexOf(upper);
  433. if (completeIndex > -1) {
  434. lastIndex = completeIndex - 1;
  435. }
  436. for (var j = 0; j < needle.length; j++) {
  437. var i1 = caption.indexOf(lower[j], lastIndex + 1);
  438. var i2 = caption.indexOf(upper[j], lastIndex + 1);
  439. index = (i1 >= 0) ? ((i2 < 0 || i1 < i2) ? i1 : i2) : i2;
  440. if (index < 0)
  441. continue loop;
  442. distance = index - lastIndex - 1;
  443. if (distance > 0) {
  444. penalty += distance;
  445. }
  446. matchMask = matchMask | (1 << index);
  447. lastIndex = index;
  448. }
  449. }
  450. item.matchMask = matchMask;
  451. item.exactMatch = penalty ? 0 : 1;
  452. item.score = (item.score || 0) - penalty;
  453. item.startsWith = completeIndex === 0;
  454. item.completeMatch = completeIndex > -1;
  455. results.push(item);
  456. }
  457. return results;
  458. };
  459. }).call(FilteredList.prototype);
  460. exports.Autocomplete = Autocomplete;
  461. exports.FilteredList = FilteredList;
  462. });