]> git.donarmstrong.com Git - dactyl.git/blob - common/content/commandline.js
9ea1fc33ba78d13920b7979c8f0430e5fee2756b
[dactyl.git] / common / content / commandline.js
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-2012 Kris Maglione <maglione.k@gmail.com>
4 //
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
7 "use strict";
8
9 /** @scope modules */
10
11 var CommandWidgets = Class("CommandWidgets", {
12     depends: ["statusline"],
13
14     init: function init() {
15         let s = "dactyl-statusline-field-";
16
17         overlay.overlayWindow(window, {
18             objects: {
19                 eventTarget: commandline
20             },
21             append: [
22                 ["vbox", { id: config.ids.commandContainer, xmlns: "xul" },
23                     ["vbox", { class: "dactyl-container", hidden: "false", collapsed: "true" },
24                         ["iframe", { class: "dactyl-completions", id: "dactyl-completions-dactyl-commandline",
25                                      src: "dactyl://content/buffer.xhtml", contextmenu: "dactyl-contextmenu",
26                                      flex: "1", hidden: "false", collapsed: "false",
27                                      highlight: "Events", events: "mowEvents" }]],
28
29                     ["stack", { orient: "horizontal", align: "stretch", class: "dactyl-container",
30                                 id: "dactyl-container", highlight: "CmdLine CmdCmdLine" },
31                         ["textbox", { class: "plain", id: "dactyl-strut",   flex: "1", crop: "end", collapsed: "true" }],
32                         ["textbox", { class: "plain", id: "dactyl-mode",    flex: "1", crop: "end" }],
33                         ["hbox", { id: "dactyl-message-box" },
34                             ["label", { class: "plain", id: "dactyl-message-pre", flex: "0", readonly: "true", highlight: "WarningMsg" }],
35                             ["textbox", { class: "plain", id: "dactyl-message", flex: "1", readonly: "true" }]],
36
37                         ["hbox", { id: "dactyl-commandline", hidden: "false", class: "dactyl-container", highlight: "Normal CmdNormal", collapsed: "true" },
38                             ["label", {   id: "dactyl-commandline-prompt",  class: "dactyl-commandline-prompt  plain", flex: "0", crop: "end", value: "", collapsed: "true" }],
39                             ["textbox", { id: "dactyl-commandline-command", class: "dactyl-commandline-command plain", flex: "1", type: "input", timeout: "100",
40                                           highlight: "Events" }]]],
41
42                     ["vbox", { class: "dactyl-container", hidden: "false", collapsed: "false", highlight: "CmdLine" },
43                         ["textbox", { id: "dactyl-multiline-input", class: "plain", flex: "1", rows: "1", hidden: "false", collapsed: "true",
44                                       multiline: "true", highlight: "Normal Events", events: "multilineInputEvents" }]]],
45
46                 ["stack", { id: "dactyl-statusline-stack", xmlns: "xul" },
47                     ["hbox", { id: s + "commandline", hidden: "false", class: "dactyl-container", highlight: "Normal StatusNormal", collapsed: "true" },
48                         ["label", { id: s + "commandline-prompt",    class: "dactyl-commandline-prompt  plain", flex: "0", crop: "end", value: "", collapsed: "true" }],
49                         ["textbox", { id: s + "commandline-command", class: "dactyl-commandline-command plain", flex: "1", type: "text", timeout: "100",
50                                       highlight: "Events",  }]]]],
51
52             before: [
53                 ["toolbar", { id: statusline.statusBar.id, xmlns: "xul" },
54                     ["vbox", { id: "dactyl-completions-" + s + "commandline-container", class: "dactyl-container", hidden: "false", collapsed: "true" },
55                         ["iframe", { class: "dactyl-completions", id: "dactyl-completions-" + s + "commandline", src: "dactyl://content/buffer.xhtml",
56                                      contextmenu: "dactyl-contextmenu", flex: "1", hidden: "false", collapsed: "false", highlight: "Events",
57                                      events: "mowEvents" }]]]]
58         });
59
60         this.elements = {};
61
62         this.addElement({
63             name: "container",
64             noValue: true
65         });
66
67         this.addElement({
68             name: "commandline",
69             getGroup: function () options.get("guioptions").has("C") ? this.commandbar : this.statusbar,
70             getValue: function () this.command
71         });
72
73         this.addElement({
74             name: "strut",
75             defaultGroup: "Normal",
76             getGroup: function () this.commandbar,
77             getValue: function () options.get("guioptions").has("c")
78         });
79
80         this.addElement({
81             name: "command",
82             test: function test(stack, prev) stack.pop && !isinstance(prev.main, modes.COMMAND_LINE),
83             id: "commandline-command",
84             get: function command_get(elem) {
85                 // The long path is because of complications with the
86                 // completion preview.
87                 try {
88                     return elem.inputField.editor.rootElement.firstChild.textContent;
89                 }
90                 catch (e) {
91                     return elem.value;
92                 }
93             },
94             getElement: CommandWidgets.getEditor,
95             getGroup: function (value) this.activeGroup.commandline,
96             onChange: function command_onChange(elem, value) {
97                 if (elem.inputField != dactyl.focusedElement)
98                     try {
99                         elem.selectionStart = elem.value.length;
100                         elem.selectionEnd = elem.value.length;
101                     }
102                     catch (e) {}
103
104                 if (!elem.collapsed)
105                     dactyl.focus(elem);
106             },
107             onVisibility: function command_onVisibility(elem, visible) {
108                 if (visible)
109                     dactyl.focus(elem);
110             }
111         });
112
113         this.addElement({
114             name: "prompt",
115             id: "commandline-prompt",
116             defaultGroup: "CmdPrompt",
117             getGroup: function () this.activeGroup.commandline
118         });
119
120         this.addElement({
121             name: "message",
122             defaultGroup: "Normal",
123             getElement: CommandWidgets.getEditor,
124             getGroup: function (value) {
125                 if (this.command && !options.get("guioptions").has("M"))
126                     return this.statusbar;
127
128                 let statusElem = this.statusbar.message;
129                 // Currently doesn't work as expected with <hbox> parent.
130                 if (false && value && !value[2] && statusElem.editor && statusElem.editor.rootElement.scrollWidth > statusElem.scrollWidth)
131                     return this.commandbar;
132                 return this.activeGroup.mode;
133             }
134         });
135
136         this.addElement({
137             name: "message-pre",
138             defaultGroup: "WarningMsg",
139             getGroup: function () this.activeGroup.message
140         });
141
142         this.addElement({
143             name: "message-box",
144             defaultGroup: "Normal",
145             getGroup: function () this.activeGroup.message,
146             getValue: function () this.message
147         });
148
149         this.addElement({
150             name: "mode",
151             defaultGroup: "ModeMsg",
152             getGroup: function (value) {
153                 if (!options.get("guioptions").has("M"))
154                     if (this.commandbar.container.clientHeight == 0 ||
155                             value && !this.commandbar.commandline.collapsed)
156                         return this.statusbar;
157                 return this.commandbar;
158             }
159         });
160         this.updateVisibility();
161
162         this.initialized = true;
163     },
164     addElement: function addElement(obj) {
165         const self = this;
166         this.elements[obj.name] = obj;
167
168         function get(prefix, map, id) (obj.getElement || util.identity)(map[id] || document.getElementById(prefix + id));
169
170         this.active.__defineGetter__(obj.name, () => this.activeGroup[obj.name][obj.name]);
171         this.activeGroup.__defineGetter__(obj.name, () => this.getGroup(obj.name));
172
173         memoize(this.statusbar, obj.name, () => get("dactyl-statusline-field-", statusline.widgets, (obj.id || obj.name)));
174         memoize(this.commandbar, obj.name, () => get("dactyl-", {}, (obj.id || obj.name)));
175
176         if (!(obj.noValue || obj.getValue)) {
177             Object.defineProperty(this, obj.name, Modes.boundProperty({
178                 test: obj.test,
179
180                 get: function get_widgetValue() {
181                     let elem = self.getGroup(obj.name, obj.value)[obj.name];
182                     if (obj.value != null)
183                         return [obj.value[0],
184                                 obj.get ? obj.get.call(this, elem) : elem.value]
185                                 .concat(obj.value.slice(2));
186                     return null;
187                 },
188
189                 set: function set_widgetValue(val) {
190                     if (val != null && !isArray(val))
191                         val = [obj.defaultGroup || "", val];
192                     obj.value = val;
193
194                     [this.commandbar, this.statusbar].forEach(function (nodeSet) {
195                         let elem = nodeSet[obj.name];
196                         if (val == null)
197                             elem.value = "";
198                         else {
199                             highlight.highlightNode(elem,
200                                 (val[0] != null ? val[0] : obj.defaultGroup)
201                                     .split(/\s/).filter(util.identity)
202                                     .map(function (g) g + " " + nodeSet.group + g)
203                                     .join(" "));
204                             elem.value = val[1];
205                             if (obj.onChange)
206                                 obj.onChange.call(this, elem, val);
207                         }
208                     }, this);
209
210                     this.updateVisibility();
211                     return val;
212                 }
213             }).init(obj.name));
214         }
215         else if (obj.defaultGroup) {
216             [this.commandbar, this.statusbar].forEach(function (nodeSet) {
217                 let elem = nodeSet[obj.name];
218                 if (elem)
219                     highlight.highlightNode(elem, obj.defaultGroup.split(/\s/)
220                                                      .map(function (g) g + " " + nodeSet.group + g).join(" "));
221             });
222         }
223     },
224
225     getGroup: function getgroup(name, value) {
226         if (!statusline.visible)
227             return this.commandbar;
228         return this.elements[name].getGroup.call(this, arguments.length > 1 ? value : this[name]);
229     },
230
231     updateVisibility: function updateVisibility() {
232         let changed = 0;
233         for (let elem in values(this.elements))
234             if (elem.getGroup) {
235                 let value = elem.getValue ? elem.getValue.call(this)
236                           : elem.noValue || this[elem.name];
237
238                 let activeGroup = this.getGroup(elem.name, value);
239                 for (let group in values([this.commandbar, this.statusbar])) {
240                     let meth, node = group[elem.name];
241                     let visible = (value && group === activeGroup);
242                     if (node && !node.collapsed == !visible) {
243                         changed++;
244                         node.collapsed = !visible;
245                         if (elem.onVisibility)
246                             elem.onVisibility.call(this, node, visible);
247                     }
248                 }
249             }
250
251         // Hack. Collapse hidden elements in the stack.
252         // Might possibly be better to use a deck and programmatically
253         // choose which element to select.
254         function check(node) {
255             if (DOM(node).style.display === "-moz-stack") {
256                 let nodes = Array.filter(node.children, function (n) !n.collapsed && n.boxObject.height);
257                 nodes.forEach(function (node, i) { node.style.opacity = (i == nodes.length - 1) ? "" : "0" });
258             }
259             Array.forEach(node.children, check);
260         }
261         [this.commandbar.container, this.statusbar.container].forEach(check);
262
263         // Work around a redrawing bug.
264         if (changed && config.haveGecko("16", "20")) {
265             util.delay(function () {
266                 // Urgh.
267                 statusline.statusBar.style.paddingRight = "1px";
268                 DOM(statusline.statusBar).rect; // Force reflow.
269                 statusline.statusBar.style.paddingRight = "";
270             }, 0);
271         }
272
273         if (this.initialized && loaded.mow && mow.visible)
274             mow.resize(false);
275     },
276
277     active: Class.Memoize(Object),
278     activeGroup: Class.Memoize(Object),
279     commandbar: Class.Memoize(function () ({ group: "Cmd" })),
280     statusbar: Class.Memoize(function ()  ({ group: "Status" })),
281
282     _ready: function _ready(elem) {
283         return elem.contentDocument.documentURI === elem.getAttribute("src") &&
284                ["viewable", "complete"].indexOf(elem.contentDocument.readyState) >= 0;
285     },
286
287     _whenReady: function _whenReady(id, init) {
288         let elem = document.getElementById(id);
289         while (!this._ready(elem))
290             yield 10;
291
292         if (init)
293             init.call(this, elem);
294         yield elem;
295     },
296
297     completionContainer: Class.Memoize(function () this.completionList.parentNode),
298
299     contextMenu: Class.Memoize(function () {
300         ["copy", "copylink", "selectall"].forEach(function (tail) {
301             // some host apps use "hostPrefixContext-copy" ids
302             let css   = "menuitem[id$='ontext-" + tail + "']:not([id^=dactyl-])";
303             let style = DOM(css, document).style;
304             DOM("#dactyl-context-" + tail, document).css({
305                 listStyleImage: style.listStyleImage,
306                 MozImageRegion: style.MozImageRegion
307             });
308         });
309         return document.getElementById("dactyl-contextmenu");
310     }),
311
312     multilineOutput: Class.Memoize(function () this._whenReady("dactyl-multiline-output", function (elem) {
313         highlight.highlightNode(elem.contentDocument.body, "MOW");
314     }), true),
315
316     multilineInput: Class.Memoize(function () document.getElementById("dactyl-multiline-input")),
317
318     mowContainer: Class.Memoize(function () document.getElementById("dactyl-multiline-output-container"))
319 }, {
320     getEditor: function getEditor(elem) {
321         elem.inputField.QueryInterface(Ci.nsIDOMNSEditableElement);
322         return elem;
323     }
324 });
325
326 var CommandMode = Class("CommandMode", {
327     init: function CM_init() {
328         this.keepCommand = userContext.hidden_option_command_afterimage;
329     },
330
331     get autocomplete() options["autocomplete"].length,
332
333     get command() this.widgets.command[1],
334     set command(val) this.widgets.command = val,
335
336     get prompt() this._open ? this.widgets.prompt : this._prompt,
337     set prompt(val) {
338         if (this._open)
339             this.widgets.prompt = val;
340         else
341             this._prompt = val;
342     },
343
344     open: function CM_open(command) {
345         dactyl.assert(isinstance(this.mode, modes.COMMAND_LINE),
346                       /*L*/"Not opening command line in non-command-line mode.",
347                       false);
348
349         this.messageCount = commandline.messageCount;
350         modes.push(this.mode, this.extendedMode, this.closure);
351
352         this.widgets.active.commandline.collapsed = false;
353         this.widgets.prompt = this.prompt;
354         this.widgets.command = command || "";
355
356         this._open = true;
357
358         this.input = this.widgets.active.command.inputField;
359         if (this.historyKey)
360             this.history = CommandLine.History(this.input, this.historyKey, this);
361
362         if (this.complete)
363             this.completions = CommandLine.Completions(this.input, this);
364
365         if (this.completions && command && commandline.commandSession === this)
366             this.completions.autocompleteTimer.flush(true);
367     },
368
369     get active() this === commandline.commandSession,
370
371     get holdFocus() this.widgets.active.command.inputField,
372
373     get mappingSelf() this,
374
375     get widgets() commandline.widgets,
376
377     enter: function CM_enter(stack) {
378         commandline.commandSession = this;
379         if (stack.pop && commandline.command) {
380             this.onChange(commandline.command);
381             if (this.completions && stack.pop)
382                 this.completions.complete(true, false);
383         }
384     },
385
386     leave: function CM_leave(stack) {
387         if (!stack.push) {
388             commandline.commandSession = null;
389             this.input.dactylKeyPress = undefined;
390
391             let waiting = this.accepted && this.completions && this.completions.waiting;
392             if (waiting)
393                 this.completions.onComplete = bind("onSubmit", this);
394
395             if (this.completions)
396                 this.completions.cleanup();
397
398             if (this.history)
399                 this.history.save();
400
401             commandline.hideCompletions();
402
403             modes.delay(function () {
404                 if (!this.keepCommand || commandline.silent || commandline.quiet)
405                     commandline.hide();
406                 if (!waiting)
407                     this[this.accepted ? "onSubmit" : "onCancel"](commandline.command);
408                 if (commandline.messageCount === this.messageCount)
409                     commandline.clearMessage();
410             }, this);
411         }
412     },
413
414     events: {
415         input: function CM_onInput(event) {
416             if (this.completions) {
417                 this.resetCompletions();
418
419                 this.completions.autocompleteTimer.tell(false);
420             }
421             this.onChange(commandline.command);
422         },
423         keyup: function CM_onKeyUp(event) {
424             let key = DOM.Event.stringify(event);
425             if (/-?Tab>$/.test(key) && this.completions)
426                 this.completions.tabTimer.flush();
427         }
428     },
429
430     keepCommand: false,
431
432     onKeyPress: function CM_onKeyPress(events) {
433         if (this.completions)
434             this.completions.previewClear();
435
436         return true; /* Pass event */
437     },
438
439     onCancel: function (value) {},
440
441     onChange: function (value) {},
442
443     onHistory: function (value) {},
444
445     onSubmit: function (value) {},
446
447     resetCompletions: function CM_resetCompletions() {
448         if (this.completions)
449             this.completions.clear();
450         if (this.history)
451             this.history.reset();
452     },
453 });
454
455 var CommandExMode = Class("CommandExMode", CommandMode, {
456
457     get mode() modes.EX,
458
459     historyKey: "command",
460
461     prompt: ["Normal", ":"],
462
463     complete: function CEM_complete(context) {
464         try {
465             context.fork("ex", 0, completion, "ex");
466         }
467         catch (e) {
468             context.message = _("error.error", e);
469         }
470     },
471
472     onSubmit: function CEM_onSubmit(command) {
473         contexts.withContext({ file: /*L*/"[Command Line]", line: 1 },
474                              function _onSubmit() {
475             io.withSavedValues(["readHeredoc"], function _onSubmit() {
476                 this.readHeredoc = commandline.readHeredoc;
477                 commands.repeat = command;
478                 dactyl.execute(command);
479             });
480         });
481     }
482 });
483
484 var CommandPromptMode = Class("CommandPromptMode", CommandMode, {
485     init: function init(prompt, params) {
486         this.prompt = isArray(prompt) ? prompt : ["Question", prompt];
487         update(this, params);
488         init.supercall(this);
489     },
490
491     complete: function CPM_complete(context, ...args) {
492         if (this.completer)
493             context.forkapply("prompt", 0, this, "completer", args);
494     },
495
496     get mode() modes.PROMPT
497 });
498
499 /**
500  * This class is used for prompting of user input and echoing of messages.
501  *
502  * It consists of a prompt and command field be sure to only create objects of
503  * this class when the chrome is ready.
504  */
505 var CommandLine = Module("commandline", {
506     init: function init() {
507         this._callbacks = {};
508
509         memoize(this, "_store", function () storage.newMap("command-history", { store: true, privateData: true }));
510
511         for (let name in values(["command", "search"]))
512             if (storage.exists("history-" + name)) {
513                 let ary = storage.newArray("history-" + name, { store: true, privateData: true });
514
515                 this._store.set(name, [v for ([k, v] in ary)]);
516                 ary.delete();
517                 this._store.changed();
518             }
519
520         this._messageHistory = { //{{{
521             _messages: [],
522             get messages() {
523                 let max = options["messages"];
524
525                 // resize if 'messages' has changed
526                 if (this._messages.length > max)
527                     this._messages = this._messages.splice(this._messages.length - max);
528
529                 return this._messages;
530             },
531
532             get length() this._messages.length,
533
534             clear: function clear() {
535                 this._messages = [];
536             },
537
538             filter: function filter(fn, self) {
539                 this._messages = this._messages.filter(fn, self);
540             },
541
542             add: function add(message) {
543                 if (!message)
544                     return;
545
546                 if (this._messages.length >= options["messages"])
547                     this._messages.shift();
548
549                 this._messages.push(update({
550                     timestamp: Date.now()
551                 }, message));
552             }
553         }; //}}}
554     },
555
556     signals: {
557         "browser.locationChange": function (webProgress, request, uri) {
558             this.clear();
559         }
560     },
561
562     /**
563      * Determines whether the command line should be visible.
564      *
565      * @returns {boolean}
566      */
567     get commandVisible() !!this.commandSession,
568
569     /**
570      * Ensure that the multiline input widget is the correct size.
571      */
572     _autosizeMultilineInputWidget: function _autosizeMultilineInputWidget() {
573         let lines = this.widgets.multilineInput.value.split("\n").length - 1;
574
575         this.widgets.multilineInput.setAttribute("rows", Math.max(lines, 1));
576     },
577
578     HL_NORMAL:     "Normal",
579     HL_ERRORMSG:   "ErrorMsg",
580     HL_MODEMSG:    "ModeMsg",
581     HL_MOREMSG:    "MoreMsg",
582     HL_QUESTION:   "Question",
583     HL_INFOMSG:    "InfoMsg",
584     HL_WARNINGMSG: "WarningMsg",
585     HL_LINENR:     "LineNr",
586
587     FORCE_MULTILINE    : 1 << 0,
588     FORCE_SINGLELINE   : 1 << 1,
589     DISALLOW_MULTILINE : 1 << 2, // If an echo() should try to use the single line
590                                  // but output nothing when the MOW is open; when also
591                                  // FORCE_MULTILINE is given, FORCE_MULTILINE takes precedence
592     APPEND_TO_MESSAGES : 1 << 3, // Add the string to the message history.
593     ACTIVE_WINDOW      : 1 << 4, // Only echo in active window.
594
595     get completionContext() this._completions.context,
596
597     _silent: false,
598     get silent() this._silent,
599     set silent(val) {
600         this._silent = val;
601         this.quiet = this.quiet;
602     },
603
604     _quite: false,
605     get quiet() this._quiet,
606     set quiet(val) {
607         this._quiet = val;
608         ["commandbar", "statusbar"].forEach(function (nodeSet) {
609             Array.forEach(this.widgets[nodeSet].commandline.children, function (node) {
610                 node.style.opacity = this._quiet || this._silent ? "0" : "";
611             }, this);
612         }, this);
613     },
614
615     widgets: Class.Memoize(function () CommandWidgets()),
616
617     runSilently: function runSilently(func, self) {
618         this.withSavedValues(["silent"], function () {
619             this.silent = true;
620             func.call(self);
621         });
622     },
623
624     get completionList() {
625         let node = this.widgets.active.commandline;
626         if (this.commandSession && this.commandSession.completionList)
627             node = document.getElementById(this.commandSession.completionList);
628
629         if (!node.completionList) {
630             let elem = document.getElementById("dactyl-completions-" + node.id);
631             util.waitFor(bind(this.widgets._ready, null, elem));
632
633             node.completionList = ItemList(elem);
634             node.completionList.isAboveMow = node.id ==
635                 this.widgets.statusbar.commandline.id;
636         }
637         return node.completionList;
638     },
639
640     hideCompletions: function hideCompletions() {
641         for (let nodeSet in values([this.widgets.statusbar, this.widgets.commandbar]))
642             if (nodeSet.commandline.completionList)
643                 nodeSet.commandline.completionList.visible = false;
644     },
645
646     _lastClearable: Modes.boundProperty(),
647     messages: Modes.boundProperty(),
648
649     multilineInputVisible: Modes.boundProperty({
650         set: function set_miwVisible(value) { this.widgets.multilineInput.collapsed = !value; }
651     }),
652
653     get command() {
654         if (this.commandVisible && this.widgets.command)
655             return commands.lastCommand = this.widgets.command[1];
656         return commands.lastCommand;
657     },
658     set command(val) {
659         if (this.commandVisible && (modes.extended & modes.EX))
660             return this.widgets.command = val;
661         return commands.lastCommand = val;
662     },
663
664     clear: function clear(scroll) {
665         if (!scroll || Date.now() - this._lastEchoTime > 5000)
666             this.clearMessage();
667         this._lastEchoTime = 0;
668         this.hiddenMessages = 0;
669
670         if (!this.commandSession) {
671             this.widgets.command = null;
672             this.hideCompletions();
673         }
674
675         if (modes.main == modes.OUTPUT_MULTILINE && !mow.isScrollable(1))
676             modes.pop();
677
678         if (!modes.have(modes.OUTPUT_MULTILINE))
679             mow.visible = false;
680     },
681
682     clearMessage: function clearMessage() {
683         if (this.widgets.message && this.widgets.message[1] === this._lastClearable) {
684             this.widgets.message = null;
685             this.hiddenMessages = 0;
686         }
687     },
688
689     /**
690      * Displays the multi-line output of a command, preceded by the last
691      * executed ex command string.
692      *
693      * @param {XML} xml The output as an E4X XML object.
694      */
695     commandOutput: function commandOutput(xml) {
696         if (!this.command)
697             this.echo(xml, this.HIGHLIGHT_NORMAL, this.FORCE_MULTILINE);
698         else
699             this.echo([["div", { xmlns: "html" }, ":" + this.command], "\n", xml],
700                       this.HIGHLIGHT_NORMAL, this.FORCE_MULTILINE);
701         this.command = null;
702     },
703
704     /**
705      * Hides the command line, and shows any status messages that
706      * are under it.
707      */
708     hide: function hide() {
709         this.widgets.command = null;
710     },
711
712     /**
713      * Display a message in the command-line area.
714      *
715      * @param {string} str
716      * @param {string} highlightGroup
717      * @param {boolean} forceSingle If provided, don't let over-long
718      *     messages move to the MOW.
719      */
720     _echoLine: function echoLine(str, highlightGroup, forceSingle, silent) {
721         this.widgets.message = str ? [highlightGroup, str, forceSingle] : null;
722
723         dactyl.triggerObserver("echoLine", str, highlightGroup, null, forceSingle);
724
725         if (!this.commandVisible)
726             this.hide();
727
728         let field = this.widgets.active.message.inputField;
729         if (field.value && !forceSingle && field.editor.rootElement.scrollWidth > field.scrollWidth) {
730             this.widgets.message = null;
731             mow.echo(["span", { highlight: "Message" }, str], highlightGroup, true);
732         }
733     },
734
735     _hiddenMessages: 0,
736     get hiddenMessages() this._hiddenMessages,
737     set hiddenMessages(val) {
738         this._hiddenMessages = val;
739         if (val)
740             this.widgets["message-pre"] = _("commandline.moreMessages", val) + " ";
741         else
742             this.widgets["message-pre"] = null;
743     },
744
745     _lastEcho: null,
746
747     /**
748      * Output the given string onto the command line. With no flags, the
749      * message will be shown in the status line if it's short enough to
750      * fit, and contains no new lines, and isn't XML. Otherwise, it will be
751      * shown in the MOW.
752      *
753      * @param {string} str
754      * @param {string} highlightGroup The Highlight group for the
755      *     message.
756      * @default "Normal"
757      * @param {number} flags Changes the behavior as follows:
758      *   commandline.APPEND_TO_MESSAGES - Causes message to be added to the
759      *          messages history, and shown by :messages.
760      *   commandline.FORCE_SINGLELINE   - Forbids the command from being
761      *          pushed to the MOW if it's too long or of there are already
762      *          status messages being shown.
763      *   commandline.DISALLOW_MULTILINE - Cancels the operation if the MOW
764      *          is already visible.
765      *   commandline.FORCE_MULTILINE    - Forces the message to appear in
766      *          the MOW.
767      */
768     messageCount: 0,
769     echo: function echo(data, highlightGroup, flags) {
770         // dactyl.echo uses different order of flags as it omits the highlight group, change commandline.echo argument order? --mst
771         if (this._silent || !this.widgets)
772             return;
773
774         this.messageCount++;
775
776         highlightGroup = highlightGroup || this.HL_NORMAL;
777
778         let appendToMessages = (data) => {
779             let message = isObject(data) && !DOM.isJSONXML(data) ? data : { message: data };
780
781             // Make sure the memoized message property is an instance property.
782             message.message;
783             this._messageHistory.add(update({ highlight: highlightGroup }, message));
784             return message.message;
785         }
786
787         if (flags & this.APPEND_TO_MESSAGES)
788             data = appendToMessages(data);
789
790         if ((flags & this.ACTIVE_WINDOW) && window != overlay.activeWindow)
791             return;
792
793         if ((flags & this.DISALLOW_MULTILINE) && !this.widgets.mowContainer.collapsed)
794             return;
795
796         let forceSingle = flags & (this.FORCE_SINGLELINE | this.DISALLOW_MULTILINE);
797         let action = this._echoLine;
798
799         if ((flags & this.FORCE_MULTILINE) || (/\n/.test(data) || !isinstance(data, [_, "String"])) && !(flags & this.FORCE_SINGLELINE))
800             action = mow.closure.echo;
801
802         let checkSingleLine = () => action == this._echoLine;
803
804         if (forceSingle) {
805             this._lastEcho = null;
806             this.hiddenMessages = 0;
807         }
808         else {
809             // So complicated...
810             if (checkSingleLine() && !this.widgets.mowContainer.collapsed) {
811                 highlightGroup += " Message";
812                 action = mow.closure.echo;
813             }
814             else if (!checkSingleLine() && this.widgets.mowContainer.collapsed) {
815                 if (this._lastEcho && this.widgets.message && this.widgets.message[1] == this._lastEcho.msg) {
816                     if (!(this._lastEcho.flags & this.APPEND_TO_MESSAGES))
817                         appendToMessages(this._lastEcho.data);
818
819                     mow.echo(
820                         ["span", { highlight: "Message" },
821                             ["span", { highlight: "WarningMsg" },
822                                 _("commandline.moreMessages", this.hiddenMessages + 1) + " "],
823                             this._lastEcho.msg],
824                         this.widgets.message[0], true);
825
826                     this.hiddenMessages = 0;
827                 }
828             }
829             else if (this._lastEcho && this.widgets.message && this.widgets.message[1] == this._lastEcho.msg) {
830                 if (!(this._lastEcho.flags & this.APPEND_TO_MESSAGES))
831                     appendToMessages(this._lastEcho.data);
832                 if (checkSingleLine() && !(flags & this.APPEND_TO_MESSAGES))
833                     appendToMessages(data);
834
835                 flags |= this.APPEND_TO_MESSAGES;
836                 this.hiddenMessages++;
837             }
838             this._lastEcho = checkSingleLine() && { flags: flags, msg: data, data: arguments[0] };
839         }
840
841         this._lastClearable = action === this._echoLine && String(data);
842         this._lastEchoTime = (flags & this.FORCE_SINGLELINE) && Date.now();
843
844         if (action)
845             action.call(this, data, highlightGroup, checkSingleLine());
846     },
847     _lastEchoTime: 0,
848
849     /**
850      * Prompt the user. Sets modes.main to COMMAND_LINE, which the user may
851      * pop at any time to close the prompt.
852      *
853      * @param {string} prompt The input prompt to use.
854      * @param {function(string)} callback
855      * @param {Object} extra
856      * @... {function} onChange - A function to be called with the current
857      *     input every time it changes.
858      * @... {function(CompletionContext)} completer - A completion function
859      *     for the user's input.
860      * @... {string} promptHighlight - The HighlightGroup used for the
861      *     prompt. @default "Question"
862      * @... {string} default - The initial value that will be returned
863      *     if the user presses <CR> straightaway. @default ""
864      */
865     input: function _input(prompt, callback, extra) {
866         extra = extra || {};
867
868         CommandPromptMode(prompt, update({ onSubmit: callback }, extra)).open();
869     },
870
871     readHeredoc: function readHeredoc(end) {
872         let args;
873         commandline.inputMultiline(end, function (res) { args = res; });
874         util.waitFor(function () args !== undefined);
875         return args;
876     },
877
878     /**
879      * Get a multi-line input from a user, up to but not including the line
880      * which matches the given regular expression. Then execute the
881      * callback with that string as a parameter.
882      *
883      * @param {string} end
884      * @param {function(string)} callback
885      */
886     // FIXME: Buggy, especially when pasting.
887     inputMultiline: function inputMultiline(end, callback) {
888         let cmd = this.command;
889         let self = {
890             end: "\n" + end + "\n",
891             callback: callback
892         };
893
894         modes.push(modes.INPUT_MULTILINE, null, {
895             holdFocus: true,
896             leave: function leave() {
897                 if (!self.done)
898                     self.callback(null);
899             },
900             mappingSelf: self
901         });
902
903         if (cmd != false)
904             this._echoLine(cmd, this.HL_NORMAL);
905
906         // save the arguments, they are needed in the event handler onKeyPress
907
908         this.multilineInputVisible = true;
909         this.widgets.multilineInput.value = "";
910         this._autosizeMultilineInputWidget();
911
912         this.timeout(function () { dactyl.focus(this.widgets.multilineInput); }, 10);
913     },
914
915     get commandMode() this.commandSession && isinstance(modes.main, modes.COMMAND_LINE),
916
917     events: update(
918         iter(CommandMode.prototype.events).map(
919             function ([event, handler]) [
920                 event, function (event) {
921                     if (this.commandMode)
922                         handler.call(this.commandSession, event);
923                 }
924             ]).toObject(),
925         {
926             focus: function onFocus(event) {
927                 if (!this.commandSession
928                         && event.originalTarget === this.widgets.active.command.inputField) {
929                     event.target.blur();
930                     dactyl.beep();
931                 }
932             }
933         }
934     ),
935
936     get mowEvents() mow.events,
937
938     /**
939      * Multiline input events, they will come straight from
940      * #dactyl-multiline-input in the XUL.
941      *
942      * @param {Event} event
943      */
944     multilineInputEvents: {
945         blur: function onBlur(event) {
946             if (modes.main == modes.INPUT_MULTILINE)
947                 this.timeout(function () {
948                     dactyl.focus(this.widgets.multilineInput.inputField);
949                 });
950         },
951         input: function onInput(event) {
952             this._autosizeMultilineInputWidget();
953         }
954     },
955
956     updateOutputHeight: deprecated("mow.resize", function updateOutputHeight(open, extra) mow.resize(open, extra)),
957
958     withOutputToString: function withOutputToString(fn, self, ...args) {
959         dactyl.registerObserver("echoLine", observe, true);
960         dactyl.registerObserver("echoMultiline", observe, true);
961
962         let output = [];
963         function observe(str, highlight, dom) {
964             output.push(dom && !isString(str) ? dom : str);
965         }
966
967         this.savingOutput = true;
968         dactyl.trapErrors.apply(dactyl, [fn, self].concat(args));
969         this.savingOutput = false;
970         return output.map(function (elem) elem instanceof Node ? DOM.stringify(elem) : elem)
971                      .join("\n");
972     }
973 }, {
974     /**
975      * A class for managing the history of an input field.
976      *
977      * @param {HTMLInputElement} inputField
978      * @param {string} mode The mode for which we need history.
979      */
980     History: Class("History", {
981         init: function init(inputField, mode, session) {
982             this.mode = mode;
983             this.input = inputField;
984             this.reset();
985             this.session = session;
986         },
987         get store() commandline._store.get(this.mode, []),
988         set store(ary) { commandline._store.set(this.mode, ary); },
989         /**
990          * Reset the history index to the first entry.
991          */
992         reset: function reset() {
993             this.index = null;
994         },
995         /**
996          * Save the last entry to the permanent store. All duplicate entries
997          * are removed and the list is truncated, if necessary.
998          */
999         save: function save() {
1000             if (events.feedingKeys)
1001                 return;
1002
1003             let str = this.input.value;
1004             if (/^\s*$/.test(str))
1005                 return;
1006
1007             let privateData = this.checkPrivate(str);
1008             if (privateData == "never-save")
1009                 return;
1010
1011             this.store = this.store.filter(function (line) (line.value || line) != str);
1012             dactyl.trapErrors(function () {
1013                 this.store.push({ value: str, timestamp: Date.now() * 1000, privateData: privateData });
1014             }, this);
1015             this.store = this.store.slice(Math.max(0, this.store.length - options["history"]));
1016         },
1017         /**
1018          * @property {function} Returns whether a data item should be
1019          * considered private.
1020          */
1021         checkPrivate: function checkPrivate(str) {
1022             // Not really the ideal place for this check.
1023             if (this.mode == "command")
1024                 return commands.hasPrivateData(str);
1025             return false;
1026         },
1027         /**
1028          * Replace the current input field value.
1029          *
1030          * @param {string} val The new value.
1031          */
1032         replace: function replace(val) {
1033             editor.withSavedValues(["skipSave"], function () {
1034                 editor.skipSave = true;
1035
1036                 this.input.dactylKeyPress = undefined;
1037                 if (this.completions)
1038                     this.completions.previewClear();
1039                 this.input.value = val;
1040                 this.session.onHistory(val);
1041             }, this);
1042         },
1043
1044         /**
1045          * Move forward or backward in history.
1046          *
1047          * @param {boolean} backward Direction to move.
1048          * @param {boolean} matchCurrent Search for matches starting
1049          *      with the current input value.
1050          */
1051         select: function select(backward, matchCurrent) {
1052             // always reset the tab completion if we use up/down keys
1053             if (this.session.completions)
1054                 this.session.completions.reset();
1055
1056             let diff = backward ? -1 : 1;
1057
1058             if (this.index == null) {
1059                 this.original = this.input.value;
1060                 this.index = this.store.length;
1061             }
1062
1063             // search the history for the first item matching the current
1064             // command-line string
1065             while (true) {
1066                 this.index += diff;
1067                 if (this.index < 0 || this.index > this.store.length) {
1068                     this.index = Math.constrain(this.index, 0, this.store.length);
1069                     dactyl.beep();
1070                     // I don't know why this kludge is needed. It
1071                     // prevents the caret from moving to the end of
1072                     // the input field.
1073                     if (this.input.value == "") {
1074                         this.input.value = " ";
1075                         this.input.value = "";
1076                     }
1077                     break;
1078                 }
1079
1080                 let hist = this.store[this.index];
1081                 // user pressed DOWN when there is no newer history item
1082                 if (!hist)
1083                     hist = this.original;
1084                 else
1085                     hist = (hist.value || hist);
1086
1087                 if (!matchCurrent || hist.substr(0, this.original.length) == this.original) {
1088                     this.replace(hist);
1089                     break;
1090                 }
1091             }
1092         }
1093     }),
1094
1095     /**
1096      * A class for tab completions on an input field.
1097      *
1098      * @param {Object} input
1099      */
1100     Completions: Class("Completions", {
1101         UP: {},
1102         DOWN: {},
1103         CTXT_UP: {},
1104         CTXT_DOWN: {},
1105         PAGE_UP: {},
1106         PAGE_DOWN: {},
1107         RESET: null,
1108
1109         init: function init(input, session) {
1110             let self = this;
1111
1112             this.context = CompletionContext(input.QueryInterface(Ci.nsIDOMNSEditableElement).editor);
1113             this.context.onUpdate = function onUpdate() { self.asyncUpdate(this); };
1114
1115             this.editor = input.editor;
1116             this.input = input;
1117             this.session = session;
1118
1119             this.wildmode = options.get("wildmode");
1120             this.wildtypes = this.wildmode.value;
1121
1122             this.itemList = commandline.completionList;
1123             this.itemList.open(this.context);
1124
1125             dactyl.registerObserver("events.doneFeeding", this.closure.onDoneFeeding, true);
1126
1127             this.autocompleteTimer = Timer(200, 500, function autocompleteTell(tabPressed) {
1128                 if (events.feedingKeys && !tabPressed)
1129                     this.ignoredCount++;
1130                 else if (this.session.autocomplete) {
1131                     this.itemList.visible = true;
1132                     this.complete(true, false);
1133                 }
1134             }, this);
1135
1136             this.tabTimer = Timer(0, 0, function tabTell(event) {
1137                 let tabCount = this.tabCount;
1138                 this.tabCount = 0;
1139                 this.tab(tabCount, event.altKey && options["altwildmode"]);
1140             }, this);
1141         },
1142
1143         tabCount: 0,
1144
1145         ignoredCount: 0,
1146
1147         /**
1148          * @private
1149          */
1150         onDoneFeeding: function onDoneFeeding() {
1151             if (this.ignoredCount)
1152                 this.autocompleteTimer.flush(true);
1153             this.ignoredCount = 0;
1154         },
1155
1156         /**
1157          * @private
1158          */
1159         onTab: function onTab(event) {
1160             this.tabCount += event.shiftKey ? -1 : 1;
1161             this.tabTimer.tell(event);
1162         },
1163
1164         get activeContexts() this.context.contextList
1165                                  .filter(function (c) c.items.length || c.incomplete),
1166
1167         /**
1168          * Returns the current completion string relative to the
1169          * offset of the currently selected context.
1170          */
1171         get completion() {
1172             let offset = this.selected ? this.selected[0].offset : this.start;
1173             return commandline.command.slice(offset, this.caret);
1174         },
1175
1176         /**
1177          * Updates the input field from *offset* to {@link #caret}
1178          * with the value *value*. Afterward, the caret is moved
1179          * just after the end of the updated text.
1180          *
1181          * @param {number} offset The offset in the original input
1182          *      string at which to insert *value*.
1183          * @param {string} value The value to insert.
1184          */
1185         setCompletion: function setCompletion(offset, value) {
1186             editor.withSavedValues(["skipSave"], function () {
1187                 editor.skipSave = true;
1188                 this.previewClear();
1189
1190                 if (value == null)
1191                     var [input, caret] = [this.originalValue, this.originalCaret];
1192                 else {
1193                     input = this.getCompletion(offset, value);
1194                     caret = offset + value.length;
1195                 }
1196
1197                 // Change the completion text.
1198                 // The second line is a hack to deal with some substring
1199                 // preview corner cases.
1200                 commandline.widgets.active.command.value = input;
1201                 this.editor.selection.focusNode.textContent = input;
1202
1203                 this.caret = caret;
1204                 this._caret = this.caret;
1205
1206                 this.input.dactylKeyPress = undefined;
1207             }, this);
1208         },
1209
1210         /**
1211          * For a given offset and completion string, returns the
1212          * full input value after selecting that item.
1213          *
1214          * @param {number} offset The offset at which to insert the
1215          *      completion.
1216          * @param {string} value The value to insert.
1217          * @returns {string};
1218          */
1219         getCompletion: function getCompletion(offset, value) {
1220             return this.originalValue.substr(0, offset)
1221                  + value
1222                  + this.originalValue.substr(this.originalCaret);
1223         },
1224
1225         get selected() this.itemList.selected,
1226         set selected(tuple) {
1227             if (!array.equals(tuple || [],
1228                               this.itemList.selected || []))
1229                 this.itemList.select(tuple);
1230
1231             if (!tuple)
1232                 this.setCompletion(null);
1233             else {
1234                 let [ctxt, idx] = tuple;
1235                 this.setCompletion(ctxt.offset, ctxt.items[idx].result);
1236             }
1237         },
1238
1239         get caret() this.editor.selection.getRangeAt(0).startOffset,
1240         set caret(offset) {
1241             this.editor.selection.collapse(this.editor.rootElement.firstChild, offset);
1242         },
1243
1244         get start() this.context.allItems.start,
1245
1246         get items() this.context.allItems.items,
1247
1248         get substring() this.context.longestAllSubstring,
1249
1250         get wildtype() this.wildtypes[this.wildIndex] || "",
1251
1252         /**
1253          * Cleanup resources used by this completion session. This
1254          * instance should not be used again once this method is
1255          * called.
1256          */
1257         cleanup: function cleanup() {
1258             dactyl.unregisterObserver("events.doneFeeding", this.closure.onDoneFeeding);
1259             this.previewClear();
1260
1261             this.tabTimer.reset();
1262             this.autocompleteTimer.reset();
1263             if (!this.onComplete)
1264                 this.context.cancelAll();
1265
1266             this.itemList.visible = false;
1267             this.input.dactylKeyPress = undefined;
1268             this.hasQuit = true;
1269         },
1270
1271         /**
1272          * Run the completer.
1273          *
1274          * @param {boolean} show Passed to {@link #reset}.
1275          * @param {boolean} tabPressed Should be set to true if, and
1276          *      only if, this function is being called in response
1277          *      to a <Tab> press.
1278          */
1279         complete: function complete(show, tabPressed) {
1280             this.session.ignoredCount = 0;
1281
1282             this.waiting = null;
1283             this.context.reset();
1284             this.context.tabPressed = tabPressed;
1285
1286             this.session.complete(this.context);
1287             if (!this.session.active)
1288                 return;
1289
1290             this.reset(show, tabPressed);
1291             this.wildIndex = 0;
1292             this._caret = this.caret;
1293         },
1294
1295         /**
1296          * Clear any preview string and cancel any pending
1297          * asynchronous context. Called when there is further input
1298          * to be processed.
1299          */
1300         clear: function clear() {
1301             this.context.cancelAll();
1302             this.wildIndex = -1;
1303             this.previewClear();
1304         },
1305
1306         /**
1307          * Saves the current input state. To be called before an
1308          * item is selected in a new set of completion responses.
1309          * @private
1310          */
1311         saveInput: function saveInput() {
1312             this.originalValue = this.context.value;
1313             this.originalCaret = this.caret;
1314         },
1315
1316         /**
1317          * Resets the completion state.
1318          *
1319          * @param {boolean} show If true and options allow the
1320          *      completion list to be shown, show it.
1321          */
1322         reset: function reset(show) {
1323             this.waiting = null;
1324             this.wildIndex = -1;
1325
1326             this.saveInput();
1327
1328             if (show) {
1329                 this.itemList.update();
1330                 this.context.updateAsync = true;
1331                 if (this.haveType("list"))
1332                     this.itemList.visible = true;
1333                 this.wildIndex = 0;
1334             }
1335
1336             this.preview();
1337         },
1338
1339         /**
1340          * Calls when an asynchronous completion context has new
1341          * results to return.
1342          *
1343          * @param {CompletionContext} context The changed context.
1344          * @private
1345          */
1346         asyncUpdate: function asyncUpdate(context) {
1347             if (this.hasQuit) {
1348                 let item = this.getItem(this.waiting);
1349                 if (item && this.waiting && this.onComplete) {
1350                     util.trapErrors("onComplete", this,
1351                                     this.getCompletion(this.waiting[0].offset,
1352                                                        item.result));
1353                     this.waiting = null;
1354                     this.context.cancelAll();
1355                 }
1356                 return;
1357             }
1358
1359             let value = this.editor.selection.focusNode.textContent;
1360             this.saveInput();
1361
1362             if (this.itemList.visible)
1363                 this.itemList.updateContext(context);
1364
1365             if (this.waiting && this.waiting[0] == context)
1366                 this.select(this.waiting);
1367             else if (!this.waiting) {
1368                 let cursor = this.selected;
1369                 if (cursor && cursor[0] == context) {
1370                     let item = this.getItem(cursor);
1371                     if (!item || this.completion != item.result)
1372                         this.itemList.select(null);
1373                 }
1374
1375                 this.preview();
1376             }
1377         },
1378
1379         /**
1380          * Returns true if the currently selected 'wildmode' index
1381          * has the given completion type.
1382          */
1383         haveType: function haveType(type)
1384             this.wildmode.checkHas(this.wildtype, type == "first" ? "" : type),
1385
1386         /**
1387          * Returns the completion item for the given selection
1388          * tuple.
1389          *
1390          * @param {[CompletionContext,number]} tuple The spec of the
1391          *      item to return.
1392          *      @default {@link #selected}
1393          * @returns {object}
1394          */
1395         getItem: function getItem(tuple) {
1396             tuple = tuple || this.selected;
1397             return tuple && tuple[0] && tuple[0].items[tuple[1]];
1398         },
1399
1400         /**
1401          * Returns a tuple representing the next item, at the given
1402          * *offset*, from *tuple*.
1403          *
1404          * @param {[CompletionContext,number]} tuple The offset from
1405          *      which to search.
1406          *      @default {@link #selected}
1407          * @param {number} offset The positive or negative offset to
1408          *      find.
1409          *      @default 1
1410          * @param {boolean} noWrap If true, and the search would
1411          *      wrap, return null.
1412          */
1413         nextItem: function nextItem(tuple, offset, noWrap) {
1414             if (tuple === undefined)
1415                 tuple = this.selected;
1416
1417             return this.itemList.getRelativeItem(offset || 1, tuple, noWrap);
1418         },
1419
1420         /**
1421          * The last previewed substring.
1422          * @private
1423          */
1424         lastSubstring: "",
1425
1426         /**
1427          * Displays a preview of the text provided by the next <Tab>
1428          * press if the current input is an anchored substring of
1429          * that result.
1430          */
1431         preview: function preview() {
1432             this.previewClear();
1433             if (this.wildIndex < 0 || this.caret < this.input.value.length
1434                     || !this.activeContexts.length || this.waiting)
1435                 return;
1436
1437             let substring = "";
1438             switch (this.wildtype.replace(/.*:/, "")) {
1439             case "":
1440                 var cursor = this.nextItem(null);
1441                 break;
1442             case "longest":
1443                 if (this.items.length > 1) {
1444                     substring = this.substring;
1445                     break;
1446                 }
1447                 // Fallthrough
1448             case "full":
1449                 cursor = this.nextItem();
1450                 break;
1451             }
1452             if (cursor)
1453                 substring = this.getItem(cursor).result;
1454
1455             // Don't show 1-character substrings unless we've just hit backspace
1456             if (substring.length < 2 && this.lastSubstring.indexOf(substring))
1457                 return;
1458
1459             this.lastSubstring = substring;
1460
1461             let value = this.completion;
1462             if (util.compareIgnoreCase(value, substring.substr(0, value.length)))
1463                 return;
1464
1465             substring = substring.substr(value.length);
1466             this.removeSubstring = substring;
1467
1468             let node = DOM.fromJSON(["span", { highlight: "Preview" }, substring],
1469                                     document);
1470
1471             this.withSavedValues(["caret"], function () {
1472                 this.editor.insertNode(node, this.editor.rootElement, 1);
1473             });
1474         },
1475
1476         /**
1477          * Clears the currently displayed next-<Tab> preview string.
1478          */
1479         previewClear: function previewClear() {
1480             let node = this.editor.rootElement.firstChild;
1481             if (node && node.nextSibling) {
1482                 try {
1483                     DOM(node.nextSibling).remove();
1484                 }
1485                 catch (e) {
1486                     node.nextSibling.textContent = "";
1487                 }
1488             }
1489             else if (this.removeSubstring) {
1490                 let str = this.removeSubstring;
1491                 let cmd = commandline.widgets.active.command.value;
1492                 if (cmd.substr(cmd.length - str.length) == str)
1493                     commandline.widgets.active.command.value = cmd.substr(0, cmd.length - str.length);
1494             }
1495             delete this.removeSubstring;
1496         },
1497
1498         /**
1499          * Selects a completion based on the value of *idx*.
1500          *
1501          * @param {[CompletionContext,number]|const object} The
1502          *      (context,index) tuple of the item to select, or an
1503          *      offset constant from this object.
1504          * @param {number} count When given an offset constant,
1505          *      select *count* units.
1506          *      @default 1
1507          * @param {boolean} fromTab If true, this function was
1508          *      called by {@link #tab}.
1509          *      @private
1510          */
1511         select: function select(idx, count, fromTab) {
1512             count = count || 1;
1513
1514             switch (idx) {
1515             case this.UP:
1516             case this.DOWN:
1517                 idx = this.nextItem(this.waiting || this.selected,
1518                                     idx == this.UP ? -count : count,
1519                                     true);
1520                 break;
1521
1522             case this.CTXT_UP:
1523             case this.CTXT_DOWN:
1524                 let groups = this.itemList.activeGroups;
1525                 let i = Math.max(0, groups.indexOf(this.itemList.selectedGroup));
1526
1527                 i += idx == this.CTXT_DOWN ? 1 : -1;
1528                 i %= groups.length;
1529                 if (i < 0)
1530                     i += groups.length;
1531
1532                 var position = 0;
1533                 idx = [groups[i].context, 0];
1534                 break;
1535
1536             case this.PAGE_UP:
1537             case this.PAGE_DOWN:
1538                 idx = this.itemList.getRelativePage(idx == this.PAGE_DOWN ? 1 : -1);
1539                 break;
1540
1541             case this.RESET:
1542                 idx = null;
1543                 break;
1544
1545             default:
1546                 break;
1547             }
1548
1549             if (!fromTab)
1550                 this.wildIndex = this.wildtypes.length - 1;
1551
1552             if (idx && idx[1] >= idx[0].items.length) {
1553                 if (!idx[0].incomplete)
1554                     this.waiting = null;
1555                 else {
1556                     this.waiting = idx;
1557                     statusline.progress = _("completion.waitingForResults");
1558                 }
1559                 return;
1560             }
1561
1562             this.waiting = null;
1563
1564             this.itemList.select(idx, null, position);
1565             this.selected = idx;
1566
1567             this.preview();
1568
1569             if (this.selected == null)
1570                 statusline.progress = "";
1571             else
1572                 statusline.progress = _("completion.matchIndex",
1573                                         this.itemList.getOffset(idx),
1574                                         this.itemList.itemCount);
1575         },
1576
1577         /**
1578          * Selects a completion result based on the 'wildmode'
1579          * option, or the value of the *wildmode* parameter.
1580          *
1581          * @param {number} offset The positive or negative number of
1582          *      tab presses to process.
1583          * @param {[string]} wildmode A 'wildmode' value to
1584          *      substitute for the value of the 'wildmode' option.
1585          *      @optional
1586          */
1587         tab: function tab(offset, wildmode) {
1588             this.autocompleteTimer.flush();
1589             this.ignoredCount = 0;
1590
1591             if (this._caret != this.caret)
1592                 this.reset();
1593             this._caret = this.caret;
1594
1595             // Check if we need to run the completer.
1596             if (this.context.waitingForTab || this.wildIndex == -1)
1597                 this.complete(true, true);
1598
1599             this.wildtypes = wildmode || options["wildmode"];
1600             let count = Math.abs(offset);
1601             let steps = Math.constrain(this.wildtypes.length - this.wildIndex,
1602                                        1, count);
1603             count = Math.max(1, count - steps);
1604
1605             while (steps--) {
1606                 this.wildIndex = Math.min(this.wildIndex, this.wildtypes.length - 1);
1607                 switch (this.wildtype.replace(/.*:/, "")) {
1608                 case "":
1609                     this.select(this.nextItem(null));
1610                     break;
1611                 case "longest":
1612                     if (this.itemList.itemCount > 1) {
1613                         if (this.substring && this.substring.length > this.completion.length)
1614                             this.setCompletion(this.start, this.substring);
1615                         break;
1616                     }
1617                     // Fallthrough
1618                 case "full":
1619                     let c = steps ? 1 : count;
1620                     this.select(offset < 0 ? this.UP : this.DOWN, c, true);
1621                     break;
1622                 }
1623
1624                 if (this.haveType("list"))
1625                     this.itemList.visible = true;
1626
1627                 this.wildIndex++;
1628             }
1629
1630             if (this.items.length == 0 && !this.waiting)
1631                 dactyl.beep();
1632         }
1633     }),
1634
1635     /**
1636      * Evaluate a JavaScript expression and return a string suitable
1637      * to be echoed.
1638      *
1639      * @param {string} arg
1640      * @param {boolean} useColor When true, the result is a
1641      *     highlighted XML object.
1642      */
1643     echoArgumentToString: function (arg, useColor) {
1644         if (!arg)
1645             return "";
1646
1647         arg = dactyl.userEval(arg);
1648         if (isObject(arg))
1649             arg = util.objectToString(arg, useColor);
1650         else if (callable(arg))
1651             arg = String.replace(arg, "/* use strict */ \n", "/* use strict */ ");
1652         else if (!isString(arg) && useColor)
1653             arg = template.highlight(arg);
1654         return arg;
1655     }
1656 }, {
1657     commands: function initCommands() {
1658         [
1659             {
1660                 name: "ec[ho]",
1661                 description: "Echo the expression",
1662                 action: dactyl.echo
1663             },
1664             {
1665                 name: "echoe[rr]",
1666                 description: "Echo the expression as an error message",
1667                 action: dactyl.echoerr
1668             },
1669             {
1670                 name: "echom[sg]",
1671                 description: "Echo the expression as an informational message",
1672                 action: dactyl.echomsg
1673             }
1674         ].forEach(function (command) {
1675             commands.add([command.name],
1676                 command.description,
1677                 function (args) {
1678                     command.action(CommandLine.echoArgumentToString(args[0] || "", true));
1679                 }, {
1680                     completer: function (context) completion.javascript(context),
1681                     literal: 0
1682                 });
1683         });
1684
1685         commands.add(["mes[sages]"],
1686             "Display previously shown messages",
1687             function () {
1688                 // TODO: are all messages single line? Some display an aggregation
1689                 //       of single line messages at least. E.g. :source
1690                 if (commandline._messageHistory.length == 1) {
1691                     let message = commandline._messageHistory.messages[0];
1692                     commandline.echo(message.message, message.highlight, commandline.FORCE_SINGLELINE);
1693                 }
1694                 else if (commandline._messageHistory.length > 1) {
1695                     commandline.commandOutput(
1696                         template.map(commandline._messageHistory.messages, function (message)
1697                            ["div", { highlight: message.highlight + " Message" },
1698                                message.message]));
1699                 }
1700             },
1701             { argCount: "0" });
1702
1703         commands.add(["messc[lear]"],
1704             "Clear the message history",
1705             function () { commandline._messageHistory.clear(); },
1706             { argCount: "0" });
1707
1708         commands.add(["sil[ent]"],
1709             "Run a command silently",
1710             function (args) {
1711                 commandline.runSilently(function () commands.execute(args[0] || "", null, true));
1712             }, {
1713                 completer: function (context) completion.ex(context),
1714                 literal: 0,
1715                 subCommand: 0
1716             });
1717     },
1718     modes: function initModes() {
1719         initModes.require("editor");
1720
1721         modes.addMode("COMMAND_LINE", {
1722             char: "c",
1723             description: "Active when the command line is focused",
1724             insert: true,
1725             ownsFocus: true,
1726             get mappingSelf() commandline.commandSession
1727         });
1728         // this._extended modes, can include multiple modes, and even main modes
1729         modes.addMode("EX", {
1730             description: "Ex command mode, active when the command line is open for Ex commands",
1731             bases: [modes.COMMAND_LINE]
1732         });
1733         modes.addMode("PROMPT", {
1734             description: "Active when a prompt is open in the command line",
1735             bases: [modes.COMMAND_LINE]
1736         });
1737
1738         modes.addMode("INPUT_MULTILINE", {
1739             description: "Active when the command line's multiline input buffer is open",
1740             bases: [modes.INSERT]
1741         });
1742     },
1743     mappings: function initMappings() {
1744
1745         mappings.add([modes.COMMAND],
1746             [":"], "Enter Command Line mode",
1747             function () { CommandExMode().open(""); });
1748
1749         mappings.add([modes.INPUT_MULTILINE],
1750             ["<Return>", "<C-j>", "<C-m>"], "Begin a new line",
1751             function ({ self }) {
1752                 let text = "\n" + commandline.widgets.multilineInput
1753                                              .value.substr(0, commandline.widgets.multilineInput.selectionStart)
1754                          + "\n";
1755
1756                 let index = text.indexOf(self.end);
1757                 if (index >= 0) {
1758                     self.done = true;
1759                     text = text.substring(1, index);
1760                     modes.pop();
1761
1762                     return function () self.callback.call(commandline, text);
1763                 }
1764                 return Events.PASS;
1765             });
1766
1767         let bind = function bind(...args) mappings.add.apply(mappings, [[modes.COMMAND_LINE]].concat(args));
1768
1769         bind(["<Esc>", "<C-[>"], "Stop waiting for completions or exit Command Line mode",
1770              function ({ self }) {
1771                  if (self.completions && self.completions.waiting)
1772                      self.completions.waiting = null;
1773                  else
1774                      return Events.PASS;
1775              });
1776
1777         // Any "non-keyword" character triggers abbreviation expansion
1778         // TODO: Add "<CR>" and "<Tab>" to this list
1779         //       At the moment, adding "<Tab>" breaks tab completion. Adding
1780         //       "<CR>" has no effect.
1781         // TODO: Make non-keyword recognition smarter so that there need not
1782         //       be two lists of the same characters (one here and a regexp in
1783         //       mappings.js)
1784         bind(["<Space>", '"', "'"], "Expand command line abbreviation",
1785              function ({ self }) {
1786                  self.resetCompletions();
1787                  editor.expandAbbreviation(modes.COMMAND_LINE);
1788                  return Events.PASS;
1789              });
1790
1791         bind(["<Return>", "<C-j>", "<C-m>"], "Accept the current input",
1792              function ({ self }) {
1793                  if (self.completions)
1794                      self.completions.tabTimer.flush();
1795
1796                  let command = commandline.command;
1797
1798                  self.accepted = true;
1799                  return function () { modes.pop(); };
1800              });
1801
1802         [
1803             [["<Up>", "<A-p>", "<cmd-prev-match>"],   "previous matching", true,  true],
1804             [["<S-Up>", "<C-p>", "<cmd-prev>"],       "previous",          true,  false],
1805             [["<Down>", "<A-n>", "<cmd-next-match>"], "next matching",     false, true],
1806             [["<S-Down>", "<C-n>", "<cmd-next>"],     "next",              false, false]
1807         ].forEach(function ([keys, desc, up, search]) {
1808             bind(keys, "Recall the " + desc + " command line from the history list",
1809                  function ({ self }) {
1810                      dactyl.assert(self.history);
1811                      self.history.select(up, search);
1812                  });
1813         });
1814
1815         bind(["<A-Tab>", "<Tab>", "<A-compl-next>", "<compl-next>"],
1816              "Select the next matching completion item",
1817              function ({ keypressEvents, self }) {
1818                  dactyl.assert(self.completions);
1819                  self.completions.onTab(keypressEvents[0]);
1820              });
1821
1822         bind(["<A-S-Tab>", "<S-Tab>", "<A-compl-prev>", "<compl-prev>"],
1823              "Select the previous matching completion item",
1824              function ({ keypressEvents, self }) {
1825                  dactyl.assert(self.completions);
1826                  self.completions.onTab(keypressEvents[0]);
1827              });
1828
1829         bind(["<C-Tab>", "<A-f>", "<compl-next-group>"],
1830              "Select the next matching completion group",
1831              function ({ keypressEvents, self }) {
1832                  dactyl.assert(self.completions);
1833                  self.completions.tabTimer.flush();
1834                  self.completions.select(self.completions.CTXT_DOWN);
1835              });
1836
1837         bind(["<C-S-Tab>", "<A-S-f>", "<compl-prev-group>"],
1838              "Select the previous matching completion group",
1839              function ({ keypressEvents, self }) {
1840                  dactyl.assert(self.completions);
1841                  self.completions.tabTimer.flush();
1842                  self.completions.select(self.completions.CTXT_UP);
1843              });
1844
1845         bind(["<C-f>", "<PageDown>", "<compl-next-page>"],
1846              "Select the next page of completions",
1847              function ({ keypressEvents, self }) {
1848                  dactyl.assert(self.completions);
1849                  self.completions.tabTimer.flush();
1850                  self.completions.select(self.completions.PAGE_DOWN);
1851              });
1852
1853         bind(["<C-b>", "<PageUp>", "<compl-prev-page>"],
1854              "Select the previous page of completions",
1855              function ({ keypressEvents, self }) {
1856                  dactyl.assert(self.completions);
1857                  self.completions.tabTimer.flush();
1858                  self.completions.select(self.completions.PAGE_UP);
1859              });
1860
1861         bind(["<BS>", "<C-h>"], "Delete the previous character",
1862              function () {
1863                  if (!commandline.command)
1864                      modes.pop();
1865                  else
1866                      return Events.PASS;
1867              });
1868
1869         bind(["<C-]>", "<C-5>"], "Expand command line abbreviation",
1870              function () { editor.expandAbbreviation(modes.COMMAND_LINE); });
1871     },
1872     options: function initOptions() {
1873         options.add(["history", "hi"],
1874             "Number of Ex commands and search patterns to store in the command-line history",
1875             "number", 500,
1876             { validator: function (value) value >= 0 });
1877
1878         options.add(["maxitems"],
1879             "Maximum number of completion items to display at once",
1880             "number", 20,
1881             { validator: function (value) value >= 1 });
1882
1883         options.add(["messages", "msgs"],
1884             "Number of messages to store in the :messages history",
1885             "number", 100,
1886             { validator: function (value) value >= 0 });
1887     },
1888     sanitizer: function initSanitizer() {
1889         sanitizer.addItem("commandline", {
1890             description: "Command-line and search history",
1891             persistent: true,
1892             action: function (timespan, host) {
1893                 let store = commandline._store;
1894                 for (let [k, v] in store) {
1895                     if (k == "command")
1896                         store.set(k, v.filter(function (item)
1897                             !(timespan.contains(item.timestamp) && (!host || commands.hasDomain(item.value, host)))));
1898                     else if (!host)
1899                         store.set(k, v.filter(function (item) !timespan.contains(item.timestamp)));
1900                 }
1901             }
1902         });
1903         // Delete history-like items from the commandline and messages on history purge
1904         sanitizer.addItem("history", {
1905             action: function (timespan, host) {
1906                 commandline._store.set("command",
1907                     commandline._store.get("command", []).filter(function (item)
1908                         !(timespan.contains(item.timestamp) && (host ? commands.hasDomain(item.value, host)
1909                                                                      : item.privateData))));
1910
1911                 commandline._messageHistory.filter(function (item) !timespan.contains(item.timestamp * 1000) ||
1912                     !item.domains && !item.privateData ||
1913                     host && (!item.domains || !item.domains.some(function (d) util.isSubdomain(d, host))));
1914             }
1915         });
1916         sanitizer.addItem("messages", {
1917             description: "Saved :messages",
1918             action: function (timespan, host) {
1919                 commandline._messageHistory.filter(function (item) !timespan.contains(item.timestamp * 1000) ||
1920                     host && (!item.domains || !item.domains.some(function (d) util.isSubdomain(d, host))));
1921             }
1922         });
1923     }
1924 });
1925
1926 /**
1927  * The list which is used for the completion box.
1928  *
1929  * @param {string} id The id of the iframe which will display the list. It
1930  *     must be in its own container element, whose height it will update as
1931  *     necessary.
1932  */
1933
1934 var ItemList = Class("ItemList", {
1935     CONTEXT_LINES: 2,
1936
1937     init: function init(frame) {
1938         this.frame = frame;
1939
1940         this.doc = frame.contentDocument;
1941         this.win = frame.contentWindow;
1942         this.body = this.doc.body;
1943         this.container = frame.parentNode;
1944
1945         highlight.highlightNode(this.doc.body, "Comp");
1946
1947         this._onResize = Timer(20, 400, function _onResize(event) {
1948             if (this.visible)
1949                 this.onResize(event);
1950         }, this);
1951         this._resize = Timer(20, 400, function _resize(flags) {
1952             if (this.visible)
1953                 this.resize(flags);
1954         }, this);
1955
1956         DOM(this.win).resize(this._onResize.closure.tell);
1957     },
1958
1959     get rootXML()
1960         ["div", { highlight: "Normal", style: "white-space: nowrap", key: "root" },
1961             ["div", { key: "wrapper" },
1962                 ["div", { highlight: "Completions", key: "noCompletions" },
1963                     ["span", { highlight: "Title" },
1964                         _("completion.noCompletions")]],
1965                 ["div", { key: "completions" }]],
1966
1967             ["div", { highlight: "Completions" },
1968                 template.map(util.range(0, options["maxitems"] * 2), function (i)
1969                     ["div", { highlight: "CompItem NonText" },
1970                         "~"])]],
1971
1972     get itemCount() this.context.contextList
1973                         .reduce(function (acc, ctxt) acc + ctxt.items.length, 0),
1974
1975     get visible() !this.container.collapsed,
1976     set visible(val) this.container.collapsed = !val,
1977
1978     get activeGroups() this.context.contextList
1979                            .filter(function (c) c.items.length || c.message || c.incomplete)
1980                            .map(this.getGroup, this),
1981
1982     get selected() let (g = this.selectedGroup) g && g.selectedIdx != null
1983         ? [g.context, g.selectedIdx] : null,
1984
1985     getRelativeItem: function getRelativeItem(offset, tuple, noWrap) {
1986         let groups = this.activeGroups;
1987         if (!groups.length)
1988             return null;
1989
1990         let group = this.selectedGroup || groups[0];
1991         let start = group.selectedIdx || 0;
1992         if (tuple === null) { // Kludge.
1993             if (offset > 0)
1994                 tuple = [this.activeGroups[0], -1];
1995             else {
1996                 let group = this.activeGroups.slice(-1)[0];
1997                 tuple = [group, group.itemCount];
1998             }
1999         }
2000         if (tuple)
2001             [group, start] = tuple;
2002
2003         group = this.getGroup(group);
2004
2005         start = (group.offsets.start + start + offset);
2006         if (!noWrap)
2007             start %= this.itemCount || 1;
2008         if (start < 0 && (!noWrap || arguments[1] === null))
2009             start += this.itemCount;
2010
2011         if (noWrap && offset > 0) {
2012             // Check if we've passed any incomplete contexts
2013
2014             let i = groups.indexOf(group);
2015             util.assert(i >= 0, undefined, false);
2016             for (; i < groups.length; i++) {
2017                 let end = groups[i].offsets.start + groups[i].itemCount;
2018                 if (start >= end && groups[i].context.incomplete)
2019                     return [groups[i].context, start - groups[i].offsets.start];
2020
2021                 if (start >= end);
2022                     break;
2023             }
2024         }
2025
2026         if (start < 0 || start >= this.itemCount)
2027             return null;
2028
2029         group = array.nth(groups, function (g) let (i = start - g.offsets.start) i >= 0 && i < g.itemCount, 0);
2030         return [group.context, start - group.offsets.start];
2031     },
2032
2033     getRelativePage: function getRelativePage(offset, tuple, noWrap) {
2034         offset *= this.maxItems;
2035         // Try once with wrapping disabled.
2036         let res = this.getRelativeItem(offset, tuple, true);
2037
2038         if (!res) {
2039             // Wrapped.
2040             let sign = offset / Math.abs(offset);
2041
2042             let off = this.getOffset(tuple === null ? null : tuple || this.selected);
2043             if (off == null)
2044                 // Unselected. Defer to getRelativeItem.
2045                 res = this.getRelativeItem(offset, null, noWrap);
2046             else if (~[0, this.itemCount - 1].indexOf(off))
2047                 // At start or end. Jump to other end.
2048                 res = this.getRelativeItem(sign, null, noWrap);
2049             else
2050                 // Wrapped. Go to beginning or end.
2051                 res = this.getRelativeItem(-sign, null);
2052         }
2053         return res;
2054     },
2055
2056     /**
2057      * Initializes the ItemList for use with a new root completion
2058      * context.
2059      *
2060      * @param {CompletionContext} context The new root context.
2061      */
2062     open: function open(context) {
2063         this.context = context;
2064         this.nodes = {};
2065         this.container.height = 0;
2066         this.minHeight = 0;
2067         this.maxItems  = options["maxitems"];
2068
2069         DOM(this.rootXML, this.doc, this.nodes)
2070             .appendTo(DOM(this.body).empty());
2071
2072         this.update();
2073     },
2074
2075     /**
2076      * Updates the absolute result indices of all groups after
2077      * results have changed.
2078      * @private
2079      */
2080     updateOffsets: function updateOffsets() {
2081         let total = this.itemCount;
2082         let count = 0;
2083         for (let group in values(this.activeGroups)) {
2084             group.offsets = { start: count, end: total - count - group.itemCount };
2085             count += group.itemCount;
2086         }
2087     },
2088
2089     /**
2090      * Updates the set and state of active groups for a new set of
2091      * completion results.
2092      */
2093     update: function update() {
2094         DOM(this.nodes.completions).empty();
2095
2096         let container = DOM(this.nodes.completions);
2097         let groups = this.activeGroups;
2098         for (let group in values(groups)) {
2099             group.reset();
2100             container.append(group.nodes.root);
2101         }
2102
2103         this.updateOffsets();
2104
2105         DOM(this.nodes.noCompletions).toggle(!groups.length);
2106
2107         this.startPos = null;
2108         this.select(groups[0] && groups[0].context, null);
2109
2110         this._resize.tell();
2111     },
2112
2113     /**
2114      * Updates the group for *context* after an asynchronous update
2115      * push.
2116      *
2117      * @param {CompletionContext} context The context which has
2118      *      changed.
2119      */
2120     updateContext: function updateContext(context) {
2121         let group = this.getGroup(context);
2122         this.updateOffsets();
2123
2124         if (~this.activeGroups.indexOf(group))
2125             group.update();
2126         else {
2127             DOM(group.nodes.root).remove();
2128             if (this.selectedGroup == group)
2129                 this.selectedGroup = null;
2130         }
2131
2132         let g = this.selectedGroup;
2133         this.select(g, g && g.selectedIdx);
2134     },
2135
2136     /**
2137      * Updates the DOM to reflect the current state of all groups.
2138      * @private
2139      */
2140     draw: function draw() {
2141         for (let group in values(this.activeGroups))
2142             group.draw();
2143
2144         // We need to collect all of the rescrolling functions in
2145         // one go, as the height calculation that they need to do
2146         // would force a reflow after each DOM modification.
2147         this.activeGroups.filter(function (g) !g.collapsed)
2148             .map(function (g) g.rescrollFunc)
2149             .forEach(call);
2150
2151         if (!this.selected)
2152             this.win.scrollTo(0, 0);
2153
2154         this._resize.tell(ItemList.RESIZE_BRIEF);
2155     },
2156
2157     onResize: function onResize() {
2158         if (this.selectedGroup)
2159             this.selectedGroup.rescrollFunc();
2160     },
2161
2162     minHeight: 0,
2163
2164     /**
2165      * Resizes the list after an update.
2166      * @private
2167      */
2168     resize: function resize(flags) {
2169         let { completions, root } = this.nodes;
2170
2171         if (!this.visible)
2172             root.style.minWidth = document.getElementById("dactyl-commandline").scrollWidth + "px";
2173
2174         let { minHeight } = this;
2175         if (mow.visible && this.isAboveMow) // Kludge.
2176             minHeight -= mow.wantedHeight;
2177
2178         let needed = this.win.scrollY + DOM(completions).rect.bottom;
2179         this.minHeight = Math.max(minHeight, needed);
2180
2181         if (!this.visible)
2182             root.style.minWidth = "";
2183
2184         let height = this.visible ? parseFloat(this.container.height) : 0;
2185         if (this.minHeight <= minHeight || !mow.visible)
2186             this.container.height = Math.min(this.minHeight,
2187                                              height + config.outputHeight - mow.spaceNeeded);
2188         else {
2189             // FIXME: Belongs elsewhere.
2190             mow.resize(false, Math.max(0, this.minHeight - this.container.height));
2191
2192             this.container.height = this.minHeight - mow.spaceNeeded;
2193             mow.resize(false);
2194             this.timeout(function () {
2195                 this.container.height -= mow.spaceNeeded;
2196             });
2197         }
2198     },
2199
2200     /**
2201      * Selects the item at the given *group* and *index*.
2202      *
2203      * @param {CompletionContext|[CompletionContext,number]} *group* The
2204      *      completion context to select, or a tuple specifying the
2205      *      context and item index.
2206      * @param {number} index The item index in *group* to select.
2207      * @param {number} position If non-null, try to position the
2208      *      selected item at the *position*th row from the top of
2209      *      the screen. Note that at least {@link #CONTEXT_LINES}
2210      *      lines will be visible above and below the selected item
2211      *      unless there aren't enough results to make this possible.
2212      *      @optional
2213      */
2214     select: function select(group, index, position) {
2215         if (isArray(group))
2216             [group, index] = group;
2217
2218         group = this.getGroup(group);
2219
2220         if (this.selectedGroup && (!group || group != this.selectedGroup))
2221             this.selectedGroup.selectedIdx = null;
2222
2223         this.selectedGroup = group;
2224
2225         if (group)
2226             group.selectedIdx = index;
2227
2228         let groups = this.activeGroups;
2229
2230         if (position != null || !this.startPos && groups.length)
2231             this.startPos = [group || groups[0], position || 0];
2232
2233         if (groups.length) {
2234             group = group || groups[0];
2235             let idx = groups.indexOf(group);
2236
2237             let start  = this.startPos[0].getOffset(this.startPos[1]);
2238             if (group) {
2239                 let idx = group.selectedIdx || 0;
2240                 let off = group.getOffset(idx);
2241
2242                 start = Math.constrain(start,
2243                                        off + Math.min(this.CONTEXT_LINES,
2244                                                       group.itemCount - idx + group.offsets.end)
2245                                            - this.maxItems + 1,
2246                                        off - Math.min(this.CONTEXT_LINES,
2247                                                       idx + group.offsets.start));
2248             }
2249
2250             let count = this.maxItems;
2251             for (let group in values(groups)) {
2252                 let off = Math.max(0, start - group.offsets.start);
2253
2254                 group.count = Math.constrain(group.itemCount - off, 0, count);
2255                 count -= group.count;
2256
2257                 group.collapsed = group.offsets.start >= start + this.maxItems
2258                                || group.offsets.start + group.itemCount < start;
2259
2260                 group.range = ItemList.Range(off, off + group.count);
2261
2262                 if (!startPos)
2263                     var startPos = [group, group.range.start];
2264             }
2265             this.startPos = startPos;
2266         }
2267         this.draw();
2268     },
2269
2270     /**
2271      * Returns an ItemList group for the given completion context,
2272      * creating one if necessary.
2273      *
2274      * @param {CompletionContext} context
2275      * @returns {ItemList.Group}
2276      */
2277     getGroup: function getGroup(context)
2278         context instanceof ItemList.Group ? context
2279                                           : context && context.getCache("itemlist-group",
2280                                                                         bind("Group", ItemList, this, context)),
2281
2282     getOffset: function getOffset(tuple) tuple && this.getGroup(tuple[0]).getOffset(tuple[1])
2283 }, {
2284     RESIZE_BRIEF: 1 << 0,
2285
2286     WAITING_MESSAGE: _("completion.generating"),
2287
2288     Group: Class("ItemList.Group", {
2289         init: function init(parent, context) {
2290             this.parent  = parent;
2291             this.context = context;
2292             this.offsets = {};
2293             this.range   = ItemList.Range(0, 0);
2294         },
2295
2296         get rootXML()
2297             ["div", { key: "root", highlight: "CompGroup" },
2298                 ["div", { highlight: "Completions" },
2299                     this.context.createRow(this.context.title || [], "CompTitle")],
2300                 ["div", { highlight: "CompTitleSep" }],
2301                 ["div", { key: "contents" },
2302                     ["div", { key: "up", highlight: "CompLess" }],
2303                     ["div", { key: "message", highlight: "CompMsg" },
2304                         this.context.message || []],
2305                     ["div", { key: "itemsContainer", class: "completion-items-container" },
2306                         ["div", { key: "items", highlight: "Completions" }]],
2307                     ["div", { key: "waiting", highlight: "CompMsg" },
2308                         ItemList.WAITING_MESSAGE],
2309                     ["div", { key: "down", highlight: "CompMore" }]]],
2310
2311         get doc() this.parent.doc,
2312         get win() this.parent.win,
2313         get maxItems() this.parent.maxItems,
2314
2315         get itemCount() this.context.items.length,
2316
2317         /**
2318          * Returns a function which will update the scroll offsets
2319          * and heights of various DOM members.
2320          * @private
2321          */
2322         get rescrollFunc() {
2323             let container = this.nodes.itemsContainer;
2324             let pos    = DOM(container).rect.top;
2325             let start  = DOM(this.getRow(this.range.start)).rect.top;
2326             let height = DOM(this.getRow(this.range.end - 1)).rect.bottom - start || 0;
2327             let scroll = start + container.scrollTop - pos;
2328
2329             let win = this.win;
2330             let row = this.selectedRow;
2331             if (row && this.parent.minHeight) {
2332                 let { rect } = DOM(this.selectedRow);
2333                 var scrollY = this.win.scrollY + rect.bottom - this.win.innerHeight;
2334             }
2335
2336             return function () {
2337                 container.style.height = height + "px";
2338                 container.scrollTop = scroll;
2339                 if (scrollY != null)
2340                     win.scrollTo(0, Math.max(scrollY, 0));
2341             };
2342         },
2343
2344         /**
2345          * Reset this group for use with a new set of results.
2346          */
2347         reset: function reset() {
2348             this.nodes = {};
2349             this.generatedRange = ItemList.Range(0, 0);
2350
2351             DOM.fromJSON(this.rootXML, this.doc, this.nodes);
2352         },
2353
2354         /**
2355          * Update this group after an asynchronous results push.
2356          */
2357         update: function update() {
2358             this.generatedRange = ItemList.Range(0, 0);
2359             DOM(this.nodes.items).empty();
2360
2361             if (this.context.message)
2362                 DOM(this.nodes.message).empty()
2363                     .append(DOM.fromJSON(this.context.message, this.doc));
2364
2365             if (this.selectedIdx > this.itemCount)
2366                 this.selectedIdx = null;
2367         },
2368
2369         /**
2370          * Updates the DOM to reflect the current state of this
2371          * group.
2372          * @private
2373          */
2374         draw: function draw() {
2375             DOM(this.nodes.contents).toggle(!this.collapsed);
2376             if (this.collapsed)
2377                 return;
2378
2379             DOM(this.nodes.message).toggle(this.context.message && this.range.start == 0);
2380             DOM(this.nodes.waiting).toggle(this.context.incomplete && this.range.end <= this.itemCount);
2381             DOM(this.nodes.up).toggle(this.range.start > 0);
2382             DOM(this.nodes.down).toggle(this.range.end < this.itemCount);
2383
2384             if (!this.generatedRange.contains(this.range)) {
2385                 if (this.generatedRange.end == 0)
2386                     var [start, end] = this.range;
2387                 else {
2388                     start = this.range.start - (this.range.start <= this.generatedRange.start
2389                                                     ? this.maxItems / 2 : 0);
2390                     end   = this.range.end   + (this.range.end > this.generatedRange.end
2391                                                     ? this.maxItems / 2 : 0);
2392                 }
2393
2394                 let range = ItemList.Range(Math.max(0, start - start % 2),
2395                                            Math.min(this.itemCount, end));
2396
2397                 let first;
2398                 for (let [i, row] in this.context.getRows(this.generatedRange.start,
2399                                                           this.generatedRange.end,
2400                                                           this.doc))
2401                     if (!range.contains(i))
2402                         DOM(row).remove();
2403                     else if (!first)
2404                         first = row;
2405
2406                 let container = DOM(this.nodes.items);
2407                 let before    = first ? DOM(first).closure.before
2408                                       : DOM(this.nodes.items).closure.append;
2409
2410                 for (let [i, row] in this.context.getRows(range.start, range.end,
2411                                                           this.doc)) {
2412                     if (i < this.generatedRange.start)
2413                         before(row);
2414                     else if (i >= this.generatedRange.end)
2415                         container.append(row);
2416                     if (i == this.selectedIdx)
2417                         this.selectedIdx = this.selectedIdx;
2418                 }
2419
2420                 this.generatedRange = range;
2421             }
2422         },
2423
2424         getRow: function getRow(idx) this.context.getRow(idx, this.doc),
2425
2426         getOffset: function getOffset(idx) this.offsets.start + (idx || 0),
2427
2428         get selectedRow() this.getRow(this._selectedIdx),
2429
2430         get selectedIdx() this._selectedIdx,
2431         set selectedIdx(idx) {
2432             if (this.selectedRow && this._selectedIdx != idx)
2433                 DOM(this.selectedRow).attr("selected", null);
2434
2435             this._selectedIdx = idx;
2436
2437             if (this.selectedRow)
2438                 DOM(this.selectedRow).attr("selected", true);
2439         }
2440     }),
2441
2442     Range: Class.Memoize(function () {
2443         let Range = Struct("ItemList.Range", "start", "end");
2444         update(Range.prototype, {
2445             contains: function contains(idx)
2446                 typeof idx == "number" ? idx >= this.start && idx < this.end
2447                                        : this.contains(idx.start) &&
2448                                          idx.end >= this.start && idx.end <= this.end
2449         });
2450         return Range;
2451     })
2452 });
2453
2454 // vim: set fdm=marker sw=4 sts=4 ts=8 et: