contrib/xrev: support osKey, simplify display, style, whitespace
[conkeror.git] / modules / buffer.js
blob23771e298490e28c2b2abe573f580db7e5a723bf
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007-2012 John J. Foerch
4  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
5  *
6  * Use, modification, and distribution are subject to the terms specified in the
7  * COPYING file.
8 **/
10 var define_buffer_local_hook = local_hook_definer("window");
12 function define_current_buffer_hook (hook_name, existing_hook) {
13     define_buffer_local_hook(hook_name);
14     add_hook(existing_hook, function (buffer) {
15             if (!buffer.window.buffers || buffer != buffer.window.buffers.current)
16                 return;
17             var hook = conkeror[hook_name];
18             hook.run.apply(hook, Array.prototype.slice.call(arguments));
19         });
22 define_buffer_local_hook("buffer_title_change_hook");
23 define_buffer_local_hook("buffer_description_change_hook");
24 define_buffer_local_hook("buffer_icon_change_hook");
25 define_buffer_local_hook("select_buffer_hook");
26 define_buffer_local_hook("create_buffer_early_hook");
27 define_buffer_local_hook("create_buffer_late_hook");
28 define_buffer_local_hook("create_buffer_hook");
29 define_buffer_local_hook("kill_buffer_hook");
30 define_buffer_local_hook("move_buffer_hook");
31 define_buffer_local_hook("buffer_scroll_hook");
32 define_buffer_local_hook("buffer_dom_content_loaded_hook");
33 define_buffer_local_hook("buffer_loaded_hook");
34 define_buffer_local_hook("set_input_mode_hook");
35 define_buffer_local_hook("zoom_hook");
37 define_current_buffer_hook("current_buffer_title_change_hook", "buffer_title_change_hook");
38 define_current_buffer_hook("current_buffer_description_change_hook", "buffer_description_change_hook");
39 define_current_buffer_hook("current_buffer_icon_change_hook", "buffer_icon_change_hook");
40 define_current_buffer_hook("current_buffer_scroll_hook", "buffer_scroll_hook");
41 define_current_buffer_hook("current_buffer_dom_content_loaded_hook", "buffer_dom_content_loaded_hook");
42 define_current_buffer_hook("current_buffer_zoom_hook", "zoom_hook");
45 function buffer_position_before (container, b, i) {
46     return i;
49 function buffer_position_after (container, b, i) {
50     return i + 1;
53 function buffer_position_end (container, b, i) {
54     return container.count;
57 function buffer_position_end_by_type (container, b, i) {
58     // after last buffer of same type
59     var count = container.count;
60     var p = count - 1;
61     while (p >= 0 &&
62            container.get_buffer(p).constructor != b.constructor)
63     {
64         p--;
65     }
66     if (p == -1)
67         return count;
68     else
69         return p + 1;
72 define_variable("new_buffer_position", buffer_position_end,
73     "Used to compute the position in the buffer-list at which "+
74     "to insert new buffers which do not have an opener.  These "+
75     "include buffers created by typing an url or webjump, or "+
76     "buffers created via command-line remoting.  The value "+
77     "should be a number giving the index or a function of three "+
78     "arguments that returns the index at which to insert the "+
79     "new buffer.  The first argument is the buffer_container "+
80     "into which the new buffer is being inserted.  The second "+
81     "argument is the buffer to be inserted.  The third argument "+
82     "is the position of the currently selected buffer.  Several "+
83     "such functions are provided, including, buffer_position_before, "+
84     "buffer_position_after, buffer_position_end, and "+
85     "buffer_position_end_by_type.");
87 define_variable("new_buffer_with_opener_position", buffer_position_after,
88     "Used to compute the position in the buffer-list at which "+
89     "to insert new buffers which have an opener in the same "+
90     "window.  These include buffers created by following a link "+
91     "or frame, and contextual help buffers.  The allowed values "+
92     "are the same as those for `new_buffer_position', except that "+
93     "the second argument passed to the function is the index of "+
94     "the opener instead of the index of the current buffer (often "+
95     "one and the same).");
97 define_variable("bury_buffer_position", null,
98     "Used to compute the position in the buffer-list to move a "+
99     "buried buffer to.  A value of null prevents bury-buffer "+
100     "from moving the buffer at all.  Other allowed values are "+
101     "the same as those for `new_buffer_position', except that "+
102     "the second argument passed to the function is the index of "+
103     "the new buffer that will be selected after burying the "+
104     "current buffer.");
106 define_variable("allow_browser_window_close", true,
107     "If this is set to true, if a content buffer page calls " +
108     "window.close() from JavaScript and is not prevented by the " +
109     "normal Mozilla mechanism that restricts pages from closing " +
110     "a window that was not opened by a script, the buffer will be " +
111     "killed, deleting the window as well if it is the only buffer.");
113 define_keywords("$opener", "$position");
114 function buffer_creator (type) {
115     var args = forward_keywords(arguments);
116     return function (window) {
117         return new type(window, args);
118     };
121 function buffer_modality (buffer) {
122     buffer.keymaps.push(default_global_keymap);
125 function buffer (window) {
126     this.constructor_begin();
127     keywords(arguments, $position = this.default_position);
128     this.opener = arguments.$opener;
129     this.window = window;
130     var element = create_XUL(window, "vbox");
131     element.setAttribute("flex", "1");
132     var browser = create_XUL(window, "browser");
133     browser.setAttribute("type", "content");
134     browser.setAttribute("flex", "1");
135     browser.setAttribute("autocompletepopup", "popup_autocomplete");
136     element.appendChild(browser);
137     this.window.buffers.container.appendChild(element);
138     this.window.buffers.insert(this, arguments.$position, this.opener);
139     this.window.buffers.buffer_history.push(this);
140     this.element = element;
141     this.browser = element.firstChild;
142     this.element.conkeror_buffer_object = this;
144     this.local = { __proto__: conkeror };
145     this.page = null;
146     this.enabled_modes = [];
147     this.default_browser_object_classes = {};
149     var buffer = this;
151     this.browser.addEventListener("scroll", function (event) {
152             buffer_scroll_hook.run(buffer);
153         }, true /* capture */);
155     this.browser.addEventListener("DOMContentLoaded", function (event) {
156             buffer_dom_content_loaded_hook.run(buffer);
157         }, true /* capture */);
159     this.window.setTimeout(function () { create_buffer_late_hook.run(buffer); }, 0);
161     this.browser.addEventListener("load", function (event) {
162             if (event.target == buffer.document)
163                 buffer_loaded_hook.run(buffer);
164         }, true /* capture */);
166     this.browser.addEventListener("DOMWindowClose", function (event) {
167             /* This call to preventDefault is very important; without
168              * it, somehow Mozilla does something bad and as a result
169              * the window loses focus, causing keyboard commands to
170              * stop working. */
171             event.preventDefault();
173             if (allow_browser_window_close)
174                 kill_buffer(buffer, true);
175         }, true);
177     this.browser.addEventListener("focus", function (event) {
178         if (buffer.focusblocker &&
179             event.target instanceof Ci.nsIDOMHTMLElement &&
180             buffer.focusblocker(buffer, event))
181         {
182             event.target.blur();
183         } else
184             buffer.set_input_mode();
185     }, true);
187     this.browser.addEventListener("blur", function (event) {
188         buffer.set_input_mode();
189     }, true);
191     this.modalities = [buffer_modality];
193     // When create_buffer_early_hook runs, basic buffer properties
194     // will be available, but not the properties subclasses.
195     create_buffer_early_hook.run(this);
197     this.constructor_end();
199 buffer.prototype = {
200     constructor: buffer,
201     toString: function () "#<buffer>",
203     // default_position is the default value for the $position keyword to
204     // the buffer constructor.  This property can be set on the prototype
205     // of a subclass in order to override new_buffer_position and
206     // new_buffer_with_opener_position for specific types of buffers.
207     default_position: null,
209     /* Saved focus state */
210     saved_focused_frame: null,
211     saved_focused_element: null,
213     clear_saved_focus: function () {
214         this.saved_focused_frame = null;
215         this.saved_focused_element = null;
216     },
218     // get title ()   [must be defined by subclasses]
219     // get name ()    [must be defined by subclasses]
220     dead: false, /* This is set when the buffer is killed */
222     keymaps: null,
223     mark_active: false,
225     // The property focusblocker is available for an external module to
226     // put a function on which takes a buffer as its argument and returns
227     // true to block a focus event, or false to let normal processing
228     // occur.  Having this one property explicitly handled by the buffer
229     // class allows for otherwise modular focus-blockers.
230     focusblocker: null,
232     // icon is a string url of an icon to use for this buffer.  Setting it
233     // causes buffer_icon_change_hook to be run.
234     _icon: null,
235     get icon () this._icon,
236     set icon (x) {
237         if (this._icon != x) {
238             this._icon = x;
239             buffer_icon_change_hook.run(this);
240         }
241     },
243     default_message: "",
245     set_default_message: function (str) {
246         this.default_message = str;
247         if (this == this.window.buffers.current)
248             this.window.minibuffer.set_default_message(str);
249     },
251     constructors_running: 0,
253     constructor_begin: function () {
254         this.constructors_running++;
255     },
257     constructor_end: function () {
258         if (--this.constructors_running == 0) {
259             create_buffer_hook.run(this);
260             this.set_input_mode();
261             delete this.opener;
262         }
263     },
265     destroy: function () {
266         this.dead = true;
267         this.browser = null;
268         this.element = null;
269         this.saved_focused_frame = null;
270         this.saved_focused_element = null;
271         // prevent modalities from accessing dead browser
272         this.modalities = [];
273     },
275     set_input_mode: function () {
276         if (this != this.window.buffers.current)
277             return;
278         this.keymaps = [];
279         this.modalities.map(function (m) m(this), this);
280         set_input_mode_hook.run(this);
281     },
283     override_keymaps: function (keymaps) {
284         if (keymaps) {
285             this.keymaps = keymaps;
286             this.set_input_mode = function () {
287                 set_input_mode_hook.run(this);
288             };
289         } else
290             delete this.set_input_mode;
291         this.set_input_mode();
292     },
294     /* Browser accessors */
295     get top_frame () { return this.browser.contentWindow; },
296     get document () { return this.browser.contentDocument; },
297     get web_navigation () { return this.browser.webNavigation; },
298     get doc_shell () { return this.browser.docShell; },
299     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
300     get current_uri () { return this.browser.currentURI; },
302     is_child_element: function (element) {
303         return (element && this.is_child_frame(element.ownerDocument.defaultView));
304     },
306     is_child_frame: function (frame) {
307         return (frame && frame.top == this.top_frame);
308     },
310     // This method is like focused_frame, except that if no content
311     // frame actually has focus, this returns null.
312     get focused_frame_or_null () {
313         var frame = this.window.document.commandDispatcher.focusedWindow;
314         if (this.is_child_frame(frame))
315             return frame;
316         return null;
317     },
319     get focused_frame () {
320         var frame = this.window.document.commandDispatcher.focusedWindow;
321         if (this.is_child_frame(frame))
322             return frame;
323         return this.top_frame;
324     },
326     get focused_element () {
327         var element = this.window.document.commandDispatcher.focusedElement;
328         if (this.is_child_element(element))
329             return element;
330         return null;
331     },
333     get focused_selection_controller () {
334         return this.focused_frame
335             .QueryInterface(Ci.nsIInterfaceRequestor)
336             .getInterface(Ci.nsIWebNavigation)
337             .QueryInterface(Ci.nsIInterfaceRequestor)
338             .getInterface(Ci.nsISelectionDisplay)
339             .QueryInterface(Ci.nsISelectionController);
340     },
342     do_command: function (command) {
343         function attempt_command (element, command) {
344             var controller;
345             if (element.controllers
346                 && (controller = element.controllers.getControllerForCommand(command)) != null
347                 && controller.isCommandEnabled(command))
348             {
349                 controller.doCommand(command);
350                 return true;
351             }
352             return false;
353         }
355         var element = this.focused_element;
356         if (element && attempt_command(element, command))
357             return;
358         var win = this.focused_frame;
359         while (true) {
360             if (attempt_command(win, command))
361                 return;
362             if (!win.parent || win == win.parent)
363                 break;
364             win = win.parent;
365         }
366     }
369 function with_current_buffer (buffer, callback) {
370     return callback(new interactive_context(buffer));
373 function check_buffer (obj, type) {
374     if (!(obj instanceof type))
375         throw interactive_error("Buffer has invalid type.");
376     if (obj.dead)
377         throw interactive_error("Buffer has already been killed.");
378     return obj;
381 function caret_enabled (buffer) {
382     return buffer.browser.getAttribute('showcaret');
385 function clear_selection (buffer) {
386     let sel_ctrl = buffer.focused_selection_controller;
387     if (sel_ctrl) {
388         let sel = sel_ctrl.getSelection(sel_ctrl.SELECTION_NORMAL);
389         if (caret_enabled(buffer)) {
390             if (sel.anchorNode)
391                 sel.collapseToStart();
392         } else {
393             sel.removeAllRanges();
394         }
395     }
399 function buffer_container (window, create_initial_buffer) {
400     this.window = window;
401     this.container = window.document.getElementById("buffer-container");
402     this.buffer_list = [];
403     this.buffer_history = [];
404     window.buffers = this;
405     create_initial_buffer(window);
407 buffer_container.prototype = {
408     constructor: buffer_container,
409     toString: function () "#<buffer_container>",
411     insert: function (buffer, position, opener) {
412         var i = this.index_of(opener);
413         if (position == null) {
414             if (i == null)
415                 position = new_buffer_position;
416             else
417                 position = new_buffer_with_opener_position;
418         }
419         if (i == null)
420             i = this.selected_index || 0;
421         try {
422             if (position instanceof Function)
423                 var p = position(this, buffer, i);
424             else
425                 p = position;
426             this.buffer_list.splice(p, 0, buffer);
427         } catch (e) {
428             this.buffer_list.splice(0, 0, buffer);
429             dumpln("Error inserting buffer, inserted at 0.");
430             dump_error(e);
431         }
432     },
434     get current () {
435         return this.container.selectedPanel.conkeror_buffer_object;
436     },
438     set current (buffer) {
439         var old_value = this.current;
440         if (old_value == buffer)
441             return;
443         this.buffer_history.splice(this.buffer_history.indexOf(buffer), 1);
444         this.buffer_history.unshift(buffer);
446         this._switch_away_from(this.current);
447         this._switch_to(buffer);
449         // Run hooks
450         select_buffer_hook.run(buffer);
451     },
453     // Ensure the focus state for the current buffer is updated
454     save_focus: function () {
455         // If minibuffer is active, the focus is already saved, so leave that focus state as is
456         if (this.window.minibuffer.active)
457             return;
459         var b = this.current;
460         b.saved_focused_frame = b.focused_frame;
461         b.saved_focused_element = b.focused_element;
462     },
464     // Restore the focus state for the current buffer, unless the minibuffer is still active
465     restore_focus: function () {
466         /**
467          * This next focus call seems to be needed to avoid focus
468          * somehow getting lost (and the keypress handler therefore
469          * not getting called at all) when killing buffers.
470          */
471         this.window.focus();
473         // If the minibuffer is active, keep the saved focus state but don't
474         // restore it until the minibuffer becomes inactive
475         if (this.window.minibuffer.active)
476             return;
478         var b = this.current;
480         b.browser.focus();
482         var saved_focused_element = b.saved_focused_element;
483         var saved_focused_frame = b.saved_focused_frame;
484         b.clear_saved_focus();
486         if (saved_focused_element) {
487             try {
488                 if (saved_focused_element.focus) {
489                     set_focus_no_scroll(this.window, saved_focused_element);
490                     return;
491                 }
492             } catch (e) { /* saved_focused_element may be dead */ }
493         }
495         if (saved_focused_frame) {
496             try {
497                 set_focus_no_scroll(this.window, saved_focused_frame);
498             } catch (e) { /* saved_focused_frame may be dead */ }
499         }
500     },
502     // Note: old_value is still the current buffer when this is called
503     _switch_away_from: function (old_value) {
504         this.save_focus();
506         if ('isActive' in old_value.browser.docShell)
507             old_value.browser.docShell.isActive = false;
508         old_value.browser.setAttribute("type", "content");
509     },
511     _switch_to: function (buffer) {
512         // Select new buffer in the XUL deck
513         this.container.selectedPanel = buffer.element;
515         buffer.browser.setAttribute("type", "content-primary");
516         if ('isActive' in buffer.browser.docShell)
517             buffer.browser.docShell.isActive = true;
519         this.restore_focus();
521         buffer.set_input_mode();
523         this.window.minibuffer.set_default_message(buffer.default_message);
524     },
526     get count () {
527         return this.buffer_list.length;
528     },
530     get_buffer: function (index) {
531         if (index >= 0 && index < this.count)
532             return this.buffer_list[index]
533         return null;
534     },
536     get selected_index () {
537         var nodes = this.buffer_list;
538         var count = nodes.length;
539         for (var i = 0; i < count; ++i)
540             if (nodes[i] == this.container.selectedPanel.conkeror_buffer_object)
541                 return i;
542         return null;
543     },
545     index_of: function (b) {
546         var nodes = this.buffer_list;
547         var count = nodes.length;
548         for (var i = 0; i < count; ++i)
549             if (nodes[i] == b)
550                 return i;
551         return null;
552     },
554     get unique_name_list () {
555         var existing_names = {};
556         var bufs = [];
557         this.for_each(function(b) {
558                 var base_name = b.name;
559                 var name = base_name;
560                 var index = 1;
561                 while (existing_names[name]) {
562                     ++index;
563                     name = base_name + "<" + index + ">";
564                 }
565                 existing_names[name] = true;
566                 bufs.push([name, b]);
567             });
568         return bufs;
569     },
571     kill_buffer: function (b) {
572         if (b.dead)
573             return true;
574         var count = this.count;
575         if (count <= 1)
576             return false;
577         var new_buffer = this.buffer_history[0];
578         var changed = false;
579         if (b == new_buffer) {
580             new_buffer = this.buffer_history[1];
581             changed = true;
582         }
583         this._switch_away_from(this.current);
584         // The removeChild call below may trigger events in progress
585         // listeners.  This call to `destroy' gives buffer subclasses a
586         // chance to remove such listeners, so that they cannot try to
587         // perform UI actions based upon a xul:browser that no longer
588         // exists.
589         var element = b.element;
590         b.destroy();
591         this.container.removeChild(element);
592         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
593         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
594         this._switch_to(new_buffer);
595         if (changed) {
596             select_buffer_hook.run(new_buffer);
597             this.buffer_history.splice(this.buffer_history.indexOf(new_buffer), 1);
598             this.buffer_history.unshift(new_buffer);
599         }
600         kill_buffer_hook.run(b);
601         return true;
602     },
604     bury_buffer: function (b) {
605         var new_buffer = this.buffer_history[0];
606         if (b == new_buffer)
607             new_buffer = this.buffer_history[1];
608         if (! new_buffer)
609             throw interactive_error("No other buffer");
610         if (bury_buffer_position != null) {
611             this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
612             this.insert(b, bury_buffer_position, new_buffer);
613         }
614         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
615         this.buffer_history.push(b);
616         this.current = new_buffer;
617         if (bury_buffer_position != null)
618             move_buffer_hook.run(b);
619         return true;
620     },
622     unbury_buffer: function (b) {
623         var c = this.current;
624         if (bury_buffer_position != null) {
625             this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
626             this.buffer_list.splice(this.buffer_list.indexOf(c), 0, b);
627         }
628         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
629         this.buffer_history.unshift(b);
630         this.current = b;
631         if (bury_buffer_position != null)
632             move_buffer_hook.run(b);
633         return true;
634     },
636     for_each: function (f) {
637         var count = this.count;
638         for (var i = 0; i < count; ++i)
639             f(this.get_buffer(i));
640     }
643 function buffer_initialize_window_early (window) {
644     /**
645      * Use content_buffer by default to handle an unusual case where
646      * browser.chromeURI is used perhaps.  In general this default
647      * should not be needed.
648      */
649     var create_initial_buffer =
650         window.args.initial_buffer_creator || buffer_creator(content_buffer);
651     new buffer_container(window, create_initial_buffer);
654 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
658  * initialize_first_buffer_type is a workaround for a XULRunner bug that
659  * first appeared in version 2.0, manifested as missing scrollbars in the
660  * first buffer of any window.  It only affects content-primary browsers,
661  * and the workaround is to initialize the browser as type "content" then
662  * change it to content-primary after a delay.
663  */
664 function initialize_first_buffer_type (window) {
665     window.buffers.current.browser.setAttribute("type", "content-primary");
668 add_hook("window_initialize_late_hook", initialize_first_buffer_type);
671 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
672 function buffer_before_window_close (window) {
673     var bs = window.buffers;
674     var count = bs.count;
675     for (let i = 0; i < count; ++i) {
676         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
677             return false;
678     }
679     return true;
681 add_hook("window_before_close_hook", buffer_before_window_close);
683 function buffer_window_close_handler (window) {
684     var bs = window.buffers;
685     var count = bs.count;
686     for (let i = 0; i < count; ++i) {
687         let b = bs.get_buffer(i);
688         b.destroy();
689     }
691 add_hook("window_close_hook", buffer_window_close_handler);
693 /* open/follow targets */
694 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
695                                // buffer is a content_buffer.
696 const OPEN_NEW_BUFFER = 1;
697 const OPEN_NEW_BUFFER_BACKGROUND = 2;
698 const OPEN_NEW_WINDOW = 3;
700 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
701 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
703 var TARGET_PROMPTS = [" in current buffer",
704                       " in new buffer",
705                       " in new buffer (background)",
706                       " in new window",
707                       "",
708                       " in current frame"];
710 var TARGET_NAMES = ["current buffer",
711                     "new buffer",
712                     "new buffer (background)",
713                     "new window",
714                     "default",
715                     "current frame"];
718 function create_buffer (window, creator, target) {
719     switch (target) {
720     case OPEN_NEW_BUFFER:
721         window.buffers.current = creator(window, null);
722         break;
723     case OPEN_NEW_BUFFER_BACKGROUND:
724         creator(window, null);
725         break;
726     case OPEN_NEW_WINDOW:
727         make_window(creator);
728         break;
729     default:
730         throw new Error("invalid target");
731     }
734 let (queued_buffer_creators = null) {
735     function create_buffer_in_current_window (creator, target, focus_existing) {
736         function process_queued_buffer_creators (window) {
737             for (var i = 0; i < queued_buffer_creators.length; ++i) {
738                 var x = queued_buffer_creators[i];
739                 create_buffer(window, x[0], x[1]);
740             }
741             queued_buffer_creators = null;
742         }
744         if (target == OPEN_NEW_WINDOW)
745             throw new Error("invalid target");
746         var window = get_recent_conkeror_window();
747         if (window) {
748             if (focus_existing)
749                 window.focus();
750             create_buffer(window, creator, target);
751         } else if (queued_buffer_creators != null) {
752             queued_buffer_creators.push([creator,target]);
753         } else {
754             queued_buffer_creators = [];
755             window = make_window(creator);
756             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
757         }
758     }
763  * Read Buffer
764  */
765 define_variable("read_buffer_show_icons", false,
766     "Boolean which says whether read_buffer should show buffer "+
767     "icons in the completions list.\nNote, setting this variable "+
768     "alone does not cause favicons or other kinds of icons to be "+
769     "fetched.  For that, load the `favicon' (or similar other) "+
770     "library.");
772 minibuffer_auto_complete_preferences["buffer"] = true;
773 define_keywords("$buffers", "$default");
774 minibuffer.prototype.read_buffer = function () {
775     var window = this.window;
776     keywords(arguments, $prompt = "Buffer:",
777              $buffers = function (visitor) window.buffers.for_each(visitor),
778              $default = window.buffers.current,
779              $history = "buffer");
780     var completer = all_word_completer(
781         $completions = arguments.$buffers,
782         $get_string = function (x) x.description,
783         $get_description = function (x) x.title,
784         $get_icon = (read_buffer_show_icons ?
785                      function (x) x.icon : null));
786     var result = yield this.read(
787         $keymap = read_buffer_keymap,
788         $prompt = arguments.$prompt,
789         $history = arguments.$history,
790         $completer = completer,
791         $enable_icons = read_buffer_show_icons,
792         $match_required = true,
793         $auto_complete = "buffer",
794         $auto_complete_initial = true,
795         $auto_complete_delay = 0,
796         $default_completion = arguments.$default);
797     yield co_return(result);
801 function buffer_move_forward (window, count) {
802     var buffers = window.buffers;
803     var index = buffers.selected_index;
804     var buffer = buffers.current
805     var total = buffers.count;
806     if (total == 1)
807         return;
808     var new_index = (index + count) % total;
809     if (new_index == index)
810         return;
811     if (new_index < 0)
812         new_index += total;
813     buffers.buffer_list.splice(index, 1);
814     buffers.buffer_list.splice(new_index, 0, buffer);
815     move_buffer_hook.run(buffer);
817 interactive("buffer-move-forward",
818     "Move the current buffer forward in the buffer order.",
819     function (I) { buffer_move_forward(I.window, I.p); });
821 interactive("buffer-move-backward",
822     "Move the current buffer backward in the buffer order.",
823     function (I) { buffer_move_forward(I.window, -I.p); });
826 function buffer_next (window, count) {
827     var index = window.buffers.selected_index;
828     var total = window.buffers.count;
829     if (total == 1)
830         throw new interactive_error("No other buffer");
831     index = (index + count) % total;
832     if (index < 0)
833         index += total;
834     window.buffers.current = window.buffers.get_buffer(index);
836 interactive("buffer-next",
837     "Switch to the next buffer.",
838     function (I) { buffer_next(I.window, I.p); });
839 interactive("buffer-previous",
840     "Switch to the previous buffer.",
841     function (I) { buffer_next(I.window, -I.p); });
843 function switch_to_buffer (window, buffer) {
844     if (buffer && !buffer.dead)
845         window.buffers.current = buffer;
847 interactive("switch-to-buffer",
848     "Prompt for a buffer and switch to it.",
849     function (I) {
850         switch_to_buffer(
851             I.window,
852             (yield I.minibuffer.read_buffer(
853                 $prompt = "Switch to buffer:",
854                 $default = (I.window.buffers.count > 1 ?
855                             I.window.buffers.buffer_history[1] :
856                             I.buffer))));
857     });
859 define_variable("can_kill_last_buffer", true,
860     "When true, kill-buffer can kill the last  buffer in a window, "+
861     "and close the window.");
863 function kill_other_buffers (buffer) {
864     if (!buffer)
865         return;
866     var bs = buffer.window.buffers;
867     var b;
868     while ((b = bs.get_buffer(0)) != buffer)
869         bs.kill_buffer(b);
870     var count = bs.count;
871     while (--count)
872         bs.kill_buffer(bs.get_buffer(1));
874 interactive("kill-other-buffers",
875     "Kill all buffers except current one.\n",
876     function (I) { kill_other_buffers(I.buffer); });
879 function kill_buffer (buffer, force) {
880     if (!buffer)
881         return;
882     var buffers = buffer.window.buffers;
883     if (buffers.count == 1 && buffer == buffers.current) {
884         if (can_kill_last_buffer || force) {
885             delete_window(buffer.window);
886             return;
887         } else
888             throw interactive_error("Can't kill last buffer.");
889     }
890     buffers.kill_buffer(buffer);
892 interactive("kill-buffer",
893     "Kill a buffer specified in the minibuffer.\n" +
894     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
895     "last remaining buffer in a window will cause the window to be closed.",
896     function (I) {
897         kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:")));
898     });
900 interactive("kill-current-buffer",
901     "Kill the current buffer.\n" +
902     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
903     "last remaining buffer in a window will cause the window to be closed.",
904     function (I) { kill_buffer(I.buffer); });
906 interactive("read-buffer-kill-buffer",
907     "Kill the current selected buffer in the completions list "+
908     "in a read buffer minibuffer interaction.",
909     function (I) {
910         var s = I.window.minibuffer.current_state;
911         var i = s.selected_completion_index;
912         var c = s.completions;
913         if (i == -1)
914             return;
915         kill_buffer(c.get_value(i));
916         s.completer.refresh();
917         s.handle_input(I.window.minibuffer);
918     });
920 interactive("bury-buffer",
921     "Bury the current buffer.\nPut the current buffer at the end of " +
922     "the buffer list, so that it is the least likely buffer to be " +
923     "selected by `switch-to-buffer'.",
924     function (I) { I.window.buffers.bury_buffer(I.buffer); });
926 interactive("unbury-buffer",
927     "Unbury the buffer lowest in the buffer-history list.\n"+
928     "With universal argument, prompt for a buffer.  When "+
929     "`bury_buffer_position` is non-null, move the buffer "+
930     "to the current position in the buffer list.",
931     function (I) {
932         var buffers = I.window.buffers;
933         if (I.prefix_argument)
934             var b = yield I.minibuffer.read_buffer(
935                 $prompt = "Switch to buffer:",
936                 $buffers = function (visitor) {
937                     var count = buffers.count;
938                     for (var i = count - 1; i >= 0; --i)
939                         visitor(buffers.buffer_history[i]);
940                 },
941                 $default = buffers.buffer_history[buffers.count - 1]);
942         else
943             b = buffers.buffer_history[buffers.count - 1];
944         buffers.unbury_buffer(b);
945     });
947 function change_directory (buffer, dir) {
948     if (buffer.page != null)
949         delete buffer.page.local.cwd;
950     buffer.local.cwd = make_file(dir);
952 interactive("change-directory",
953     "Change the current directory of the selected buffer.",
954     function (I) {
955         change_directory(
956             I.buffer,
957             (yield I.minibuffer.read_existing_directory_path(
958                 $prompt = "Change to directory:",
959                 $initial_value = make_file(I.local.cwd).path)));
960     });
962 interactive("shell-command", null,
963     function (I) {
964         var cwd = I.local.cwd;
965         var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
966         yield shell_command(cmd, $cwd = cwd);
967     });
971  * selection_is_embed_p is used to test whether the unfocus command can
972  * unfocus an element, even though there is a selection.  This happens
973  * when the focused element is an html:embed.
974  */
975 function selection_is_embed_p (sel, focused_element) {
976     if (sel.rangeCount == 1) {
977         try {
978             var r = sel.getRangeAt(0);
979             var a = r.startContainer.childNodes[r.startOffset];
980             if ((a instanceof Ci.nsIDOMHTMLEmbedElement ||
981                  a instanceof Ci.nsIDOMHTMLObjectElement) &&
982                 a == focused_element)
983             {
984                 return true;
985             }
986         } catch (e) {}
987     }
988     return false;
992  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
993  * frames, iframes, plugins, and also clearing the selection.
994  */
995 define_buffer_local_hook("unfocus_hook");
996 function unfocus (window, buffer) {
997     // 1. if there is a selection, clear it.
998     var selc = buffer.focused_selection_controller;
999     if (selc) {
1000         var sel = selc.getSelection(selc.SELECTION_NORMAL);
1001         var active = ! sel.isCollapsed;
1002         var embed_p = selection_is_embed_p(sel, buffer.focused_element);
1003         clear_selection(buffer);
1004         if (active && !embed_p) {
1005             window.minibuffer.message("cleared selection");
1006             return;
1007         }
1008     }
1009     // 2. if there is a focused element, unfocus it.
1010     if (buffer.focused_element) {
1011         buffer.focused_element.blur();
1012         // if an element in a detached fragment has focus, blur() will
1013         // not work, and we need to take more drastic measures.  the
1014         // action taken was found through experiment, so it is possibly
1015         // not the most concise way to unfocus such an element.
1016         if (buffer.focused_element) {
1017             buffer.element.focus();
1018             buffer.top_frame.focus();
1019         }
1020         window.minibuffer.message("unfocused element");
1021         return;
1022     }
1023     // 3. if an iframe has focus, we must blur it.
1024     if (buffer.focused_frame_or_null &&
1025         buffer.focused_frame_or_null.frameElement)
1026     {
1027         buffer.focused_frame_or_null.frameElement.blur();
1028     }
1029     // 4. return focus to top-frame from subframes and plugins.
1030     buffer.top_frame.focus();
1031     buffer.top_frame.focus(); // needed to get focus back from plugins
1032     window.minibuffer.message("refocused top frame");
1033     // give page-modes an opportunity to set focus specially
1034     unfocus_hook.run(buffer);
1036 interactive("unfocus",
1037     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
1038     "frames, iframes, plugins, and also for clearing the selection.\n"+
1039     "The action that it takes is based on precedence.  If there is a "+
1040     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
1041     "there is a selection, it will clear the selection.  Otherwise, it "+
1042     "will return focus to the top frame from a focused frame, iframe, "+
1043     "or plugin.  In the case of plugins, since they steal keyboard "+
1044     "control away from Conkeror, the normal way to unfocus them is "+
1045     "to use command-line remoting externally: conkeror -batch -f "+
1046     "unfocus.  Page-modes also have an opportunity to alter the default"+
1047     "focus via the hook, `focus_hook'.",
1048     function (I) {
1049         unfocus(I.window, I.buffer);
1050     });
1053 function for_each_buffer (f) {
1054     for_each_window(function (w) { w.buffers.for_each(f); });
1059  * Buffer Modes
1060  */
1062 define_buffer_local_hook("buffer_mode_change_hook");
1063 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
1065 define_keywords("$display_name", "$doc");
1066 function buffer_mode (name, enable, disable) {
1067     keywords(arguments);
1068     this.name = name.replace("-","_","g");
1069     this.hyphen_name = name.replace("_","-","g");
1070     if (enable)
1071         this._enable = enable;
1072     if (disable)
1073         this._disable = disable;
1074     this.display_name = arguments.$display_name;
1075     this.doc = arguments.$doc;
1076     this.enable_hook = this.name + "_enable_hook";
1077     this.disable_hook = this.name + "_disable_hook";
1079 buffer_mode.prototype = {
1080     constructor: buffer_mode,
1081     name: null,
1082     display_name: null,
1083     doc: null,
1084     enable_hook: null,
1085     disable_hook: null,
1086     _enable: null,
1087     _disable: null,
1088     enable: function (buffer) {
1089         try {
1090             if (this._enable)
1091                 this._enable(buffer);
1092         } finally {
1093             buffer.enabled_modes.push(this.name);
1094             if (conkeror[this.enable_hook])
1095                 conkeror[this.enable_hook].run(buffer);
1096             buffer_mode_change_hook.run(buffer);
1097         }
1098     },
1099     disable: function (buffer) {
1100         try {
1101             if (this._disable)
1102                 this._disable(buffer);
1103         } finally {
1104             var i = buffer.enabled_modes.indexOf(this.name);
1105             if (i > -1)
1106                 buffer.enabled_modes.splice(i, 1);
1107             if (conkeror[this.disable_hook])
1108                 conkeror[this.disable_hook].run(buffer);
1109             buffer_mode_change_hook.run(buffer);
1110         }
1111     }
1113 define_keywords("$constructor");
1114 function define_buffer_mode (name, enable, disable) {
1115     keywords(arguments, $constructor = buffer_mode, $doc = null);
1116     var constructor = arguments.$constructor;
1117     var m = new constructor(name, enable, disable, forward_keywords(arguments));
1118     name = m.name; // normalized
1119     conkeror[name] = m;
1120     define_buffer_local_hook(m.enable_hook);
1121     define_buffer_local_hook(m.disable_hook);
1122     interactive(m.hyphen_name,
1123         arguments.$doc,
1124         function (I) {
1125             var enabledp = (I.buffer.enabled_modes.indexOf(name) > -1);
1126             if (enabledp)
1127                 m.disable(I.buffer);
1128             else
1129                 m.enable(I.buffer);
1130             I.minibuffer.message(m.hyphen_name + (enabledp ? " disabled" : " enabled"));
1131         });
1133 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
1137  * Mode Display in Minibuffer
1138  */
1140 function minibuffer_mode_indicator (window) {
1141     this.window = window;
1142     var element = create_XUL(window, "label");
1143     element.setAttribute("id", "minibuffer-mode-indicator");
1144     element.setAttribute("class", "mode-text-widget");
1145     window.document.getElementById("minibuffer").appendChild(element);
1146     this.element = element;
1147     this.hook_function = method_caller(this, this.update);
1148     add_hook.call(window, "select_buffer_hook", this.hook_function);
1149     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_function);
1150     this.update();
1152 minibuffer_mode_indicator.prototype = {
1153     constructor: minibuffer_mode_indicator,
1154     window: null,
1155     element: null,
1156     hook_function: null,
1157     update: function () {
1158         var buffer = this.window.buffers.current;
1159         var str = buffer.enabled_modes.map(
1160             function (x) {
1161                 return (conkeror[x].display_name || null);
1162             }).filter(function (x) x != null).join(" ");
1163         this.element.value = str;
1164     },
1165     uninstall: function () {
1166         remove_hook.call(this.window, "select_buffer_hook", this.hook_function);
1167         remove_hook.call(this.window, "current_buffer_mode_change_hook", this.hook_function);
1168         this.element.parentNode.removeChild(this.element);
1169     }
1171 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
1172 minibuffer_mode_indicator_mode(true);
1176  * minibuffer-keymaps-display
1177  */
1178 function minibuffer_keymaps_display_update (buffer) {
1179     var element = buffer.window.document
1180         .getElementById("keymaps-display");
1181     if (element) {
1182         var str = buffer.keymaps.reduce(
1183             function (acc, kmap) {
1184                 if (kmap.display_name)
1185                     acc.push(kmap.display_name);
1186                 return acc;
1187             }, []).join("/");
1188         if (element.value != str)
1189             element.value = str;
1190     }
1193 function minibuffer_keymaps_display_initialize (window) {
1194     var element = create_XUL(window, "label");
1195     element.setAttribute("id", "keymaps-display");
1196     element.setAttribute("class", "mode-text-widget");
1197     element.setAttribute("value", "");
1198     var mb = window.document.getElementById("minibuffer");
1199     mb.appendChild(element);
1202 define_global_mode("minibuffer_keymaps_display_mode",
1203     function enable () {
1204         add_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1205         add_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1206         for_each_window(minibuffer_keymaps_display_initialize);
1207     },
1208     function disable () {
1209         remove_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1210         remove_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1211         for_each_window(function (w) {
1212             var element = w.document
1213                 .getElementById("keymaps-display");
1214             if (element)
1215                 element.parentNode.removeChild(element);
1216         });
1217     });
1219 minibuffer_keymaps_display_mode(true);
1223  * minibuffer-keymaps-highlight
1224  */
1225 function minibuffer_keymaps_highlight_update (buffer) {
1226     var mb = buffer.window.document.getElementById("minibuffer");
1227     if (buffer.keymaps.some(function (k) k.notify))
1228         dom_add_class(mb, "highlight");
1229     else
1230         dom_remove_class(mb, "highlight");
1233 define_global_mode("minibuffer_keymaps_highlight_mode",
1234     function enable () {
1235         add_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1236     },
1237     function disable () {
1238         remove_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1239         for_each_window(function (w) {
1240             var mb = w.document.getElementById("minibuffer");
1241             if (mb)
1242                 dom_remove_class("highlight");
1243         });
1244     });
1246 minibuffer_keymaps_highlight_mode(true);
1249 provide("buffer");