本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

461 lines
17KB

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