autocomplete.js 18 KB

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