autocomplete.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. this.editor.renderer.scrollCursorIntoView();
  173. }
  174. this.detach();
  175. };
  176. this.commands = {
  177. "Up": function(editor) { editor.completer.goTo("up"); },
  178. "Down": function(editor) { editor.completer.goTo("down"); },
  179. "Ctrl-Up|Ctrl-Home": function(editor) { editor.completer.goTo("start"); },
  180. "Ctrl-Down|Ctrl-End": function(editor) { editor.completer.goTo("end"); },
  181. "Esc": function(editor) { editor.completer.detach(); },
  182. "Return": function(editor) { return editor.completer.insertMatch(); },
  183. "Shift-Return": function(editor) { editor.completer.insertMatch(null, {deleteSuffix: true}); },
  184. "Tab": function(editor) {
  185. var result = editor.completer.insertMatch();
  186. if (!result && !editor.tabstopManager)
  187. editor.completer.goTo("down");
  188. else
  189. return result;
  190. },
  191. "PageUp": function(editor) { editor.completer.popup.gotoPageUp(); },
  192. "PageDown": function(editor) { editor.completer.popup.gotoPageDown(); }
  193. };
  194. this.gatherCompletions = function(editor, callback) {
  195. var session = editor.getSession();
  196. var pos = editor.getCursorPosition();
  197. var line = session.getLine(pos.row);
  198. var prefix = util.retrievePrecedingIdentifier(line, pos.column);
  199. this.base = session.doc.createAnchor(pos.row, pos.column - prefix.length);
  200. this.base.$insertRight = true;
  201. var matches = [];
  202. var total = editor.completers.length + session.getCompleters().length;
  203. editor.completers.concat(session.getCompleters()).forEach(function(completer, i) {
  204. completer.getCompletions(editor, session, pos, prefix, function(err, results) {
  205. if (!err)
  206. matches = matches.concat(results);
  207. // Fetch prefix again, because they may have changed by now
  208. var pos = editor.getCursorPosition();
  209. var line = session.getLine(pos.row);
  210. callback(null, {
  211. prefix: util.retrievePrecedingIdentifier(line, pos.column, results[0] && results[0].identifierRegex),
  212. matches: matches,
  213. finished: (--total === 0)
  214. });
  215. });
  216. });
  217. return true;
  218. };
  219. this.showPopup = function(editor) {
  220. if (this.editor)
  221. this.detach();
  222. this.activated = true;
  223. this.editor = editor;
  224. if (editor.completer != this) {
  225. if (editor.completer)
  226. editor.completer.detach();
  227. editor.completer = this;
  228. }
  229. editor.on("changeSelection", this.changeListener);
  230. editor.on("blur", this.blurListener);
  231. editor.on("mousedown", this.mousedownListener);
  232. editor.on("mousewheel", this.mousewheelListener);
  233. this.updateCompletions();
  234. };
  235. this.updateCompletions = function(keepPopupPosition) {
  236. if (keepPopupPosition && this.base && this.completions) {
  237. var pos = this.editor.getCursorPosition();
  238. var prefix = this.editor.session.getTextRange({start: this.base, end: pos});
  239. if (prefix == this.completions.filterText)
  240. return;
  241. this.completions.setFilter(prefix);
  242. if (!this.completions.filtered.length)
  243. return this.detach();
  244. if (this.completions.filtered.length == 1
  245. && this.completions.filtered[0].value == prefix
  246. && !this.completions.filtered[0].snippet)
  247. return this.detach();
  248. this.openPopup(this.editor, prefix, keepPopupPosition);
  249. return;
  250. }
  251. // Save current gatherCompletions session, session is close when a match is insert
  252. var _id = this.gatherCompletionsId;
  253. this.gatherCompletions(this.editor, function(err, results) {
  254. // Only detach if result gathering is finished
  255. var detachIfFinished = function() {
  256. if (!results.finished) return;
  257. return this.detach();
  258. }.bind(this);
  259. var prefix = results.prefix;
  260. var matches = results && results.matches;
  261. if (!matches || !matches.length)
  262. return detachIfFinished();
  263. // Wrong prefix or wrong session -> ignore
  264. if (prefix.indexOf(results.prefix) !== 0 || _id != this.gatherCompletionsId)
  265. return;
  266. this.completions = new FilteredList(matches);
  267. if (this.exactMatch)
  268. this.completions.exactMatch = true;
  269. this.completions.setFilter(prefix);
  270. var filtered = this.completions.filtered;
  271. // No results
  272. if (!filtered.length)
  273. return detachIfFinished();
  274. // One result equals to the prefix
  275. if (filtered.length == 1 && filtered[0].value == prefix && !filtered[0].snippet)
  276. return detachIfFinished();
  277. // Autoinsert if one result
  278. if (this.autoInsert && filtered.length == 1 && results.finished)
  279. return this.insertMatch(filtered[0]);
  280. this.openPopup(this.editor, prefix, keepPopupPosition);
  281. }.bind(this));
  282. };
  283. this.cancelContextMenu = function() {
  284. this.editor.$mouseHandler.cancelContextMenu();
  285. };
  286. this.updateDocTooltip = function() {
  287. var popup = this.popup;
  288. var all = popup.data;
  289. var selected = all && (all[popup.getHoveredRow()] || all[popup.getRow()]);
  290. var doc = null;
  291. if (!selected || !this.editor || !this.popup.isOpen)
  292. return this.hideDocTooltip();
  293. this.editor.completers.some(function(completer) {
  294. if (completer.getDocTooltip)
  295. doc = completer.getDocTooltip(selected);
  296. return doc;
  297. });
  298. if (!doc)
  299. doc = selected;
  300. if (typeof doc == "string")
  301. doc = {docText: doc};
  302. if (!doc || !(doc.docHTML || doc.docText))
  303. return this.hideDocTooltip();
  304. this.showDocTooltip(doc);
  305. };
  306. this.showDocTooltip = function(item) {
  307. if (!this.tooltipNode) {
  308. this.tooltipNode = dom.createElement("div");
  309. this.tooltipNode.className = "autocomplete-tooltip";
  310. this.tooltipNode.style.margin = 0;
  311. this.tooltipNode.style.pointerEvents = "auto";
  312. this.tooltipNode.tabIndex = -1;
  313. this.tooltipNode.onblur = this.blurListener.bind(this);
  314. }
  315. var tooltipNode = this.tooltipNode;
  316. if (item.docHTML) {
  317. tooltipNode.innerHTML = item.docHTML;
  318. } else if (item.docText) {
  319. tooltipNode.textContent = item.docText;
  320. }
  321. if (!tooltipNode.parentNode)
  322. document.body.appendChild(tooltipNode);
  323. var popup = this.popup;
  324. var rect = popup.container.getBoundingClientRect();
  325. tooltipNode.style.top = popup.container.style.top;
  326. tooltipNode.style.bottom = popup.container.style.bottom;
  327. if (window.innerWidth - rect.right < 320) {
  328. tooltipNode.style.right = window.innerWidth - rect.left + "px";
  329. tooltipNode.style.left = "";
  330. } else {
  331. tooltipNode.style.left = (rect.right + 1) + "px";
  332. tooltipNode.style.right = "";
  333. }
  334. tooltipNode.style.display = "block";
  335. };
  336. this.hideDocTooltip = function() {
  337. this.tooltipTimer.cancel();
  338. if (!this.tooltipNode) return;
  339. var el = this.tooltipNode;
  340. if (!this.editor.isFocused() && document.activeElement == el)
  341. this.editor.focus();
  342. this.tooltipNode = null;
  343. if (el.parentNode)
  344. el.parentNode.removeChild(el);
  345. };
  346. }).call(Autocomplete.prototype);
  347. Autocomplete.startCommand = {
  348. name: "startAutocomplete",
  349. exec: function(editor) {
  350. if (editor.useHueAutocompleter) {
  351. var renderer = editor.renderer;
  352. var lineHeight = renderer.layerConfig.lineHeight;
  353. var pos = renderer.$cursorLayer.getPixelPosition(this.base, true);
  354. var rect = editor.container.getBoundingClientRect();
  355. pos.top += rect.top - renderer.layerConfig.offset;
  356. pos.left += rect.left - editor.renderer.scrollLeft;
  357. pos.left += renderer.gutterWidth;
  358. huePubSub.publish('hue.ace.autocompleter.show', { editor: editor, position: pos, lineHeight: lineHeight });
  359. return;
  360. }
  361. if (!editor.completer)
  362. editor.completer = new Autocomplete();
  363. editor.completer.autoInsert = false;
  364. editor.completer.autoSelect = true;
  365. editor.completer.showPopup(editor);
  366. // prevent ctrl-space opening context menu on firefox on mac
  367. editor.completer.cancelContextMenu();
  368. },
  369. bindKey: "Ctrl-Space|Ctrl-Shift-Space|Alt-Space"
  370. };
  371. var FilteredList = function(array, filterText) {
  372. this.all = array;
  373. this.filtered = array;
  374. this.filterText = filterText || "";
  375. this.exactMatch = false;
  376. };
  377. (function(){
  378. this.setFilter = function(str) {
  379. if (str.length > this.filterText && str.lastIndexOf(this.filterText, 0) === 0)
  380. var matches = this.filtered;
  381. else
  382. var matches = this.all;
  383. this.filterText = str;
  384. matches = this.filterCompletions(matches, this.filterText);
  385. matches = matches.sort(function (a, b) {
  386. if (a.completeMatch && ! b.completeMatch) {
  387. return -1;
  388. } else if (! a.completeMatch && b.completeMatch) {
  389. return 1;
  390. } else if (a.completeMatch && b.completeMatch && a.weight && b.weight && b.weight !== a.weight) {
  391. return b.weight - a.weight;
  392. } else if (a.completeMatch && b.completeMatch && a.startsWith && ! b.startsWith) {
  393. return -1;
  394. } else if (a.completeMatch && b.completeMatch && ! a.startsWith && b.startsWith) {
  395. return 1;
  396. }
  397. if (a.prioritizeScore && b.prioritizeScore) {
  398. return b.score - a.score
  399. } else if (a.prioritizeScore) {
  400. return -1;
  401. } else if (b.prioritizeScore) {
  402. return 1;
  403. }
  404. var alpha = 0;
  405. if (a.caption > b.caption) {
  406. alpha = 1;
  407. }
  408. if (a.caption < b.caption) {
  409. alpha = -1;
  410. }
  411. return alpha + b.exactMatch - a.exactMatch || alpha + b.score - a.score;
  412. });
  413. // make unique
  414. var prev = null;
  415. matches = matches.filter(function(item){
  416. var caption = item.snippet || item.caption || item.value;
  417. if (caption === prev) return false;
  418. prev = caption;
  419. return true;
  420. });
  421. this.filtered = matches;
  422. };
  423. this.filterCompletions = function(items, needle) {
  424. var results = [];
  425. var upper = needle.toUpperCase();
  426. var lower = needle.toLowerCase();
  427. loop: for (var i = 0, item; item = items[i]; i++) {
  428. var caption = item.value || item.caption || item.snippet;
  429. if (!caption) continue;
  430. var lastIndex = -1;
  431. var matchMask = 0;
  432. var penalty = 0;
  433. var index, distance;
  434. var completeIndex = 0;
  435. if (this.exactMatch && item.ignoreCase) {
  436. if (upper !== item.upperCaseValue.substr(0, needle.length)) {
  437. continue loop;
  438. }
  439. item.upperCaseMatch = needle === upper;
  440. item.caption = item.upperCaseMatch ? item.upperCaseValue : item.value;
  441. } else if (this.exactMatch && needle !== caption.substr(0, needle.length)) {
  442. continue loop;
  443. } else {
  444. completeIndex = caption.toUpperCase().indexOf(upper);
  445. if (completeIndex > -1) {
  446. lastIndex = completeIndex - 1;
  447. }
  448. for (var j = 0; j < needle.length; j++) {
  449. var i1 = caption.indexOf(lower[j], lastIndex + 1);
  450. var i2 = caption.indexOf(upper[j], lastIndex + 1);
  451. index = (i1 >= 0) ? ((i2 < 0 || i1 < i2) ? i1 : i2) : i2;
  452. if (index < 0)
  453. continue loop;
  454. distance = index - lastIndex - 1;
  455. if (distance > 0) {
  456. penalty += distance;
  457. }
  458. matchMask = matchMask | (1 << index);
  459. lastIndex = index;
  460. }
  461. }
  462. item.matchMask = matchMask;
  463. item.exactMatch = penalty ? 0 : 1;
  464. item.score = (item.score || 0) - penalty;
  465. item.startsWith = completeIndex === 0;
  466. item.completeMatch = completeIndex > -1;
  467. results.push(item);
  468. }
  469. return results;
  470. };
  471. }).call(FilteredList.prototype);
  472. exports.Autocomplete = Autocomplete;
  473. exports.FilteredList = FilteredList;
  474. });