1 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
3 // Copyright (c) 2008-2011 by Kris Maglione <maglione.k@gmail.com>
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
11 var CommandWidgets = Class("CommandWidgets", {
12 depends: ["statusline"],
14 init: function init() {
15 let s = "dactyl-statusline-field-";
17 XML.ignoreWhitespace = true;
18 overlay.overlayWindow(window, {
20 eventTarget: commandline
22 append: <e4x xmlns={XUL} xmlns:dactyl={NS}>
23 <vbox id={config.ids.commandContainer}>
24 <vbox class="dactyl-container" hidden="false" collapsed="true">
25 <iframe class="dactyl-completions" id="dactyl-completions-dactyl-commandline" src="dactyl://content/buffer.xhtml"
26 contextmenu="dactyl-contextmenu"
27 flex="1" hidden="false" collapsed="false"
28 highlight="Events" events="mowEvents" />
31 <stack orient="horizontal" align="stretch" class="dactyl-container" id="dactyl-container" highlight="CmdLine CmdCmdLine">
32 <textbox class="plain" id="dactyl-strut" flex="1" crop="end" collapsed="true"/>
33 <textbox class="plain" id="dactyl-mode" flex="1" crop="end"/>
34 <textbox class="plain" id="dactyl-message" flex="1" readonly="true"/>
36 <hbox id="dactyl-commandline" hidden="false" class="dactyl-container" highlight="Normal CmdNormal" collapsed="true">
37 <label id="dactyl-commandline-prompt" class="dactyl-commandline-prompt plain" flex="0" crop="end" value="" collapsed="true"/>
38 <textbox id="dactyl-commandline-command" class="dactyl-commandline-command plain" flex="1" type="input" timeout="100"
43 <vbox class="dactyl-container" hidden="false" collapsed="false" highlight="CmdLine">
44 <textbox id="dactyl-multiline-input" class="plain" flex="1" rows="1" hidden="false" collapsed="true" multiline="true"
45 highlight="Normal Events" events="multilineInputEvents" />
49 <stack id="dactyl-statusline-stack">
50 <hbox id={s + "commandline"} hidden="false" class="dactyl-container" highlight="Normal StatusNormal" collapsed="true">
51 <label id={s + "commandline-prompt"} class="dactyl-commandline-prompt plain" flex="0" crop="end" value="" collapsed="true"/>
52 <textbox id={s + "commandline-command"} class="dactyl-commandline-command plain" flex="1" type="text" timeout="100"
58 before: <e4x xmlns={XUL} xmlns:dactyl={NS}>
59 <toolbar id={statusline.statusBar.id}>
60 <vbox id={"dactyl-completions-" + s + "commandline-container"} class="dactyl-container" hidden="false" collapsed="true">
61 <iframe class="dactyl-completions" id={"dactyl-completions-" + s + "commandline"} src="dactyl://content/buffer.xhtml"
62 contextmenu="dactyl-contextmenu" flex="1" hidden="false" collapsed="false"
63 highlight="Events" events="mowEvents" />
78 getGroup: function () options.get("guioptions").has("C") ? this.commandbar : this.statusbar,
79 getValue: function () this.command
84 defaultGroup: "Normal",
85 getGroup: function () this.commandbar,
86 getValue: function () options.get("guioptions").has("c")
91 test: function test(stack, prev) stack.pop && !isinstance(prev.main, modes.COMMAND_LINE),
92 id: "commandline-command",
93 get: function command_get(elem) {
94 // The long path is because of complications with the
95 // completion preview.
97 return elem.inputField.editor.rootElement.firstChild.textContent;
103 getElement: CommandWidgets.getEditor,
104 getGroup: function (value) this.activeGroup.commandline,
105 onChange: function command_onChange(elem, value) {
106 if (elem.inputField != dactyl.focusedElement)
108 elem.selectionStart = elem.value.length;
109 elem.selectionEnd = elem.value.length;
116 onVisibility: function command_onVisibility(elem, visible) {
124 id: "commandline-prompt",
125 defaultGroup: "CmdPrompt",
126 getGroup: function () this.activeGroup.commandline
131 defaultGroup: "Normal",
132 getElement: CommandWidgets.getEditor,
133 getGroup: function (value) {
134 if (this.command && !options.get("guioptions").has("M"))
135 return this.statusbar;
137 let statusElem = this.statusbar.message;
138 if (value && !value[2] && statusElem.editor && statusElem.editor.rootElement.scrollWidth > statusElem.scrollWidth)
139 return this.commandbar;
140 return this.activeGroup.mode;
146 defaultGroup: "ModeMsg",
147 getGroup: function (value) {
148 if (!options.get("guioptions").has("M"))
149 if (this.commandbar.container.clientHeight == 0 ||
150 value && !this.commandbar.commandline.collapsed)
151 return this.statusbar;
152 return this.commandbar;
155 this.updateVisibility();
157 this.initialized = true;
159 addElement: function addElement(obj) {
161 this.elements[obj.name] = obj;
163 function get(prefix, map, id) (obj.getElement || util.identity)(map[id] || document.getElementById(prefix + id));
165 this.active.__defineGetter__(obj.name, function () self.activeGroup[obj.name][obj.name]);
166 this.activeGroup.__defineGetter__(obj.name, function () self.getGroup(obj.name));
168 memoize(this.statusbar, obj.name, function () get("dactyl-statusline-field-", statusline.widgets, (obj.id || obj.name)));
169 memoize(this.commandbar, obj.name, function () get("dactyl-", {}, (obj.id || obj.name)));
171 if (!(obj.noValue || obj.getValue)) {
172 Object.defineProperty(this, obj.name, Modes.boundProperty({
175 get: function get_widgetValue() {
176 let elem = self.getGroup(obj.name, obj.value)[obj.name];
177 if (obj.value != null)
178 return [obj.value[0],
179 obj.get ? obj.get.call(this, elem) : elem.value]
180 .concat(obj.value.slice(2));
184 set: function set_widgetValue(val) {
185 if (val != null && !isArray(val))
186 val = [obj.defaultGroup || "", val];
189 [this.commandbar, this.statusbar].forEach(function (nodeSet) {
190 let elem = nodeSet[obj.name];
194 highlight.highlightNode(elem,
195 (val[0] != null ? val[0] : obj.defaultGroup)
196 .split(/\s/).filter(util.identity)
197 .map(function (g) g + " " + nodeSet.group + g)
201 obj.onChange.call(this, elem, val);
205 this.updateVisibility();
210 else if (obj.defaultGroup) {
211 [this.commandbar, this.statusbar].forEach(function (nodeSet) {
212 let elem = nodeSet[obj.name];
214 highlight.highlightNode(elem, obj.defaultGroup.split(/\s/)
215 .map(function (g) g + " " + nodeSet.group + g).join(" "));
220 getGroup: function getgroup(name, value) {
221 if (!statusline.visible)
222 return this.commandbar;
223 return this.elements[name].getGroup.call(this, arguments.length > 1 ? value : this[name]);
226 updateVisibility: function updateVisibility() {
227 for (let elem in values(this.elements))
229 let value = elem.getValue ? elem.getValue.call(this)
230 : elem.noValue || this[elem.name];
232 let activeGroup = this.getGroup(elem.name, value);
233 for (let group in values([this.commandbar, this.statusbar])) {
234 let meth, node = group[elem.name];
235 let visible = (value && group === activeGroup);
236 if (node && !node.collapsed == !visible) {
237 node.collapsed = !visible;
238 if (elem.onVisibility)
239 elem.onVisibility.call(this, node, visible);
244 // Hack. Collapse hidden elements in the stack.
245 // Might possibly be better to use a deck and programmatically
246 // choose which element to select.
247 function check(node) {
248 if (DOM(node).style.display === "-moz-stack") {
249 let nodes = Array.filter(node.children, function (n) !n.collapsed && n.boxObject.height);
250 nodes.forEach(function (node, i) node.style.opacity = (i == nodes.length - 1) ? "" : "0");
252 Array.forEach(node.children, check);
254 [this.commandbar.container, this.statusbar.container].forEach(check);
256 if (this.initialized && loaded.mow && mow.visible)
260 active: Class.Memoize(Object),
261 activeGroup: Class.Memoize(Object),
262 commandbar: Class.Memoize(function () ({ group: "Cmd" })),
263 statusbar: Class.Memoize(function () ({ group: "Status" })),
265 _ready: function _ready(elem) {
266 return elem.contentDocument.documentURI === elem.getAttribute("src") &&
267 ["viewable", "complete"].indexOf(elem.contentDocument.readyState) >= 0;
270 _whenReady: function _whenReady(id, init) {
271 let elem = document.getElementById(id);
272 while (!this._ready(elem))
276 init.call(this, elem);
280 completionContainer: Class.Memoize(function () this.completionList.parentNode),
282 contextMenu: Class.Memoize(function () {
283 ["copy", "copylink", "selectall"].forEach(function (tail) {
284 // some host apps use "hostPrefixContext-copy" ids
285 let xpath = "//xul:menuitem[contains(@id, '" + "ontext-" + tail + "') and not(starts-with(@id, 'dactyl-'))]";
286 document.getElementById("dactyl-context-" + tail).style.listStyleImage =
287 DOM(DOM.XPath(xpath, document).snapshotItem(0)).style.listStyleImage;
289 return document.getElementById("dactyl-contextmenu");
292 multilineOutput: Class.Memoize(function () this._whenReady("dactyl-multiline-output", function (elem) {
293 highlight.highlightNode(elem.contentDocument.body, "MOW");
296 multilineInput: Class.Memoize(function () document.getElementById("dactyl-multiline-input")),
298 mowContainer: Class.Memoize(function () document.getElementById("dactyl-multiline-output-container"))
300 getEditor: function getEditor(elem) {
301 elem.inputField.QueryInterface(Ci.nsIDOMNSEditableElement);
306 var CommandMode = Class("CommandMode", {
307 init: function CM_init() {
308 this.keepCommand = userContext.hidden_option_command_afterimage;
311 get autocomplete() options["autocomplete"].length,
313 get command() this.widgets.command[1],
314 set command(val) this.widgets.command = val,
316 get prompt() this._open ? this.widgets.prompt : this._prompt,
319 this.widgets.prompt = val;
324 open: function CM_open(command) {
325 dactyl.assert(isinstance(this.mode, modes.COMMAND_LINE),
326 /*L*/"Not opening command line in non-command-line mode.",
329 this.messageCount = commandline.messageCount;
330 modes.push(this.mode, this.extendedMode, this.closure);
332 this.widgets.active.commandline.collapsed = false;
333 this.widgets.prompt = this.prompt;
334 this.widgets.command = command || "";
338 this.input = this.widgets.active.command.inputField;
340 this.history = CommandLine.History(this.input, this.historyKey, this);
343 this.completions = CommandLine.Completions(this.input, this);
345 if (this.completions && command && commandline.commandSession === this)
346 this.completions.autocompleteTimer.flush(true);
349 get active() this === commandline.commandSession,
351 get holdFocus() this.widgets.active.command.inputField,
353 get mappingSelf() this,
355 get widgets() commandline.widgets,
357 enter: function CM_enter(stack) {
358 commandline.commandSession = this;
359 if (stack.pop && commandline.command) {
360 this.onChange(commandline.command);
361 if (this.completions && stack.pop)
362 this.completions.complete(true, false);
366 leave: function CM_leave(stack) {
368 commandline.commandSession = null;
369 this.input.dactylKeyPress = undefined;
371 let waiting = this.accepted && this.completions && this.completions.waiting;
373 this.completions.onComplete = bind("onSubmit", this);
375 if (this.completions)
376 this.completions.cleanup();
381 commandline.hideCompletions();
383 modes.delay(function () {
384 if (!this.keepCommand || commandline.silent || commandline.quiet)
387 this[this.accepted ? "onSubmit" : "onCancel"](commandline.command);
388 if (commandline.messageCount === this.messageCount)
389 commandline.clearMessage();
395 input: function CM_onInput(event) {
396 if (this.completions) {
397 this.resetCompletions();
399 this.completions.autocompleteTimer.tell(false);
401 this.onChange(commandline.command);
403 keyup: function CM_onKeyUp(event) {
404 let key = DOM.Event.stringify(event);
405 if (/-?Tab>$/.test(key) && this.completions)
406 this.completions.tabTimer.flush();
412 onKeyPress: function CM_onKeyPress(events) {
413 if (this.completions)
414 this.completions.previewClear();
416 return true; /* Pass event */
419 onCancel: function (value) {},
421 onChange: function (value) {},
423 onHistory: function (value) {},
425 onSubmit: function (value) {},
427 resetCompletions: function CM_resetCompletions() {
428 if (this.completions)
429 this.completions.clear();
431 this.history.reset();
435 var CommandExMode = Class("CommandExMode", CommandMode, {
439 historyKey: "command",
441 prompt: ["Normal", ":"],
443 complete: function CEM_complete(context) {
445 context.fork("ex", 0, completion, "ex");
448 context.message = _("error.error", e);
452 onSubmit: function CEM_onSubmit(command) {
453 contexts.withContext({ file: /*L*/"[Command Line]", line: 1 },
454 function _onSubmit() {
455 io.withSavedValues(["readHeredoc"], function _onSubmit() {
456 this.readHeredoc = commandline.readHeredoc;
457 commands.repeat = command;
458 dactyl.execute(command);
464 var CommandPromptMode = Class("CommandPromptMode", CommandMode, {
465 init: function init(prompt, params) {
466 this.prompt = isArray(prompt) ? prompt : ["Question", prompt];
467 update(this, params);
468 init.supercall(this);
471 complete: function CPM_complete(context) {
473 context.forkapply("prompt", 0, this, "completer", Array.slice(arguments, 1));
476 get mode() modes.PROMPT
480 * This class is used for prompting of user input and echoing of messages.
482 * It consists of a prompt and command field be sure to only create objects of
483 * this class when the chrome is ready.
485 var CommandLine = Module("commandline", {
486 init: function init() {
489 this._callbacks = {};
491 memoize(this, "_store", function () storage.newMap("command-history", { store: true, privateData: true }));
493 for (let name in values(["command", "search"]))
494 if (storage.exists("history-" + name)) {
495 let ary = storage.newArray("history-" + name, { store: true, privateData: true });
497 this._store.set(name, [v for ([k, v] in ary)]);
499 this._store.changed();
502 this._messageHistory = { //{{{
505 let max = options["messages"];
507 // resize if 'messages' has changed
508 if (this._messages.length > max)
509 this._messages = this._messages.splice(this._messages.length - max);
511 return this._messages;
514 get length() this._messages.length,
516 clear: function clear() {
520 filter: function filter(fn, self) {
521 this._messages = this._messages.filter(fn, self);
524 add: function add(message) {
528 if (this._messages.length >= options["messages"])
529 this._messages.shift();
531 this._messages.push(update({
532 timestamp: Date.now()
539 "browser.locationChange": function (webProgress, request, uri) {
545 * Determines whether the command line should be visible.
549 get commandVisible() !!this.commandSession,
552 * Ensure that the multiline input widget is the correct size.
554 _autosizeMultilineInputWidget: function _autosizeMultilineInputWidget() {
555 let lines = this.widgets.multilineInput.value.split("\n").length - 1;
557 this.widgets.multilineInput.setAttribute("rows", Math.max(lines, 1));
561 HL_ERRORMSG: "ErrorMsg",
562 HL_MODEMSG: "ModeMsg",
563 HL_MOREMSG: "MoreMsg",
564 HL_QUESTION: "Question",
565 HL_INFOMSG: "InfoMsg",
566 HL_WARNINGMSG: "WarningMsg",
569 FORCE_MULTILINE : 1 << 0,
570 FORCE_SINGLELINE : 1 << 1,
571 DISALLOW_MULTILINE : 1 << 2, // If an echo() should try to use the single line
572 // but output nothing when the MOW is open; when also
573 // FORCE_MULTILINE is given, FORCE_MULTILINE takes precedence
574 APPEND_TO_MESSAGES : 1 << 3, // Add the string to the message history.
575 ACTIVE_WINDOW : 1 << 4, // Only echo in active window.
577 get completionContext() this._completions.context,
580 get silent() this._silent,
583 this.quiet = this.quiet;
587 get quiet() this._quiet,
590 ["commandbar", "statusbar"].forEach(function (nodeSet) {
591 Array.forEach(this.widgets[nodeSet].commandline.children, function (node) {
592 node.style.opacity = this._quiet || this._silent ? "0" : "";
597 widgets: Class.Memoize(function () CommandWidgets()),
599 runSilently: function runSilently(func, self) {
600 this.withSavedValues(["silent"], function () {
606 get completionList() {
607 let node = this.widgets.active.commandline;
608 if (this.commandSession && this.commandSession.completionList)
609 node = document.getElementById(this.commandSession.completionList);
611 if (!node.completionList) {
612 let elem = document.getElementById("dactyl-completions-" + node.id);
613 util.waitFor(bind(this.widgets._ready, null, elem));
615 node.completionList = ItemList(elem);
616 node.completionList.isAboveMow = node.id ==
617 this.widgets.statusbar.commandline.id
619 return node.completionList;
622 hideCompletions: function hideCompletions() {
623 for (let nodeSet in values([this.widgets.statusbar, this.widgets.commandbar]))
624 if (nodeSet.commandline.completionList)
625 nodeSet.commandline.completionList.visible = false;
628 _lastClearable: Modes.boundProperty(),
629 messages: Modes.boundProperty(),
631 multilineInputVisible: Modes.boundProperty({
632 set: function set_miwVisible(value) { this.widgets.multilineInput.collapsed = !value; }
636 if (this.commandVisible && this.widgets.command)
637 return commands.lastCommand = this.widgets.command[1];
638 return commands.lastCommand;
641 if (this.commandVisible && (modes.extended & modes.EX))
642 return this.widgets.command = val;
643 return commands.lastCommand = val;
646 clear: function clear(scroll) {
647 if (!scroll || Date.now() - this._lastEchoTime > 5000)
649 this._lastEchoTime = 0;
651 if (!this.commandSession) {
652 this.widgets.command = null;
653 this.hideCompletions();
656 if (modes.main == modes.OUTPUT_MULTILINE && !mow.isScrollable(1))
659 if (!modes.have(modes.OUTPUT_MULTILINE))
663 clearMessage: function clearMessage() {
664 if (this.widgets.message && this.widgets.message[1] === this._lastClearable)
665 this.widgets.message = null;
669 * Displays the multi-line output of a command, preceded by the last
670 * executed ex command string.
672 * @param {XML} xml The output as an E4X XML object.
674 commandOutput: function commandOutput(xml) {
675 XML.ignoreWhitespace = XML.prettyPrinting = false;
677 this.echo(<><div xmlns={XHTML}>:{this.command}</div>
{xml}</>, this.HIGHLIGHT_NORMAL, this.FORCE_MULTILINE);
679 this.echo(xml, this.HIGHLIGHT_NORMAL, this.FORCE_MULTILINE);
684 * Hides the command line, and shows any status messages that
687 hide: function hide() {
688 this.widgets.command = null;
692 * Display a message in the command-line area.
694 * @param {string} str
695 * @param {string} highlightGroup
696 * @param {boolean} forceSingle If provided, don't let over-long
697 * messages move to the MOW.
699 _echoLine: function echoLine(str, highlightGroup, forceSingle, silent) {
700 this.widgets.message = str ? [highlightGroup, str, forceSingle] : null;
702 dactyl.triggerObserver("echoLine", str, highlightGroup, null, forceSingle);
704 if (!this.commandVisible)
707 let field = this.widgets.active.message.inputField;
708 if (field.value && !forceSingle && field.editor.rootElement.scrollWidth > field.scrollWidth) {
709 this.widgets.message = null;
710 mow.echo(<span highlight="Message">{str}</span>, highlightGroup, true);
717 * Output the given string onto the command line. With no flags, the
718 * message will be shown in the status line if it's short enough to
719 * fit, and contains no new lines, and isn't XML. Otherwise, it will be
722 * @param {string} str
723 * @param {string} highlightGroup The Highlight group for the
726 * @param {number} flags Changes the behavior as follows:
727 * commandline.APPEND_TO_MESSAGES - Causes message to be added to the
728 * messages history, and shown by :messages.
729 * commandline.FORCE_SINGLELINE - Forbids the command from being
730 * pushed to the MOW if it's too long or of there are already
731 * status messages being shown.
732 * commandline.DISALLOW_MULTILINE - Cancels the operation if the MOW
733 * is already visible.
734 * commandline.FORCE_MULTILINE - Forces the message to appear in
738 echo: function echo(data, highlightGroup, flags) {
739 // dactyl.echo uses different order of flags as it omits the highlight group, change commandline.echo argument order? --mst
740 if (this._silent || !this.widgets)
745 highlightGroup = highlightGroup || this.HL_NORMAL;
747 if (flags & this.APPEND_TO_MESSAGES) {
748 let message = isObject(data) ? data : { message: data };
750 // Make sure the memoized message property is an instance property.
752 this._messageHistory.add(update({ highlight: highlightGroup }, message));
753 data = message.message;
756 if ((flags & this.ACTIVE_WINDOW) &&
757 window != services.windowWatcher.activeWindow &&
758 services.windowWatcher.activeWindow.dactyl)
761 if ((flags & this.DISALLOW_MULTILINE) && !this.widgets.mowContainer.collapsed)
764 let single = flags & (this.FORCE_SINGLELINE | this.DISALLOW_MULTILINE);
765 let action = this._echoLine;
767 if ((flags & this.FORCE_MULTILINE) || (/\n/.test(data) || !isinstance(data, [_, "String"])) && !(flags & this.FORCE_SINGLELINE))
768 action = mow.closure.echo;
771 this._lastEcho = null;
773 if (this.widgets.message && this.widgets.message[1] == this._lastEcho)
774 mow.echo(<span highlight="Message">{this._lastEcho}</span>,
775 this.widgets.message[0], true);
777 if (action === this._echoLine && !(flags & this.FORCE_MULTILINE)
778 && !(dactyl.fullyInitialized && this.widgets.mowContainer.collapsed)) {
779 highlightGroup += " Message";
780 action = mow.closure.echo;
782 this._lastEcho = (action == this._echoLine) && data;
785 this._lastClearable = action === this._echoLine && String(data);
786 this._lastEchoTime = (flags & this.FORCE_SINGLELINE) && Date.now();
789 action.call(this, data, highlightGroup, single);
794 * Prompt the user. Sets modes.main to COMMAND_LINE, which the user may
795 * pop at any time to close the prompt.
797 * @param {string} prompt The input prompt to use.
798 * @param {function(string)} callback
799 * @param {Object} extra
800 * @... {function} onChange - A function to be called with the current
801 * input every time it changes.
802 * @... {function(CompletionContext)} completer - A completion function
803 * for the user's input.
804 * @... {string} promptHighlight - The HighlightGroup used for the
805 * prompt. @default "Question"
806 * @... {string} default - The initial value that will be returned
807 * if the user presses <CR> straightaway. @default ""
809 input: function _input(prompt, callback, extra) {
812 CommandPromptMode(prompt, update({ onSubmit: callback }, extra)).open();
815 readHeredoc: function readHeredoc(end) {
817 commandline.inputMultiline(end, function (res) { args = res; });
818 util.waitFor(function () args !== undefined);
823 * Get a multi-line input from a user, up to but not including the line
824 * which matches the given regular expression. Then execute the
825 * callback with that string as a parameter.
827 * @param {string} end
828 * @param {function(string)} callback
830 // FIXME: Buggy, especially when pasting.
831 inputMultiline: function inputMultiline(end, callback) {
832 let cmd = this.command;
834 end: "\n" + end + "\n",
838 modes.push(modes.INPUT_MULTILINE, null, {
840 leave: function leave() {
848 this._echoLine(cmd, this.HL_NORMAL);
850 // save the arguments, they are needed in the event handler onKeyPress
852 this.multilineInputVisible = true;
853 this.widgets.multilineInput.value = "";
854 this._autosizeMultilineInputWidget();
856 this.timeout(function () { dactyl.focus(this.widgets.multilineInput); }, 10);
859 get commandMode() this.commandSession && isinstance(modes.main, modes.COMMAND_LINE),
862 iter(CommandMode.prototype.events).map(
863 function ([event, handler]) [
864 event, function (event) {
865 if (this.commandMode)
866 handler.call(this.commandSession, event);
870 focus: function onFocus(event) {
871 if (!this.commandSession
872 && event.originalTarget === this.widgets.active.command.inputField) {
880 get mowEvents() mow.events,
883 * Multiline input events, they will come straight from
884 * #dactyl-multiline-input in the XUL.
886 * @param {Event} event
888 multilineInputEvents: {
889 blur: function onBlur(event) {
890 if (modes.main == modes.INPUT_MULTILINE)
891 this.timeout(function () {
892 dactyl.focus(this.widgets.multilineInput.inputField);
895 input: function onInput(event) {
896 this._autosizeMultilineInputWidget();
900 updateOutputHeight: deprecated("mow.resize", function updateOutputHeight(open, extra) mow.resize(open, extra)),
902 withOutputToString: function withOutputToString(fn, self) {
903 dactyl.registerObserver("echoLine", observe, true);
904 dactyl.registerObserver("echoMultiline", observe, true);
907 function observe(str, highlight, dom) {
908 output.push(dom && !isString(str) ? dom : str);
911 this.savingOutput = true;
912 dactyl.trapErrors.apply(dactyl, [fn, self].concat(Array.slice(arguments, 2)));
913 this.savingOutput = false;
914 return output.map(function (elem) elem instanceof Node ? DOM.stringify(elem) : elem)
919 * A class for managing the history of an input field.
921 * @param {HTMLInputElement} inputField
922 * @param {string} mode The mode for which we need history.
924 History: Class("History", {
925 init: function init(inputField, mode, session) {
927 this.input = inputField;
929 this.session = session;
931 get store() commandline._store.get(this.mode, []),
932 set store(ary) { commandline._store.set(this.mode, ary); },
934 * Reset the history index to the first entry.
936 reset: function reset() {
940 * Save the last entry to the permanent store. All duplicate entries
941 * are removed and the list is truncated, if necessary.
943 save: function save() {
944 if (events.feedingKeys)
946 let str = this.input.value;
947 if (/^\s*$/.test(str))
949 this.store = this.store.filter(function (line) (line.value || line) != str);
950 dactyl.trapErrors(function () {
951 this.store.push({ value: str, timestamp: Date.now()*1000, privateData: this.checkPrivate(str) });
953 this.store = this.store.slice(Math.max(0, this.store.length - options["history"]));
956 * @property {function} Returns whether a data item should be
957 * considered private.
959 checkPrivate: function checkPrivate(str) {
960 // Not really the ideal place for this check.
961 if (this.mode == "command")
962 return commands.hasPrivateData(str);
966 * Replace the current input field value.
968 * @param {string} val The new value.
970 replace: function replace(val) {
971 editor.withSavedValues(["skipSave"], function () {
972 editor.skipSave = true;
974 this.input.dactylKeyPress = undefined;
975 if (this.completions)
976 this.completions.previewClear();
977 this.input.value = val;
978 this.session.onHistory(val);
983 * Move forward or backward in history.
985 * @param {boolean} backward Direction to move.
986 * @param {boolean} matchCurrent Search for matches starting
987 * with the current input value.
989 select: function select(backward, matchCurrent) {
990 // always reset the tab completion if we use up/down keys
991 if (this.session.completions)
992 this.session.completions.reset();
994 let diff = backward ? -1 : 1;
996 if (this.index == null) {
997 this.original = this.input.value;
998 this.index = this.store.length;
1001 // search the history for the first item matching the current
1002 // command-line string
1005 if (this.index < 0 || this.index > this.store.length) {
1006 this.index = Math.constrain(this.index, 0, this.store.length);
1008 // I don't know why this kludge is needed. It
1009 // prevents the caret from moving to the end of
1011 if (this.input.value == "") {
1012 this.input.value = " ";
1013 this.input.value = "";
1018 let hist = this.store[this.index];
1019 // user pressed DOWN when there is no newer history item
1021 hist = this.original;
1023 hist = (hist.value || hist);
1025 if (!matchCurrent || hist.substr(0, this.original.length) == this.original) {
1034 * A class for tab completions on an input field.
1036 * @param {Object} input
1038 Completions: Class("Completions", {
1047 init: function init(input, session) {
1050 this.context = CompletionContext(input.QueryInterface(Ci.nsIDOMNSEditableElement).editor);
1051 this.context.onUpdate = function onUpdate() { self.asyncUpdate(this); };
1053 this.editor = input.editor;
1055 this.session = session;
1057 this.wildmode = options.get("wildmode");
1058 this.wildtypes = this.wildmode.value;
1060 this.itemList = commandline.completionList;
1061 this.itemList.open(this.context);
1063 dactyl.registerObserver("events.doneFeeding", this.closure.onDoneFeeding, true);
1065 this.autocompleteTimer = Timer(200, 500, function autocompleteTell(tabPressed) {
1066 if (events.feedingKeys && !tabPressed)
1067 this.ignoredCount++;
1068 else if (this.session.autocomplete) {
1069 this.itemList.visible = true;
1070 this.complete(true, false);
1074 this.tabTimer = Timer(0, 0, function tabTell(event) {
1075 let tabCount = this.tabCount;
1077 this.tab(tabCount, event.altKey && options["altwildmode"]);
1088 onDoneFeeding: function onDoneFeeding() {
1089 if (this.ignoredCount)
1090 this.autocompleteTimer.flush(true);
1091 this.ignoredCount = 0;
1097 onTab: function onTab(event) {
1098 this.tabCount += event.shiftKey ? -1 : 1;
1099 this.tabTimer.tell(event);
1102 get activeContexts() this.context.contextList
1103 .filter(function (c) c.items.length || c.incomplete),
1106 * Returns the current completion string relative to the
1107 * offset of the currently selected context.
1110 let offset = this.selected ? this.selected[0].offset : this.start;
1111 return commandline.command.slice(offset, this.caret);
1115 * Updates the input field from *offset* to {@link #caret}
1116 * with the value *value*. Afterward, the caret is moved
1117 * just after the end of the updated text.
1119 * @param {number} offset The offset in the original input
1120 * string at which to insert *value*.
1121 * @param {string} value The value to insert.
1123 setCompletion: function setCompletion(offset, value) {
1124 editor.withSavedValues(["skipSave"], function () {
1125 editor.skipSave = true;
1126 this.previewClear();
1129 var [input, caret] = [this.originalValue, this.originalCaret];
1131 input = this.getCompletion(offset, value);
1132 caret = offset + value.length;
1135 // Change the completion text.
1136 // The second line is a hack to deal with some substring
1137 // preview corner cases.
1138 commandline.widgets.active.command.value = input;
1139 this.editor.selection.focusNode.textContent = input;
1142 this._caret = this.caret;
1144 this.input.dactylKeyPress = undefined;
1149 * For a given offset and completion string, returns the
1150 * full input value after selecting that item.
1152 * @param {number} offset The offset at which to insert the
1154 * @param {string} value The value to insert.
1155 * @returns {string};
1157 getCompletion: function getCompletion(offset, value) {
1158 return this.originalValue.substr(0, offset)
1160 + this.originalValue.substr(this.originalCaret);
1163 get selected() this.itemList.selected,
1164 set selected(tuple) {
1165 if (!array.equals(tuple || [],
1166 this.itemList.selected || []))
1167 this.itemList.select(tuple);
1170 this.setCompletion(null);
1172 let [ctxt, idx] = tuple;
1173 this.setCompletion(ctxt.offset, ctxt.items[idx].result);
1177 get caret() this.editor.selection.getRangeAt(0).startOffset,
1179 this.editor.selection.collapse(this.editor.rootElement.firstChild, offset);
1182 get start() this.context.allItems.start,
1184 get items() this.context.allItems.items,
1186 get substring() this.context.longestAllSubstring,
1188 get wildtype() this.wildtypes[this.wildIndex] || "",
1191 * Cleanup resources used by this completion session. This
1192 * instance should not be used again once this method is
1195 cleanup: function cleanup() {
1196 dactyl.unregisterObserver("events.doneFeeding", this.closure.onDoneFeeding);
1197 this.previewClear();
1199 this.tabTimer.reset();
1200 this.autocompleteTimer.reset();
1201 if (!this.onComplete)
1202 this.context.cancelAll();
1204 this.itemList.visible = false;
1205 this.input.dactylKeyPress = undefined;
1206 this.hasQuit = true;
1210 * Run the completer.
1212 * @param {boolean} show Passed to {@link #reset}.
1213 * @param {boolean} tabPressed Should be set to true if, and
1214 * only if, this function is being called in response
1217 complete: function complete(show, tabPressed) {
1218 this.session.ignoredCount = 0;
1220 this.context.reset();
1221 this.context.tabPressed = tabPressed;
1223 this.session.complete(this.context);
1224 if (!this.session.active)
1227 this.reset(show, tabPressed);
1229 this._caret = this.caret;
1233 * Clear any preview string and cancel any pending
1234 * asynchronous context. Called when there is further input
1237 clear: function clear() {
1238 this.context.cancelAll();
1239 this.wildIndex = -1;
1240 this.previewClear();
1244 * Saves the current input state. To be called before an
1245 * item is selected in a new set of completion responses.
1248 saveInput: function saveInput() {
1249 this.originalValue = this.context.value;
1250 this.originalCaret = this.caret;
1254 * Resets the completion state.
1256 * @param {boolean} show If true and options allow the
1257 * completion list to be shown, show it.
1259 reset: function reset(show) {
1260 this.waiting = null;
1261 this.wildIndex = -1;
1266 this.itemList.update();
1267 this.context.updateAsync = true;
1268 if (this.haveType("list"))
1269 this.itemList.visible = true;
1277 * Calls when an asynchronous completion context has new
1278 * results to return.
1280 * @param {CompletionContext} context The changed context.
1283 asyncUpdate: function asyncUpdate(context) {
1285 let item = this.getItem(this.waiting);
1286 if (item && this.waiting && this.onComplete) {
1287 util.trapErrors("onComplete", this,
1288 this.getCompletion(this.waiting[0].offset,
1290 this.waiting = null;
1291 this.context.cancelAll();
1296 let value = this.editor.selection.focusNode.textContent;
1299 if (this.itemList.visible)
1300 this.itemList.updateContext(context);
1302 if (this.waiting && this.waiting[0] == context)
1303 this.select(this.waiting);
1304 else if (!this.waiting) {
1305 let cursor = this.selected;
1306 if (cursor && cursor[0] == context) {
1307 let item = this.getItem(cursor);
1308 if (!item || this.completion != item.result)
1309 this.itemList.select(null);
1317 * Returns true if the currently selected 'wildmode' index
1318 * has the given completion type.
1320 haveType: function haveType(type)
1321 this.wildmode.checkHas(this.wildtype, type == "first" ? "" : type),
1324 * Returns the completion item for the given selection
1327 * @param {[CompletionContext,number]} tuple The spec of the
1329 * @default {@link #selected}
1332 getItem: function getItem(tuple) {
1333 tuple = tuple || this.selected;
1334 return tuple && tuple[0] && tuple[0].items[tuple[1]];
1338 * Returns a tuple representing the next item, at the given
1339 * *offset*, from *tuple*.
1341 * @param {[CompletionContext,number]} tuple The offset from
1343 * @default {@link #selected}
1344 * @param {number} offset The positive or negative offset to
1347 * @param {boolean} noWrap If true, and the search would
1348 * wrap, return null.
1350 nextItem: function nextItem(tuple, offset, noWrap) {
1351 if (tuple === undefined)
1352 tuple = this.selected;
1354 return this.itemList.getRelativeItem(offset || 1, tuple, noWrap);
1358 * The last previewed substring.
1364 * Displays a preview of the text provided by the next <Tab>
1365 * press if the current input is an anchored substring of
1368 preview: function preview() {
1369 this.previewClear();
1370 if (this.wildIndex < 0 || this.caret < this.input.value.length
1371 || !this.activeContexts.length || this.waiting)
1375 switch (this.wildtype.replace(/.*:/, "")) {
1377 var cursor = this.nextItem(null);
1380 if (this.items.length > 1) {
1381 substring = this.substring;
1386 cursor = this.nextItem();
1390 substring = this.getItem(cursor).result;
1392 // Don't show 1-character substrings unless we've just hit backspace
1393 if (substring.length < 2 && this.lastSubstring.indexOf(substring))
1396 this.lastSubstring = substring;
1398 let value = this.completion;
1399 if (util.compareIgnoreCase(value, substring.substr(0, value.length)))
1402 substring = substring.substr(value.length);
1403 this.removeSubstring = substring;
1405 let node = DOM.fromXML(<span highlight="Preview">{substring}</span>,
1408 this.withSavedValues(["caret"], function () {
1409 this.editor.insertNode(node, this.editor.rootElement, 1);
1414 * Clears the currently displayed next-<Tab> preview string.
1416 previewClear: function previewClear() {
1417 let node = this.editor.rootElement.firstChild;
1418 if (node && node.nextSibling) {
1420 DOM(node.nextSibling).remove();
1423 node.nextSibling.textContent = "";
1426 else if (this.removeSubstring) {
1427 let str = this.removeSubstring;
1428 let cmd = commandline.widgets.active.command.value;
1429 if (cmd.substr(cmd.length - str.length) == str)
1430 commandline.widgets.active.command.value = cmd.substr(0, cmd.length - str.length);
1432 delete this.removeSubstring;
1436 * Selects a completion based on the value of *idx*.
1438 * @param {[CompletionContext,number]|const object} The
1439 * (context,index) tuple of the item to select, or an
1440 * offset constant from this object.
1441 * @param {number} count When given an offset constant,
1442 * select *count* units.
1444 * @param {boolean} fromTab If true, this function was
1445 * called by {@link #tab}.
1448 select: function select(idx, count, fromTab) {
1454 idx = this.nextItem(this.waiting || this.selected,
1455 idx == this.UP ? -count : count,
1460 case this.CTXT_DOWN:
1461 let groups = this.itemList.activeGroups;
1462 let i = Math.max(0, groups.indexOf(this.itemList.selectedGroup));
1464 i += idx == this.CTXT_DOWN ? 1 : -1;
1470 idx = [groups[i].context, 0];
1474 case this.PAGE_DOWN:
1475 idx = this.itemList.getRelativePage(idx == this.PAGE_DOWN ? 1 : -1);
1487 this.wildIndex = this.wildtypes.length - 1;
1489 if (idx && idx[1] >= idx[0].items.length) {
1491 statusline.progress = _("completion.waitingForResults");
1495 this.waiting = null;
1497 this.itemList.select(idx, null, position);
1498 this.selected = idx;
1502 if (this.selected == null)
1503 statusline.progress = "";
1505 statusline.progress = _("completion.matchIndex",
1506 this.itemList.getOffset(idx),
1507 this.itemList.itemCount);
1511 * Selects a completion result based on the 'wildmode'
1512 * option, or the value of the *wildmode* parameter.
1514 * @param {number} offset The positive or negative number of
1515 * tab presses to process.
1516 * @param {[string]} wildmode A 'wildmode' value to
1517 * substitute for the value of the 'wildmode' option.
1520 tab: function tab(offset, wildmode) {
1521 this.autocompleteTimer.flush();
1522 this.ignoredCount = 0;
1524 if (this._caret != this.caret)
1526 this._caret = this.caret;
1528 // Check if we need to run the completer.
1529 if (this.context.waitingForTab || this.wildIndex == -1)
1530 this.complete(true, true);
1532 this.wildtypes = wildmode || options["wildmode"];
1533 let count = Math.abs(offset);
1534 let steps = Math.constrain(this.wildtypes.length - this.wildIndex,
1536 count = Math.max(1, count - steps);
1539 this.wildIndex = Math.min(this.wildIndex, this.wildtypes.length - 1);
1540 switch (this.wildtype.replace(/.*:/, "")) {
1542 this.select(this.nextItem(null));
1545 if (this.itemList.itemCount > 1) {
1546 if (this.substring && this.substring.length > this.completion.length)
1547 this.setCompletion(this.start, this.substring);
1552 let c = steps ? 1 : count;
1553 this.select(offset < 0 ? this.UP : this.DOWN, c, true);
1557 if (this.haveType("list"))
1558 this.itemList.visible = true;
1563 if (this.items.length == 0 && !this.waiting)
1569 * Evaluate a JavaScript expression and return a string suitable
1572 * @param {string} arg
1573 * @param {boolean} useColor When true, the result is a
1574 * highlighted XML object.
1576 echoArgumentToString: function (arg, useColor) {
1580 arg = dactyl.userEval(arg);
1582 arg = util.objectToString(arg, useColor);
1583 else if (callable(arg))
1584 arg = String.replace(arg, "/* use strict */ \n", "/* use strict */ ");
1585 else if (!isString(arg) && useColor)
1586 arg = template.highlight(arg);
1590 commands: function init_commands() {
1594 description: "Echo the expression",
1599 description: "Echo the expression as an error message",
1600 action: dactyl.echoerr
1604 description: "Echo the expression as an informational message",
1605 action: dactyl.echomsg
1607 ].forEach(function (command) {
1608 commands.add([command.name],
1609 command.description,
1611 command.action(CommandLine.echoArgumentToString(args[0] || "", true));
1613 completer: function (context) completion.javascript(context),
1618 commands.add(["mes[sages]"],
1619 "Display previously shown messages",
1621 // TODO: are all messages single line? Some display an aggregation
1622 // of single line messages at least. E.g. :source
1623 if (commandline._messageHistory.length == 1) {
1624 let message = commandline._messageHistory.messages[0];
1625 commandline.echo(message.message, message.highlight, commandline.FORCE_SINGLELINE);
1627 else if (commandline._messageHistory.length > 1) {
1628 XML.ignoreWhitespace = false;
1629 commandline.commandOutput(
1630 template.map(commandline._messageHistory.messages, function (message)
1631 <div highlight={message.highlight + " Message"}>{message.message}</div>));
1636 commands.add(["messc[lear]"],
1637 "Clear the message history",
1638 function () { commandline._messageHistory.clear(); },
1641 commands.add(["sil[ent]"],
1642 "Run a command silently",
1644 commandline.runSilently(function () commands.execute(args[0] || "", null, true));
1646 completer: function (context) completion.ex(context),
1651 modes: function initModes() {
1652 initModes.require("editor");
1654 modes.addMode("COMMAND_LINE", {
1656 description: "Active when the command line is focused",
1659 get mappingSelf() commandline.commandSession
1661 // this._extended modes, can include multiple modes, and even main modes
1662 modes.addMode("EX", {
1663 description: "Ex command mode, active when the command line is open for Ex commands",
1664 bases: [modes.COMMAND_LINE]
1666 modes.addMode("PROMPT", {
1667 description: "Active when a prompt is open in the command line",
1668 bases: [modes.COMMAND_LINE]
1671 modes.addMode("INPUT_MULTILINE", {
1672 bases: [modes.INSERT]
1675 mappings: function init_mappings() {
1677 mappings.add([modes.COMMAND],
1678 [":"], "Enter Command Line mode",
1679 function () { CommandExMode().open(""); });
1681 mappings.add([modes.INPUT_MULTILINE],
1682 ["<Return>", "<C-j>", "<C-m>"], "Begin a new line",
1683 function ({ self }) {
1684 let text = "\n" + commandline.widgets.multilineInput
1685 .value.substr(0, commandline.widgets.multilineInput.selectionStart)
1688 let index = text.indexOf(self.end);
1691 text = text.substring(1, index);
1694 return function () self.callback.call(commandline, text);
1699 let bind = function bind()
1700 mappings.add.apply(mappings, [[modes.COMMAND_LINE]].concat(Array.slice(arguments)))
1702 bind(["<Esc>", "<C-[>"], "Stop waiting for completions or exit Command Line mode",
1703 function ({ self }) {
1704 if (self.completions && self.completions.waiting)
1705 self.completions.waiting = null;
1710 // Any "non-keyword" character triggers abbreviation expansion
1711 // TODO: Add "<CR>" and "<Tab>" to this list
1712 // At the moment, adding "<Tab>" breaks tab completion. Adding
1713 // "<CR>" has no effect.
1714 // TODO: Make non-keyword recognition smarter so that there need not
1715 // be two lists of the same characters (one here and a regexp in
1717 bind(["<Space>", '"', "'"], "Expand command line abbreviation",
1718 function ({ self }) {
1719 self.resetCompletions();
1720 editor.expandAbbreviation(modes.COMMAND_LINE);
1724 bind(["<Return>", "<C-j>", "<C-m>"], "Accept the current input",
1725 function ({ self }) {
1726 if (self.completions)
1727 self.completions.tabTimer.flush();
1729 let command = commandline.command;
1731 self.accepted = true;
1732 return function () { modes.pop(); };
1736 [["<Up>", "<A-p>", "<cmd-prev-match>"], "previous matching", true, true],
1737 [["<S-Up>", "<C-p>", "<cmd-prev>"], "previous", true, false],
1738 [["<Down>", "<A-n>", "<cmd-next-match>"], "next matching", false, true],
1739 [["<S-Down>", "<C-n>", "<cmd-next>"], "next", false, false]
1740 ].forEach(function ([keys, desc, up, search]) {
1741 bind(keys, "Recall the " + desc + " command line from the history list",
1742 function ({ self }) {
1743 dactyl.assert(self.history);
1744 self.history.select(up, search);
1748 bind(["<A-Tab>", "<Tab>", "<A-compl-next>", "<compl-next>"],
1749 "Select the next matching completion item",
1750 function ({ keypressEvents, self }) {
1751 dactyl.assert(self.completions);
1752 self.completions.onTab(keypressEvents[0]);
1755 bind(["<A-S-Tab>", "<S-Tab>", "<A-compl-prev>", "<compl-prev>"],
1756 "Select the previous matching completion item",
1757 function ({ keypressEvents, self }) {
1758 dactyl.assert(self.completions);
1759 self.completions.onTab(keypressEvents[0]);
1762 bind(["<C-Tab>", "<A-f>", "<compl-next-group>"],
1763 "Select the next matching completion group",
1764 function ({ keypressEvents, self }) {
1765 dactyl.assert(self.completions);
1766 self.completions.tabTimer.flush();
1767 self.completions.select(self.completions.CTXT_DOWN);
1770 bind(["<C-S-Tab>", "<A-S-f>", "<compl-prev-group>"],
1771 "Select the previous matching completion group",
1772 function ({ keypressEvents, self }) {
1773 dactyl.assert(self.completions);
1774 self.completions.tabTimer.flush();
1775 self.completions.select(self.completions.CTXT_UP);
1778 bind(["<C-f>", "<PageDown>", "<compl-next-page>"],
1779 "Select the next page of completions",
1780 function ({ keypressEvents, self }) {
1781 dactyl.assert(self.completions);
1782 self.completions.tabTimer.flush();
1783 self.completions.select(self.completions.PAGE_DOWN);
1786 bind(["<C-b>", "<PageUp>", "<compl-prev-page>"],
1787 "Select the previous page of completions",
1788 function ({ keypressEvents, self }) {
1789 dactyl.assert(self.completions);
1790 self.completions.tabTimer.flush();
1791 self.completions.select(self.completions.PAGE_UP);
1794 bind(["<BS>", "<C-h>"], "Delete the previous character",
1796 if (!commandline.command)
1802 bind(["<C-]>", "<C-5>"], "Expand command line abbreviation",
1803 function () { editor.expandAbbreviation(modes.COMMAND_LINE); });
1805 options: function init_options() {
1806 options.add(["history", "hi"],
1807 "Number of Ex commands and search patterns to store in the command-line history",
1809 { validator: function (value) value >= 0 });
1811 options.add(["maxitems"],
1812 "Maximum number of completion items to display at once",
1814 { validator: function (value) value >= 1 });
1816 options.add(["messages", "msgs"],
1817 "Number of messages to store in the :messages history",
1819 { validator: function (value) value >= 0 });
1821 sanitizer: function init_sanitizer() {
1822 sanitizer.addItem("commandline", {
1823 description: "Command-line and search history",
1825 action: function (timespan, host) {
1826 let store = commandline._store;
1827 for (let [k, v] in store) {
1829 store.set(k, v.filter(function (item)
1830 !(timespan.contains(item.timestamp) && (!host || commands.hasDomain(item.value, host)))));
1832 store.set(k, v.filter(function (item) !timespan.contains(item.timestamp)));
1836 // Delete history-like items from the commandline and messages on history purge
1837 sanitizer.addItem("history", {
1838 action: function (timespan, host) {
1839 commandline._store.set("command",
1840 commandline._store.get("command", []).filter(function (item)
1841 !(timespan.contains(item.timestamp) && (host ? commands.hasDomain(item.value, host)
1842 : item.privateData))));
1844 commandline._messageHistory.filter(function (item) !timespan.contains(item.timestamp * 1000) ||
1845 !item.domains && !item.privateData ||
1846 host && (!item.domains || !item.domains.some(function (d) util.isSubdomain(d, host))));
1849 sanitizer.addItem("messages", {
1850 description: "Saved :messages",
1851 action: function (timespan, host) {
1852 commandline._messageHistory.filter(function (item) !timespan.contains(item.timestamp * 1000) ||
1853 host && (!item.domains || !item.domains.some(function (d) util.isSubdomain(d, host))));
1860 * The list which is used for the completion box.
1862 * @param {string} id The id of the iframe which will display the list. It
1863 * must be in its own container element, whose height it will update as
1867 var ItemList = Class("ItemList", {
1870 init: function init(frame) {
1873 this.doc = frame.contentDocument;
1874 this.win = frame.contentWindow;
1875 this.body = this.doc.body;
1876 this.container = frame.parentNode;
1878 highlight.highlightNode(this.doc.body, "Comp");
1880 this._onResize = Timer(20, 400, function _onResize(event) {
1882 this.onResize(event);
1884 this._resize = Timer(20, 400, function _resize(flags) {
1889 DOM(this.win).resize(this._onResize.closure.tell);
1893 <div highlight="Normal" style="white-space: nowrap" key="root">
1895 <div highlight="Completions" key="noCompletions"><span highlight="Title">{_("completion.noCompletions")}</span></div>
1896 <div key="completions"/>
1899 <div highlight="Completions">{
1900 template.map(util.range(0, options["maxitems"] * 2), function (i)
1901 <div highlight="CompItem NonText"><li>~</li></div>)
1906 get itemCount() this.context.contextList.reduce(function (acc, ctxt) acc + ctxt.items.length, 0),
1908 get visible() !this.container.collapsed,
1909 set visible(val) this.container.collapsed = !val,
1911 get activeGroups() this.context.contextList
1912 .filter(function (c) c.items.length || c.message || c.incomplete)
1913 .map(this.getGroup, this),
1915 get selected() let (g = this.selectedGroup) g && g.selectedIdx != null
1916 ? [g.context, g.selectedIdx] : null,
1918 getRelativeItem: function getRelativeItem(offset, tuple, noWrap) {
1919 let groups = this.activeGroups;
1923 let group = this.selectedGroup || groups[0];
1924 let start = group.selectedIdx || 0;
1925 if (tuple === null) { // Kludge.
1927 tuple = [this.activeGroups[0], -1];
1929 let group = this.activeGroups.slice(-1)[0];
1930 tuple = [group, group.itemCount];
1934 [group, start] = tuple;
1936 group = this.getGroup(group);
1938 start = (group.offsets.start + start + offset);
1940 start %= this.itemCount || 1;
1941 if (start < 0 && (!noWrap || arguments[1] === null))
1942 start += this.itemCount;
1944 if (noWrap && offset > 0) {
1945 // Check if we've passed any incomplete contexts
1947 let i = groups.indexOf(group);
1948 for (; i < groups.length; i++) {
1949 let end = groups[i].offsets.start + groups[i].itemCount;
1950 if (start >= end && groups[i].context.incomplete)
1951 return [groups[i].context, start - groups[i].offsets.start];
1958 if (start < 0 || start >= this.itemCount)
1961 group = array.nth(groups, function (g) let (i = start - g.offsets.start) i >= 0 && i < g.itemCount, 0)
1962 return [group.context, start - group.offsets.start];
1965 getRelativePage: function getRelativePage(offset, tuple, noWrap) {
1966 offset *= this.maxItems;
1967 // Try once with wrapping disabled.
1968 let res = this.getRelativeItem(offset, tuple, true);
1972 let sign = offset / Math.abs(offset);
1974 let off = this.getOffset(tuple === null ? null : tuple || this.selected);
1976 // Unselected. Defer to getRelativeItem.
1977 res = this.getRelativeItem(offset, null, noWrap);
1978 else if (~[0, this.itemCount - 1].indexOf(off))
1979 // At start or end. Jump to other end.
1980 res = this.getRelativeItem(sign, null, noWrap);
1982 // Wrapped. Go to beginning or end.
1983 res = this.getRelativeItem(-sign, null);
1989 * Initializes the ItemList for use with a new root completion
1992 * @param {CompletionContext} context The new root context.
1994 open: function open(context) {
1995 this.context = context;
1997 this.container.height = 0;
1999 this.maxItems = options["maxitems"];
2001 DOM(this.rootXML, this.doc, this.nodes)
2002 .appendTo(DOM(this.body).empty());
2008 * Updates the absolute result indices of all groups after
2009 * results have changed.
2012 updateOffsets: function updateOffsets() {
2013 let total = this.itemCount;
2015 for (let group in values(this.activeGroups)) {
2016 group.offsets = { start: count, end: total - count - group.itemCount };
2017 count += group.itemCount;
2022 * Updates the set and state of active groups for a new set of
2023 * completion results.
2025 update: function update() {
2026 DOM(this.nodes.completions).empty();
2028 let container = DOM(this.nodes.completions);
2029 let groups = this.activeGroups;
2030 for (let group in values(groups)) {
2032 container.append(group.nodes.root);
2035 this.updateOffsets();
2037 DOM(this.nodes.noCompletions).toggle(!groups.length);
2039 this.startPos = null;
2040 this.select(groups[0] && groups[0].context, null);
2042 this._resize.tell();
2046 * Updates the group for *context* after an asynchronous update
2049 * @param {CompletionContext} context The context which has
2052 updateContext: function updateContext(context) {
2053 let group = this.getGroup(context);
2054 this.updateOffsets();
2056 if (~this.activeGroups.indexOf(group))
2059 DOM(group.nodes.root).remove();
2060 if (this.selectedGroup == group)
2061 this.selectedGroup = null;
2064 let g = this.selectedGroup;
2065 this.select(g, g && g.selectedIdx);
2069 * Updates the DOM to reflect the current state of all groups.
2072 draw: function draw() {
2073 for (let group in values(this.activeGroups))
2076 // We need to collect all of the rescrolling functions in
2077 // one go, as the height calculation that they need to do
2078 // would force a reflow after each DOM modification.
2079 this.activeGroups.filter(function (g) !g.collapsed)
2080 .map(function (g) g.rescrollFunc)
2084 this.win.scrollTo(0, 0);
2086 this._resize.tell(ItemList.RESIZE_BRIEF);
2089 onResize: function onResize() {
2090 if (this.selectedGroup)
2091 this.selectedGroup.rescrollFunc();
2097 * Resizes the list after an update.
2100 resize: function resize(flags) {
2101 let { completions, root } = this.nodes;
2104 root.style.minWidth = document.getElementById("dactyl-commandline").scrollWidth + "px";
2106 let { minHeight } = this;
2107 if (mow.visible && this.isAboveMow) // Kludge.
2108 minHeight -= mow.wantedHeight;
2110 let needed = this.win.scrollY + DOM(completions).rect.bottom;
2111 this.minHeight = Math.max(minHeight, needed);
2114 root.style.minWidth = "";
2116 let height = this.visible ? parseFloat(this.container.height) : 0;
2117 if (this.minHeight <= minHeight || !mow.visible)
2118 this.container.height = Math.min(this.minHeight,
2119 height + config.outputHeight - mow.spaceNeeded);
2121 // FIXME: Belongs elsewhere.
2122 mow.resize(false, Math.max(0, this.minHeight - this.container.height));
2124 this.container.height = this.minHeight - mow.spaceNeeded;
2126 this.timeout(function () {
2127 this.container.height -= mow.spaceNeeded;
2133 * Selects the item at the given *group* and *index*.
2135 * @param {CompletionContext|[CompletionContext,number]} *group* The
2136 * completion context to select, or a tuple specifying the
2137 * context and item index.
2138 * @param {number} index The item index in *group* to select.
2139 * @param {number} position If non-null, try to position the
2140 * selected item at the *position*th row from the top of
2141 * the screen. Note that at least {@link #CONTEXT_LINES}
2142 * lines will be visible above and below the selected item
2143 * unless there aren't enough results to make this possible.
2146 select: function select(group, index, position) {
2148 [group, index] = group;
2150 group = this.getGroup(group);
2152 if (this.selectedGroup && (!group || group != this.selectedGroup))
2153 this.selectedGroup.selectedIdx = null;
2155 this.selectedGroup = group;
2158 group.selectedIdx = index;
2160 let groups = this.activeGroups;
2162 if (position != null || !this.startPos && groups.length)
2163 this.startPos = [group || groups[0], position || 0];
2165 if (groups.length) {
2166 group = group || groups[0];
2167 let idx = groups.indexOf(group);
2169 let start = this.startPos[0].getOffset(this.startPos[1]);
2171 let idx = group.selectedIdx || 0;
2172 let off = group.getOffset(idx);
2174 start = Math.constrain(start,
2175 off + Math.min(this.CONTEXT_LINES, group.itemCount - idx + group.offsets.end)
2176 - this.maxItems + 1,
2177 off - Math.min(this.CONTEXT_LINES, idx + group.offsets.start));
2180 let count = this.maxItems;
2181 for (let group in values(groups)) {
2182 let off = Math.max(0, start - group.offsets.start);
2184 group.count = Math.constrain(group.itemCount - off, 0, count);
2185 count -= group.count;
2187 group.collapsed = group.offsets.start >= start + this.maxItems
2188 || group.offsets.start + group.itemCount < start;
2190 group.range = ItemList.Range(off, off + group.count);
2193 var startPos = [group, group.range.start];
2195 this.startPos = startPos;
2201 * Returns an ItemList group for the given completion context,
2202 * creating one if necessary.
2204 * @param {CompletionContext} context
2205 * @returns {ItemList.Group}
2207 getGroup: function getGroup(context)
2208 context instanceof ItemList.Group ? context
2209 : context && context.getCache("itemlist-group",
2210 bind("Group", ItemList, this, context)),
2212 getOffset: function getOffset(tuple) tuple && this.getGroup(tuple[0]).getOffset(tuple[1])
2214 RESIZE_BRIEF: 1 << 0,
2216 WAITING_MESSAGE: _("completion.generating"),
2218 Group: Class("ItemList.Group", {
2219 init: function init(parent, context) {
2220 this.parent = parent;
2221 this.context = context;
2223 this.range = ItemList.Range(0, 0);
2227 <div key="root" highlight="CompGroup">
2228 <div highlight="Completions">
2229 { this.context.createRow(this.context.title || [], "CompTitle") }
2231 <div highlight="CompTitleSep"/>
2232 <div key="contents">
2233 <div key="up" highlight="CompLess"/>
2234 <div key="message" highlight="CompMsg">{this.context.message}</div>
2235 <div key="itemsContainer" class="completion-items-container">
2236 <div key="items" highlight="Completions"/>
2238 <div key="waiting" highlight="CompMsg">{ItemList.WAITING_MESSAGE}</div>
2239 <div key="down" highlight="CompMore"/>
2243 get doc() this.parent.doc,
2244 get win() this.parent.win,
2245 get maxItems() this.parent.maxItems,
2247 get itemCount() this.context.items.length,
2250 * Returns a function which will update the scroll offsets
2251 * and heights of various DOM members.
2254 get rescrollFunc() {
2255 let container = this.nodes.itemsContainer;
2256 let pos = DOM(container).rect.top;
2257 let start = DOM(this.getRow(this.range.start)).rect.top;
2258 let height = DOM(this.getRow(this.range.end - 1)).rect.bottom - start || 0;
2259 let scroll = start + container.scrollTop - pos;
2262 let row = this.selectedRow;
2263 if (row && this.parent.minHeight) {
2264 let { rect } = DOM(this.selectedRow);
2265 var scrollY = this.win.scrollY + rect.bottom - this.win.innerHeight;
2268 return function () {
2269 container.style.height = height + "px";
2270 container.scrollTop = scroll;
2271 if (scrollY != null)
2272 win.scrollTo(0, Math.max(scrollY, 0));
2277 * Reset this group for use with a new set of results.
2279 reset: function reset() {
2281 this.generatedRange = ItemList.Range(0, 0);
2283 DOM.fromXML(this.rootXML, this.doc, this.nodes);
2287 * Update this group after an asynchronous results push.
2289 update: function update() {
2290 this.generatedRange = ItemList.Range(0, 0);
2291 DOM(this.nodes.items).empty();
2293 if (this.context.message)
2294 DOM(this.nodes.message).empty().append(<>{this.context.message}</>);
2296 if (!this.selectedIdx > this.itemCount)
2297 this.selectedIdx = null;
2301 * Updates the DOM to reflect the current state of this
2305 draw: function draw() {
2306 DOM(this.nodes.contents).toggle(!this.collapsed);
2310 DOM(this.nodes.message).toggle(this.context.message && this.range.start == 0);
2311 DOM(this.nodes.waiting).toggle(this.context.incomplete && this.range.end <= this.itemCount);
2312 DOM(this.nodes.up).toggle(this.range.start > 0);
2313 DOM(this.nodes.down).toggle(this.range.end < this.itemCount);
2315 if (!this.generatedRange.contains(this.range)) {
2316 if (this.generatedRange.end == 0)
2317 var [start, end] = this.range;
2319 start = this.range.start - (this.range.start <= this.generatedRange.start
2320 ? this.maxItems / 2 : 0);
2321 end = this.range.end + (this.range.end > this.generatedRange.end
2322 ? this.maxItems / 2 : 0);
2325 let range = ItemList.Range(Math.max(0, start - start % 2),
2326 Math.min(this.itemCount, end));
2329 for (let [i, row] in this.context.getRows(this.generatedRange.start,
2330 this.generatedRange.end,
2332 if (!range.contains(i))
2337 let container = DOM(this.nodes.items);
2338 let before = first ? DOM(first).closure.before
2339 : DOM(this.nodes.items).closure.append;
2341 for (let [i, row] in this.context.getRows(range.start, range.end,
2343 if (i < this.generatedRange.start)
2345 else if (i >= this.generatedRange.end)
2346 container.append(row);
2347 if (i == this.selectedIdx)
2348 this.selectedIdx = this.selectedIdx;
2351 this.generatedRange = range;
2355 getRow: function getRow(idx) this.context.getRow(idx, this.doc),
2357 getOffset: function getOffset(idx) this.offsets.start + (idx || 0),
2359 get selectedRow() this.getRow(this._selectedIdx),
2361 get selectedIdx() this._selectedIdx,
2362 set selectedIdx(idx) {
2363 if (this.selectedRow && this._selectedIdx != idx)
2364 DOM(this.selectedRow).attr("selected", null);
2366 this._selectedIdx = idx;
2368 if (this.selectedRow)
2369 DOM(this.selectedRow).attr("selected", true);
2373 Range: Class.Memoize(function () {
2374 let Range = Struct("ItemList.Range", "start", "end");
2375 update(Range.prototype, {
2376 contains: function contains(idx)
2377 typeof idx == "number" ? idx >= this.start && idx < this.end
2378 : this.contains(idx.start) &&
2379 idx.end >= this.start && idx.end <= this.end
2385 // vim: set fdm=marker sw=4 ts=4 et: