buffer ordering
[conkeror.git] / modules / buffer.js
blob1a22570d883f96dd598cafd8a79b918fd46ad866
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 in_module(null);
12 var define_buffer_local_hook = local_hook_definer("window");
14 function define_current_buffer_hook (hook_name, existing_hook) {
15     define_buffer_local_hook(hook_name);
16     add_hook(existing_hook, function (buffer) {
17             if (!buffer.window.buffers || buffer != buffer.window.buffers.current)
18                 return;
19             var hook = conkeror[hook_name];
20             hook.run.apply(hook, Array.prototype.slice.call(arguments));
21         });
24 define_buffer_local_hook("buffer_title_change_hook");
25 define_buffer_local_hook("buffer_description_change_hook");
26 define_buffer_local_hook("buffer_icon_change_hook");
27 define_buffer_local_hook("select_buffer_hook");
28 define_buffer_local_hook("create_buffer_early_hook");
29 define_buffer_local_hook("create_buffer_late_hook");
30 define_buffer_local_hook("create_buffer_hook");
31 define_buffer_local_hook("kill_buffer_hook");
32 define_buffer_local_hook("move_buffer_hook");
33 define_buffer_local_hook("buffer_scroll_hook");
34 define_buffer_local_hook("buffer_dom_content_loaded_hook");
35 define_buffer_local_hook("buffer_loaded_hook");
36 define_buffer_local_hook("set_input_mode_hook");
38 define_current_buffer_hook("current_buffer_title_change_hook", "buffer_title_change_hook");
39 define_current_buffer_hook("current_buffer_description_change_hook", "buffer_description_change_hook");
40 define_current_buffer_hook("current_buffer_icon_change_hook", "buffer_icon_change_hook");
41 define_current_buffer_hook("current_buffer_scroll_hook", "buffer_scroll_hook");
42 define_current_buffer_hook("current_buffer_dom_content_loaded_hook", "buffer_dom_content_loaded_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             buffer_loaded_hook.run(buffer);
163         }, true /* capture */);
165     this.browser.addEventListener("DOMWindowClose", function (event) {
166             /* This call to preventDefault is very important; without
167              * it, somehow Mozilla does something bad and as a result
168              * the window loses focus, causing keyboard commands to
169              * stop working. */
170             event.preventDefault();
172             if (allow_browser_window_close)
173                 kill_buffer(buffer, true);
174         }, true);
176     this.browser.addEventListener("focus", function (event) {
177         if (buffer.focusblocker &&
178             event.target instanceof Ci.nsIDOMHTMLElement &&
179             buffer.focusblocker(buffer, event))
180         {
181             event.target.blur();
182         } else
183             buffer.set_input_mode();
184     }, true);
186     this.browser.addEventListener("blur", function (event) {
187         buffer.set_input_mode();
188     }, true);
190     this.modalities = [buffer_modality];
192     // When create_buffer_early_hook runs, basic buffer properties
193     // will be available, but not the properties subclasses.
194     create_buffer_early_hook.run(this);
196     this.constructor_end();
198 buffer.prototype = {
199     constructor: buffer,
201     // default_position is the default value for the $position keyword to
202     // the buffer constructor.  This property can be set on the prototype
203     // of a subclass in order to override new_buffer_position and
204     // new_buffer_with_opener_position for specific types of buffers.
205     default_position: null,
207     /* Saved focus state */
208     saved_focused_frame: null,
209     saved_focused_element: null,
211     // get title ()   [must be defined by subclasses]
212     // get name ()    [must be defined by subclasses]
213     dead: false, /* This is set when the buffer is killed */
215     keymaps: null,
216     mark_active: false,
218     // The property focusblocker is available for an external module to
219     // put a function on which takes a buffer as its argument and returns
220     // true to block a focus event, or false to let normal processing
221     // occur.  Having this one property explicitly handled by the buffer
222     // class allows for otherwise modular focus-blockers.
223     focusblocker: null,
225     // icon is a string url of an icon to use for this buffer.  Setting it
226     // causes buffer_icon_change_hook to be run.
227     _icon: null,
228     get icon () this._icon,
229     set icon (x) {
230         if (this._icon != x) {
231             this._icon = x;
232             buffer_icon_change_hook.run(this);
233         }
234     },
236     default_message: "",
238     set_default_message: function (str) {
239         this.default_message = str;
240         if (this == this.window.buffers.current)
241             this.window.minibuffer.set_default_message(str);
242     },
244     constructors_running: 0,
246     constructor_begin: function () {
247         this.constructors_running++;
248     },
250     constructor_end: function () {
251         if (--this.constructors_running == 0) {
252             create_buffer_hook.run(this);
253             this.set_input_mode();
254             delete this.opener;
255         }
256     },
258     destroy: function () {
259         this.dead = true;
260         this.browser = null;
261         this.element = null;
262         this.saved_focused_frame = null;
263         this.saved_focused_element = null;
264         // prevent modalities from accessing dead browser
265         this.modalities = [];
266     },
268     set_input_mode: function () {
269         if (this != this.window.buffers.current)
270             return;
271         this.keymaps = [];
272         this.modalities.map(function (m) m(this), this);
273         set_input_mode_hook.run(this);
274     },
276     override_keymaps: function (keymaps) {
277         if (keymaps) {
278             this.keymaps = keymaps;
279             this.set_input_mode = function () {
280                 set_input_mode_hook.run(this);
281             };
282         } else
283             delete this.set_input_mode;
284         this.set_input_mode();
285     },
287     /* Browser accessors */
288     get top_frame () { return this.browser.contentWindow; },
289     get document () { return this.browser.contentDocument; },
290     get web_navigation () { return this.browser.webNavigation; },
291     get doc_shell () { return this.browser.docShell; },
292     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
293     get current_uri () { return this.browser.currentURI; },
295     is_child_element: function (element) {
296         return (element && this.is_child_frame(element.ownerDocument.defaultView));
297     },
299     is_child_frame: function (frame) {
300         return (frame && frame.top == this.top_frame);
301     },
303     // This method is like focused_frame, except that if no content
304     // frame actually has focus, this returns null.
305     get focused_frame_or_null () {
306         var frame = this.window.document.commandDispatcher.focusedWindow;
307         if (this.is_child_frame(frame))
308             return frame;
309         return null;
310     },
312     get focused_frame () {
313         var frame = this.window.document.commandDispatcher.focusedWindow;
314         if (this.is_child_frame(frame))
315             return frame;
316         return this.top_frame;
317     },
319     get focused_element () {
320         var element = this.window.document.commandDispatcher.focusedElement;
321         if (this.is_child_element(element))
322             return element;
323         return null;
324     },
326     get focused_selection_controller () {
327         return this.focused_frame
328             .QueryInterface(Ci.nsIInterfaceRequestor)
329             .getInterface(Ci.nsIWebNavigation)
330             .QueryInterface(Ci.nsIInterfaceRequestor)
331             .getInterface(Ci.nsISelectionDisplay)
332             .QueryInterface(Ci.nsISelectionController);
333     },
335     do_command: function (command) {
336         function attempt_command (element, command) {
337             var controller;
338             if (element.controllers
339                 && (controller = element.controllers.getControllerForCommand(command)) != null
340                 && controller.isCommandEnabled(command))
341             {
342                 controller.doCommand(command);
343                 return true;
344             }
345             return false;
346         }
348         var element = this.focused_element;
349         if (element && attempt_command(element, command))
350             return;
351         var win = this.focused_frame;
352         while (true) {
353             if (attempt_command(win, command))
354                 return;
355             if (!win.parent || win == win.parent)
356                 break;
357             win = win.parent;
358         }
359     }
362 function with_current_buffer (buffer, callback) {
363     return callback(new interactive_context(buffer));
366 function check_buffer (obj, type) {
367     if (!(obj instanceof type))
368         throw interactive_error("Buffer has invalid type.");
369     if (obj.dead)
370         throw interactive_error("Buffer has already been killed.");
371     return obj;
374 function caret_enabled (buffer) {
375     return buffer.browser.getAttribute('showcaret');
378 function clear_selection (buffer) {
379     let sel_ctrl = buffer.focused_selection_controller;
380     if (sel_ctrl) {
381         let sel = sel_ctrl.getSelection(sel_ctrl.SELECTION_NORMAL);
382         if (caret_enabled(buffer)) {
383             if (sel.anchorNode)
384                 sel.collapseToStart();
385         } else {
386             sel.removeAllRanges();
387         }
388     }
392 function buffer_container (window, create_initial_buffer) {
393     this.window = window;
394     this.container = window.document.getElementById("buffer-container");
395     this.buffer_list = [];
396     this.buffer_history = [];
397     window.buffers = this;
398     create_initial_buffer(window);
400 buffer_container.prototype = {
401     constructor: buffer_container,
403     insert: function (buffer, position, opener) {
404         var i = this.index_of(opener);
405         if (position == null) {
406             if (i == null)
407                 position = new_buffer_position;
408             else
409                 position = new_buffer_with_opener_position;
410         }
411         if (i == null)
412             i = this.selected_index || 0;
413         try {
414             if (position instanceof Function)
415                 var p = position(this, buffer, i);
416             else
417                 p = position;
418             this.buffer_list.splice(p, 0, buffer);
419         } catch (e) {
420             this.buffer_list.splice(0, 0, buffer);
421             dumpln("Error inserting buffer, inserted at 0.");
422             dump_error(e);
423         }
424     },
426     get current () {
427         return this.container.selectedPanel.conkeror_buffer_object;
428     },
430     set current (buffer) {
431         var old_value = this.current;
432         if (old_value == buffer)
433             return;
435         this.buffer_history.splice(this.buffer_history.indexOf(buffer), 1);
436         this.buffer_history.unshift(buffer);
438         this._switch_away_from(this.current);
439         this._switch_to(buffer);
441         // Run hooks
442         select_buffer_hook.run(buffer);
443     },
445     _switch_away_from: function (old_value) {
446         // Save focus state
447         old_value.saved_focused_frame = old_value.focused_frame;
448         old_value.saved_focused_element = old_value.focused_element;
450         old_value.browser.setAttribute("type", "content");
451     },
453     _switch_to: function (buffer) {
454         // Select new buffer in the XUL deck
455         this.container.selectedPanel = buffer.element;
457         buffer.browser.setAttribute("type", "content-primary");
459         /**
460          * This next focus call seems to be needed to avoid focus
461          * somehow getting lost (and the keypress handler therefore
462          * not getting called at all) when killing buffers.
463          */
464         this.window.focus();
466         // Restore focus state
467         buffer.browser.focus();
468         if (buffer.saved_focused_element)
469             set_focus_no_scroll(this.window, buffer.saved_focused_element);
470         else if (buffer.saved_focused_frame)
471             set_focus_no_scroll(this.window, buffer.saved_focused_frame);
473         buffer.saved_focused_element = null;
474         buffer.saved_focused_frame = null;
476         buffer.set_input_mode();
478         this.window.minibuffer.set_default_message(buffer.default_message);
479     },
481     get count () {
482         return this.buffer_list.length;
483     },
485     get_buffer: function (index) {
486         if (index >= 0 && index < this.count)
487             return this.buffer_list[index]
488         return null;
489     },
491     get selected_index () {
492         var nodes = this.buffer_list;
493         var count = nodes.length;
494         for (var i = 0; i < count; ++i)
495             if (nodes[i] == this.container.selectedPanel.conkeror_buffer_object)
496                 return i;
497         return null;
498     },
500     index_of: function (b) {
501         var nodes = this.buffer_list;
502         var count = nodes.length;
503         for (var i = 0; i < count; ++i)
504             if (nodes[i] == b)
505                 return i;
506         return null;
507     },
509     get unique_name_list () {
510         var existing_names = new string_hashset();
511         var bufs = [];
512         this.for_each(function(b) {
513                 var base_name = b.name;
514                 var name = base_name;
515                 var index = 1;
516                 while (existing_names.contains(name)) {
517                     ++index;
518                     name = base_name + "<" + index + ">";
519                 }
520                 existing_names.add(name);
521                 bufs.push([name, b]);
522             });
523         return bufs;
524     },
526     kill_buffer: function (b) {
527         if (b.dead)
528             return true;
529         var count = this.count;
530         if (count <= 1)
531             return false;
532         var new_buffer = this.buffer_history[0];
533         var changed = false;
534         if (b == new_buffer) {
535             new_buffer = this.buffer_history[1];
536             changed = true;
537         }
538         this._switch_away_from(this.current);
539         // The removeChild call below may trigger events in progress
540         // listeners.  This call to `destroy' gives buffer subclasses a
541         // chance to remove such listeners, so that they cannot try to
542         // perform UI actions based upon a xul:browser that no longer
543         // exists.
544         var element = b.element;
545         b.destroy();
546         this.container.removeChild(element);
547         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
548         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
549         this._switch_to(new_buffer);
550         if (changed) {
551             select_buffer_hook.run(new_buffer);
552             this.buffer_history.splice(this.buffer_history.indexOf(new_buffer), 1);
553             this.buffer_history.unshift(new_buffer);
554         }
555         kill_buffer_hook.run(b);
556         return true;
557     },
559     bury_buffer: function (b) {
560         var new_buffer = this.buffer_history[0];
561         if (b == new_buffer)
562             new_buffer = this.buffer_history[1];
563         if (! new_buffer)
564             throw interactive_error("No other buffer");
565         if (bury_buffer_position != null) {
566             this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
567             this.insert(b, bury_buffer_position, new_buffer);
568         }
569         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
570         this.buffer_history.push(b);
571         this.current = new_buffer;
572         if (bury_buffer_position != null)
573             move_buffer_hook.run(b);
574         return true;
575     },
577     for_each: function (f) {
578         var count = this.count;
579         for (var i = 0; i < count; ++i)
580             f(this.get_buffer(i));
581     }
584 function buffer_initialize_window_early (window) {
585     /**
586      * Use content_buffer by default to handle an unusual case where
587      * browser.chromeURI is used perhaps.  In general this default
588      * should not be needed.
589      */
590     var create_initial_buffer =
591         window.args.initial_buffer_creator || buffer_creator(content_buffer);
592     new buffer_container(window, create_initial_buffer);
595 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
599  * initialize_first_buffer_type is a workaround for a XULRunner bug that
600  * first appeared in version 2.0, manifested as missing scrollbars in the
601  * first buffer of any window.  It only affects content-primary browsers,
602  * and the workaround is to initialize the browser as type "content" then
603  * change it to content-primary after a delay.
604  */
605 function initialize_first_buffer_type (window) {
606     window.buffers.current.browser.setAttribute("type", "content-primary");
609 add_hook("window_initialize_late_hook", initialize_first_buffer_type);
612 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
613 function buffer_before_window_close (window) {
614     var bs = window.buffers;
615     var count = bs.count;
616     for (let i = 0; i < count; ++i) {
617         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
618             return false;
619     }
620     return true;
622 add_hook("window_before_close_hook", buffer_before_window_close);
624 function buffer_window_close_handler (window) {
625     var bs = window.buffers;
626     var count = bs.count;
627     for (let i = 0; i < count; ++i) {
628         let b = bs.get_buffer(i);
629         b.destroy();
630     }
632 add_hook("window_close_hook", buffer_window_close_handler);
634 /* open/follow targets */
635 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
636                                // buffer is a content_buffer.
637 const OPEN_NEW_BUFFER = 1;
638 const OPEN_NEW_BUFFER_BACKGROUND = 2;
639 const OPEN_NEW_WINDOW = 3;
641 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
642 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
644 var TARGET_PROMPTS = [" in current buffer",
645                       " in new buffer",
646                       " in new buffer (background)",
647                       " in new window",
648                       "",
649                       " in current frame"];
651 var TARGET_NAMES = ["current buffer",
652                     "new buffer",
653                     "new buffer (background)",
654                     "new window",
655                     "default",
656                     "current frame"];
659 function create_buffer (window, creator, target) {
660     switch (target) {
661     case OPEN_NEW_BUFFER:
662         window.buffers.current = creator(window, null);
663         break;
664     case OPEN_NEW_BUFFER_BACKGROUND:
665         creator(window, null);
666         break;
667     case OPEN_NEW_WINDOW:
668         make_window(creator);
669         break;
670     default:
671         throw new Error("invalid target");
672     }
675 let (queued_buffer_creators = null) {
676     function create_buffer_in_current_window (creator, target, focus_existing) {
677         function process_queued_buffer_creators (window) {
678             for (var i = 0; i < queued_buffer_creators.length; ++i) {
679                 var x = queued_buffer_creators[i];
680                 create_buffer(window, x[0], x[1]);
681             }
682             queued_buffer_creators = null;
683         }
685         if (target == OPEN_NEW_WINDOW)
686             throw new Error("invalid target");
687         var window = get_recent_conkeror_window();
688         if (window) {
689             if (focus_existing)
690                 window.focus();
691             create_buffer(window, creator, target);
692         } else if (queued_buffer_creators != null) {
693             queued_buffer_creators.push([creator,target]);
694         } else {
695             queued_buffer_creators = [];
696             window = make_window(creator);
697             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
698         }
699     }
704  * Read Buffer
705  */
706 define_variable("read_buffer_show_icons", false,
707     "Boolean which says whether read_buffer should show buffer "+
708     "icons in the completions list.\nNote, setting this variable "+
709     "alone does not cause favicons or other kinds of icons to be "+
710     "fetched.  For that, load the `favicon' (or similar other) "+
711     "library.");
713 minibuffer_auto_complete_preferences["buffer"] = true;
714 define_keywords("$default");
715 minibuffer.prototype.read_buffer = function () {
716     var window = this.window;
717     var buffer = this.window.buffers.current;
718     keywords(arguments, $prompt = "Buffer:",
719              $default = buffer,
720              $history = "buffer");
721     var completer = all_word_completer(
722         $completions = function (visitor) window.buffers.for_each(visitor),
723         $get_string = function (x) x.description,
724         $get_description = function (x) x.title,
725         $get_icon = (read_buffer_show_icons ?
726                      function (x) x.icon : null));
727     var result = yield this.read(
728         $keymap = read_buffer_keymap,
729         $prompt = arguments.$prompt,
730         $history = arguments.$history,
731         $completer = completer,
732         $enable_icons = read_buffer_show_icons,
733         $match_required = true,
734         $auto_complete = "buffer",
735         $auto_complete_initial = true,
736         $auto_complete_delay = 0,
737         $default_completion = arguments.$default);
738     yield co_return(result);
742 function buffer_move_forward (window, count) {
743     var buffers = window.buffers;
744     var index = buffers.selected_index;
745     var buffer = buffers.current
746     var total = buffers.count;
747     if (total == 1)
748         return;
749     var new_index = (index + count) % total;
750     if (new_index == index)
751         return;
752     if (new_index < 0)
753         new_index += total;
754     buffers.buffer_list.splice(index, 1);
755     buffers.buffer_list.splice(new_index, 0, buffer);
756     move_buffer_hook.run(buffer);
758 interactive("buffer-move-forward",
759     "Move the current buffer forward in the buffer order.",
760     function (I) { buffer_move_forward(I.window, I.p); });
762 interactive("buffer-move-backward",
763     "Move the current buffer backward in the buffer order.",
764     function (I) { buffer_move_forward(I.window, -I.p); });
767 function buffer_next (window, count) {
768     var index = window.buffers.selected_index;
769     var total = window.buffers.count;
770     if (total == 1)
771         throw new interactive_error("No other buffer");
772     index = (index + count) % total;
773     if (index < 0)
774         index += total;
775     window.buffers.current = window.buffers.get_buffer(index);
777 interactive("buffer-next",
778     "Switch to the next buffer.",
779     function (I) { buffer_next(I.window, I.p); });
780 interactive("buffer-previous",
781     "Switch to the previous buffer.",
782     function (I) { buffer_next(I.window, -I.p); });
784 function switch_to_buffer (window, buffer) {
785     if (buffer && !buffer.dead)
786         window.buffers.current = buffer;
788 interactive("switch-to-buffer",
789     "Switch to a buffer specified in the minibuffer.",
790     function (I) {
791         switch_to_buffer(
792             I.window,
793             (yield I.minibuffer.read_buffer(
794                 $prompt = "Switch to buffer:",
795                 $default = (I.window.buffers.count > 1 ?
796                             I.window.buffers.buffer_history[1] :
797                             I.buffer))));
798     });
800 define_variable("can_kill_last_buffer", true,
801     "If this is set to true, kill-buffer can kill the last "+
802     "remaining buffer, and close the window.");
804 function kill_other_buffers (buffer) {
805     if (!buffer)
806         return;
807     var bs = buffer.window.buffers;
808     var b;
809     while ((b = bs.get_buffer(0)) != buffer)
810         bs.kill_buffer(b);
811     var count = bs.count;
812     while (--count)
813         bs.kill_buffer(bs.get_buffer(1));
815 interactive("kill-other-buffers",
816     "Kill all buffers except current one.\n",
817     function (I) { kill_other_buffers(I.buffer); });
820 function kill_buffer (buffer, force) {
821     if (!buffer)
822         return;
823     var buffers = buffer.window.buffers;
824     if (buffers.count == 1 && buffer == buffers.current) {
825         if (can_kill_last_buffer || force) {
826             delete_window(buffer.window);
827             return;
828         } else
829             throw interactive_error("Can't kill last buffer.");
830     }
831     buffers.kill_buffer(buffer);
833 interactive("kill-buffer",
834     "Kill a buffer specified in the minibuffer.\n" +
835     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
836     "last remaining buffer in a window will cause the window to be closed.",
837     function (I) {
838         kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:")));
839     });
841 interactive("kill-current-buffer",
842     "Kill the current buffer.\n" +
843     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
844     "last remaining buffer in a window will cause the window to be closed.",
845     function (I) { kill_buffer(I.buffer); });
847 interactive("read-buffer-kill-buffer",
848     "Kill the current selected buffer in the completions list "+
849     "in a read buffer minibuffer interaction.",
850     function (I) {
851         var s = I.window.minibuffer.current_state;
852         var i = s.selected_completion_index;
853         var c = s.completions;
854         if (i == -1)
855             return;
856         kill_buffer(c.get_value(i));
857         s.completer.refresh();
858         s.handle_input(I.window.minibuffer);
859     });
861 interactive("bury-buffer",
862     "Bury the current buffer.\n Put the current buffer at the end of " +
863     "the buffer list, so that it is the least likely buffer to be " +
864     "selected by `switch-to-buffer'.",
865     function (I) { I.window.buffers.bury_buffer(I.buffer); });
867 function change_directory (buffer, dir) {
868     if (buffer.page != null)
869         delete buffer.page.local.cwd;
870     buffer.local.cwd = make_file(dir);
872 interactive("change-directory",
873     "Change the current directory of the selected buffer.",
874     function (I) {
875         change_directory(
876             I.buffer,
877             (yield I.minibuffer.read_existing_directory_path(
878                 $prompt = "Change to directory:",
879                 $initial_value = make_file(I.local.cwd).path)));
880     });
882 interactive("shell-command", null,
883     function (I) {
884         var cwd = I.local.cwd;
885         var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
886         yield shell_command(cmd, $cwd = cwd);
887     });
891  * selection_is_embed_p is used to test whether the unfocus command can
892  * unfocus an element, even though there is a selection.  This happens
893  * when the focused element is an html:embed.
894  */
895 function selection_is_embed_p (sel, focused_element) {
896     if (sel.rangeCount == 1) {
897         try {
898             var r = sel.getRangeAt(0);
899             var a = r.startContainer.childNodes[r.startOffset];
900             if ((a instanceof Ci.nsIDOMHTMLEmbedElement ||
901                  a instanceof Ci.nsIDOMHTMLObjectElement) &&
902                 a == focused_element)
903             {
904                 return true;
905             }
906         } catch (e) {}
907     }
908     return false;
912  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
913  * frames, iframes, plugins, and also clearing the selection.
914  */
915 define_buffer_local_hook("unfocus_hook");
916 function unfocus (window, buffer) {
917     // 1. if there is a selection, clear it.
918     var selc = buffer.focused_selection_controller;
919     if (selc) {
920         var sel = selc.getSelection(selc.SELECTION_NORMAL);
921         var active = ! sel.isCollapsed;
922         var embed_p = selection_is_embed_p(sel, buffer.focused_element);
923         clear_selection(buffer);
924         if (active && !embed_p) {
925             window.minibuffer.message("cleared selection");
926             return;
927         }
928     }
929     // 2. if there is a focused element, unfocus it.
930     if (buffer.focused_element) {
931         buffer.focused_element.blur();
932         // if an element in a detached fragment has focus, blur() will
933         // not work, and we need to take more drastic measures.  the
934         // action taken was found through experiment, so it is possibly
935         // not the most concise way to unfocus such an element.
936         if (buffer.focused_element) {
937             buffer.element.focus();
938             buffer.top_frame.focus();
939         }
940         window.minibuffer.message("unfocused element");
941         return;
942     }
943     // 3. if an iframe has focus, we must blur it.
944     if (buffer.focused_frame_or_null &&
945         buffer.focused_frame_or_null.frameElement)
946     {
947         buffer.focused_frame_or_null.frameElement.blur();
948     }
949     // 4. return focus to top-frame from subframes and plugins.
950     buffer.top_frame.focus();
951     buffer.top_frame.focus(); // needed to get focus back from plugins
952     window.minibuffer.message("refocused top frame");
953     // give page-modes an opportunity to set focus specially
954     unfocus_hook.run(buffer);
956 interactive("unfocus",
957     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
958     "frames, iframes, plugins, and also for clearing the selection.\n"+
959     "The action that it takes is based on precedence.  If there is a "+
960     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
961     "there is a selection, it will clear the selection.  Otherwise, it "+
962     "will return focus to the top frame from a focused frame, iframe, "+
963     "or plugin.  In the case of plugins, since they steal keyboard "+
964     "control away from Conkeror, the normal way to unfocus them is "+
965     "to use command-line remoting externally: conkeror -batch -f "+
966     "unfocus.  Page-modes also have an opportunity to alter the default"+
967     "focus via the hook, `focus_hook'.",
968     function (I) {
969         unfocus(I.window, I.buffer);
970     });
973 function for_each_buffer (f) {
974     for_each_window(function (w) { w.buffers.for_each(f); });
979  * Buffer Modes
980  */
982 define_buffer_local_hook("buffer_mode_change_hook");
983 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
985 define_keywords("$display_name", "$doc");
986 function buffer_mode (name, enable, disable) {
987     keywords(arguments);
988     this.name = name.replace("-","_","g");
989     this.hyphen_name = name.replace("_","-","g");
990     if (enable)
991         this._enable = enable;
992     if (disable)
993         this._disable = disable;
994     this.display_name = arguments.$display_name;
995     this.doc = arguments.$doc;
996     this.enable_hook = this.name + "_enable_hook";
997     this.disable_hook = this.name + "_disable_hook";
999 buffer_mode.prototype = {
1000     constructor: buffer_mode,
1001     name: null,
1002     display_name: null,
1003     doc: null,
1004     enable_hook: null,
1005     disable_hook: null,
1006     _enable: null,
1007     _disable: null,
1008     enable: function (buffer) {
1009         try {
1010             if (this._enable)
1011                 this._enable(buffer);
1012         } finally {
1013             buffer.enabled_modes.push(this.name);
1014             if (conkeror[this.enable_hook])
1015                 conkeror[this.enable_hook].run(buffer);
1016             buffer_mode_change_hook.run(buffer);
1017         }
1018     },
1019     disable: function (buffer) {
1020         try {
1021             if (this._disable)
1022                 this._disable(buffer);
1023         } finally {
1024             var i = buffer.enabled_modes.indexOf(this.name);
1025             if (i > -1)
1026                 buffer.enabled_modes.splice(i, 1);
1027             if (conkeror[this.disable_hook])
1028                 conkeror[this.disable_hook].run(buffer);
1029             buffer_mode_change_hook.run(buffer);
1030         }
1031     }
1033 define_keywords("$constructor");
1034 function define_buffer_mode (name, enable, disable) {
1035     keywords(arguments, $constructor = buffer_mode, $doc = null);
1036     var constructor = arguments.$constructor;
1037     var m = new constructor(name, enable, disable, forward_keywords(arguments));
1038     name = m.name; // normalized
1039     conkeror[name] = m;
1040     define_buffer_local_hook(m.enable_hook);
1041     define_buffer_local_hook(m.disable_hook);
1042     interactive(m.hyphen_name,
1043         arguments.$doc,
1044         function (I) {
1045             var enabledp = (I.buffer.enabled_modes.indexOf(name) > -1);
1046             if (enabledp)
1047                 m.disable(I.buffer);
1048             else
1049                 m.enable(I.buffer);
1050             I.minibuffer.message(m.hyphen_name + (enabledp ? " disabled" : " enabled"));
1051         });
1053 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
1057  * Mode Display in Minibuffer
1058  */
1060 function minibuffer_mode_indicator (window) {
1061     this.window = window;
1062     var element = create_XUL(window, "label");
1063     element.setAttribute("id", "minibuffer-mode-indicator");
1064     element.setAttribute("class", "mode-text-widget");
1065     window.document.getElementById("minibuffer").appendChild(element);
1066     this.element = element;
1067     this.hook_function = method_caller(this, this.update);
1068     add_hook.call(window, "select_buffer_hook", this.hook_function);
1069     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_function);
1070     this.update();
1072 minibuffer_mode_indicator.prototype = {
1073     constructor: minibuffer_mode_indicator,
1074     window: null,
1075     element: null,
1076     hook_function: null,
1077     update: function () {
1078         var buffer = this.window.buffers.current;
1079         var str = buffer.enabled_modes.map(
1080             function (x) {
1081                 return (conkeror[x].display_name || null);
1082             }).filter(function (x) x != null).join(" ");
1083         this.element.value = str;
1084     },
1085     uninstall: function () {
1086         remove_hook.call(this.window, "select_buffer_hook", this.hook_function);
1087         remove_hook.call(this.window, "current_buffer_mode_change_hook", this.hook_function);
1088         this.element.parentNode.removeChild(this.element);
1089     }
1091 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
1092 minibuffer_mode_indicator_mode(true);
1096  * minibuffer-keymaps-display
1097  */
1098 function minibuffer_keymaps_display_update (buffer) {
1099     var element = buffer.window.document
1100         .getElementById("keymaps-display");
1101     if (element) {
1102         var str = buffer.keymaps.reduce(
1103             function (acc, kmap) {
1104                 if (kmap.display_name)
1105                     acc.push(kmap.display_name);
1106                 return acc;
1107             }, []).join("/");
1108         if (element.value != str)
1109             element.value = str;
1110     }
1113 function minibuffer_keymaps_display_initialize (window) {
1114     var element = create_XUL(window, "label");
1115     element.setAttribute("id", "keymaps-display");
1116     element.setAttribute("class", "mode-text-widget");
1117     element.setAttribute("value", "");
1118     var mb = window.document.getElementById("minibuffer");
1119     mb.appendChild(element);
1122 define_global_mode("minibuffer_keymaps_display_mode",
1123     function enable () {
1124         add_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1125         add_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1126         for_each_window(minibuffer_keymaps_display_initialize);
1127     },
1128     function disable () {
1129         remove_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1130         remove_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1131         for_each_window(function (w) {
1132             var element = w.document
1133                 .getElementById("keymaps-display");
1134             if (element)
1135                 element.parentNode.removeChild(element);
1136         });
1137     });
1139 minibuffer_keymaps_display_mode(true);
1143  * minibuffer-keymaps-highlight
1144  */
1145 function minibuffer_keymaps_highlight_update (buffer) {
1146     var mb = buffer.window.document.getElementById("minibuffer");
1147     if (buffer.keymaps.some(function (k) k.notify))
1148         dom_add_class(mb, "highlight");
1149     else
1150         dom_remove_class(mb, "highlight");
1153 define_global_mode("minibuffer_keymaps_highlight_mode",
1154     function enable () {
1155         add_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1156     },
1157     function disable () {
1158         remove_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1159         for_each_window(function (w) {
1160             var mb = w.document.getElementById("minibuffer");
1161             if (mb)
1162                 dom_remove_class("highlight");
1163         });
1164     });
1166 minibuffer_keymaps_highlight_mode(true);
1169 provide("buffer");