buffer_container.unique_name_list: use js object instead of string_hashset
[conkeror.git] / modules / buffer.js
blobf42414a1aa11ff0b822a5e9a1b7f0900f43c40bf
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");
36 define_current_buffer_hook("current_buffer_title_change_hook", "buffer_title_change_hook");
37 define_current_buffer_hook("current_buffer_description_change_hook", "buffer_description_change_hook");
38 define_current_buffer_hook("current_buffer_icon_change_hook", "buffer_icon_change_hook");
39 define_current_buffer_hook("current_buffer_scroll_hook", "buffer_scroll_hook");
40 define_current_buffer_hook("current_buffer_dom_content_loaded_hook", "buffer_dom_content_loaded_hook");
43 function buffer_position_before (container, b, i) {
44     return i;
47 function buffer_position_after (container, b, i) {
48     return i + 1;
51 function buffer_position_end (container, b, i) {
52     return container.count;
55 function buffer_position_end_by_type (container, b, i) {
56     // after last buffer of same type
57     var count = container.count;
58     var p = count - 1;
59     while (p >= 0 &&
60            container.get_buffer(p).constructor != b.constructor)
61     {
62         p--;
63     }
64     if (p == -1)
65         return count;
66     else
67         return p + 1;
70 define_variable("new_buffer_position", buffer_position_end,
71     "Used to compute the position in the buffer-list at which "+
72     "to insert new buffers which do not have an opener.  These "+
73     "include buffers created by typing an url or webjump, or "+
74     "buffers created via command-line remoting.  The value "+
75     "should be a number giving the index or a function of three "+
76     "arguments that returns the index at which to insert the "+
77     "new buffer.  The first argument is the buffer_container "+
78     "into which the new buffer is being inserted.  The second "+
79     "argument is the buffer to be inserted.  The third argument "+
80     "is the position of the currently selected buffer.  Several "+
81     "such functions are provided, including, buffer_position_before, "+
82     "buffer_position_after, buffer_position_end, and "+
83     "buffer_position_end_by_type.");
85 define_variable("new_buffer_with_opener_position", buffer_position_after,
86     "Used to compute the position in the buffer-list at which "+
87     "to insert new buffers which have an opener in the same "+
88     "window.  These include buffers created by following a link "+
89     "or frame, and contextual help buffers.  The allowed values "+
90     "are the same as those for `new_buffer_position', except that "+
91     "the second argument passed to the function is the index of "+
92     "the opener instead of the index of the current buffer (often "+
93     "one and the same).");
95 define_variable("bury_buffer_position", null,
96     "Used to compute the position in the buffer-list to move a "+
97     "buried buffer to.  A value of null prevents bury-buffer "+
98     "from moving the buffer at all.  Other allowed values are "+
99     "the same as those for `new_buffer_position', except that "+
100     "the second argument passed to the function is the index of "+
101     "the new buffer that will be selected after burying the "+
102     "current buffer.");
104 define_variable("allow_browser_window_close", true,
105     "If this is set to true, if a content buffer page calls " +
106     "window.close() from JavaScript and is not prevented by the " +
107     "normal Mozilla mechanism that restricts pages from closing " +
108     "a window that was not opened by a script, the buffer will be " +
109     "killed, deleting the window as well if it is the only buffer.");
111 define_keywords("$opener", "$position");
112 function buffer_creator (type) {
113     var args = forward_keywords(arguments);
114     return function (window) {
115         return new type(window, args);
116     };
119 function buffer_modality (buffer) {
120     buffer.keymaps.push(default_global_keymap);
123 function buffer (window) {
124     this.constructor_begin();
125     keywords(arguments, $position = this.default_position);
126     this.opener = arguments.$opener;
127     this.window = window;
128     var element = create_XUL(window, "vbox");
129     element.setAttribute("flex", "1");
130     var browser = create_XUL(window, "browser");
131     browser.setAttribute("type", "content");
132     browser.setAttribute("flex", "1");
133     browser.setAttribute("autocompletepopup", "popup_autocomplete");
134     element.appendChild(browser);
135     this.window.buffers.container.appendChild(element);
136     this.window.buffers.insert(this, arguments.$position, this.opener);
137     this.window.buffers.buffer_history.push(this);
138     this.element = element;
139     this.browser = element.firstChild;
140     this.element.conkeror_buffer_object = this;
142     this.local = { __proto__: conkeror };
143     this.page = null;
144     this.enabled_modes = [];
145     this.default_browser_object_classes = {};
147     var buffer = this;
149     this.browser.addEventListener("scroll", function (event) {
150             buffer_scroll_hook.run(buffer);
151         }, true /* capture */);
153     this.browser.addEventListener("DOMContentLoaded", function (event) {
154             buffer_dom_content_loaded_hook.run(buffer);
155         }, true /* capture */);
157     this.window.setTimeout(function () { create_buffer_late_hook.run(buffer); }, 0);
159     this.browser.addEventListener("load", function (event) {
160             buffer_loaded_hook.run(buffer);
161         }, true /* capture */);
163     this.browser.addEventListener("DOMWindowClose", function (event) {
164             /* This call to preventDefault is very important; without
165              * it, somehow Mozilla does something bad and as a result
166              * the window loses focus, causing keyboard commands to
167              * stop working. */
168             event.preventDefault();
170             if (allow_browser_window_close)
171                 kill_buffer(buffer, true);
172         }, true);
174     this.browser.addEventListener("focus", function (event) {
175         if (buffer.focusblocker &&
176             event.target instanceof Ci.nsIDOMHTMLElement &&
177             buffer.focusblocker(buffer, event))
178         {
179             event.target.blur();
180         } else
181             buffer.set_input_mode();
182     }, true);
184     this.browser.addEventListener("blur", function (event) {
185         buffer.set_input_mode();
186     }, true);
188     this.modalities = [buffer_modality];
190     // When create_buffer_early_hook runs, basic buffer properties
191     // will be available, but not the properties subclasses.
192     create_buffer_early_hook.run(this);
194     this.constructor_end();
196 buffer.prototype = {
197     constructor: buffer,
198     toString: function () "#<buffer>",
200     // default_position is the default value for the $position keyword to
201     // the buffer constructor.  This property can be set on the prototype
202     // of a subclass in order to override new_buffer_position and
203     // new_buffer_with_opener_position for specific types of buffers.
204     default_position: null,
206     /* Saved focus state */
207     saved_focused_frame: null,
208     saved_focused_element: null,
210     // get title ()   [must be defined by subclasses]
211     // get name ()    [must be defined by subclasses]
212     dead: false, /* This is set when the buffer is killed */
214     keymaps: null,
215     mark_active: false,
217     // The property focusblocker is available for an external module to
218     // put a function on which takes a buffer as its argument and returns
219     // true to block a focus event, or false to let normal processing
220     // occur.  Having this one property explicitly handled by the buffer
221     // class allows for otherwise modular focus-blockers.
222     focusblocker: null,
224     // icon is a string url of an icon to use for this buffer.  Setting it
225     // causes buffer_icon_change_hook to be run.
226     _icon: null,
227     get icon () this._icon,
228     set icon (x) {
229         if (this._icon != x) {
230             this._icon = x;
231             buffer_icon_change_hook.run(this);
232         }
233     },
235     default_message: "",
237     set_default_message: function (str) {
238         this.default_message = str;
239         if (this == this.window.buffers.current)
240             this.window.minibuffer.set_default_message(str);
241     },
243     constructors_running: 0,
245     constructor_begin: function () {
246         this.constructors_running++;
247     },
249     constructor_end: function () {
250         if (--this.constructors_running == 0) {
251             create_buffer_hook.run(this);
252             this.set_input_mode();
253             delete this.opener;
254         }
255     },
257     destroy: function () {
258         this.dead = true;
259         this.browser = null;
260         this.element = null;
261         this.saved_focused_frame = null;
262         this.saved_focused_element = null;
263         // prevent modalities from accessing dead browser
264         this.modalities = [];
265     },
267     set_input_mode: function () {
268         if (this != this.window.buffers.current)
269             return;
270         this.keymaps = [];
271         this.modalities.map(function (m) m(this), this);
272         set_input_mode_hook.run(this);
273     },
275     override_keymaps: function (keymaps) {
276         if (keymaps) {
277             this.keymaps = keymaps;
278             this.set_input_mode = function () {
279                 set_input_mode_hook.run(this);
280             };
281         } else
282             delete this.set_input_mode;
283         this.set_input_mode();
284     },
286     /* Browser accessors */
287     get top_frame () { return this.browser.contentWindow; },
288     get document () { return this.browser.contentDocument; },
289     get web_navigation () { return this.browser.webNavigation; },
290     get doc_shell () { return this.browser.docShell; },
291     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
292     get current_uri () { return this.browser.currentURI; },
294     is_child_element: function (element) {
295         return (element && this.is_child_frame(element.ownerDocument.defaultView));
296     },
298     is_child_frame: function (frame) {
299         return (frame && frame.top == this.top_frame);
300     },
302     // This method is like focused_frame, except that if no content
303     // frame actually has focus, this returns null.
304     get focused_frame_or_null () {
305         var frame = this.window.document.commandDispatcher.focusedWindow;
306         if (this.is_child_frame(frame))
307             return frame;
308         return null;
309     },
311     get focused_frame () {
312         var frame = this.window.document.commandDispatcher.focusedWindow;
313         if (this.is_child_frame(frame))
314             return frame;
315         return this.top_frame;
316     },
318     get focused_element () {
319         var element = this.window.document.commandDispatcher.focusedElement;
320         if (this.is_child_element(element))
321             return element;
322         return null;
323     },
325     get focused_selection_controller () {
326         return this.focused_frame
327             .QueryInterface(Ci.nsIInterfaceRequestor)
328             .getInterface(Ci.nsIWebNavigation)
329             .QueryInterface(Ci.nsIInterfaceRequestor)
330             .getInterface(Ci.nsISelectionDisplay)
331             .QueryInterface(Ci.nsISelectionController);
332     },
334     do_command: function (command) {
335         function attempt_command (element, command) {
336             var controller;
337             if (element.controllers
338                 && (controller = element.controllers.getControllerForCommand(command)) != null
339                 && controller.isCommandEnabled(command))
340             {
341                 controller.doCommand(command);
342                 return true;
343             }
344             return false;
345         }
347         var element = this.focused_element;
348         if (element && attempt_command(element, command))
349             return;
350         var win = this.focused_frame;
351         while (true) {
352             if (attempt_command(win, command))
353                 return;
354             if (!win.parent || win == win.parent)
355                 break;
356             win = win.parent;
357         }
358     }
361 function with_current_buffer (buffer, callback) {
362     return callback(new interactive_context(buffer));
365 function check_buffer (obj, type) {
366     if (!(obj instanceof type))
367         throw interactive_error("Buffer has invalid type.");
368     if (obj.dead)
369         throw interactive_error("Buffer has already been killed.");
370     return obj;
373 function caret_enabled (buffer) {
374     return buffer.browser.getAttribute('showcaret');
377 function clear_selection (buffer) {
378     let sel_ctrl = buffer.focused_selection_controller;
379     if (sel_ctrl) {
380         let sel = sel_ctrl.getSelection(sel_ctrl.SELECTION_NORMAL);
381         if (caret_enabled(buffer)) {
382             if (sel.anchorNode)
383                 sel.collapseToStart();
384         } else {
385             sel.removeAllRanges();
386         }
387     }
391 function buffer_container (window, create_initial_buffer) {
392     this.window = window;
393     this.container = window.document.getElementById("buffer-container");
394     this.buffer_list = [];
395     this.buffer_history = [];
396     window.buffers = this;
397     create_initial_buffer(window);
399 buffer_container.prototype = {
400     constructor: buffer_container,
401     toString: function () "#<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 = {};
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[name]) {
517                     ++index;
518                     name = base_name + "<" + index + ">";
519                 }
520                 existing_names[name] = true;
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");