b5251a6d47d2d50315e334fc34f2aa9ae26f7837
[conkeror.git] / modules / buffer.js
blobb5251a6d47d2d50315e334fc34f2aa9ae26f7837
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();
592         // Switch to new buffer before destroying this buffer so that
593         // there always remains a selected buffer
594         this._switch_to(new_buffer);
596         this.container.removeChild(element);
597         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
598         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
599         if (changed) {
600             select_buffer_hook.run(new_buffer);
601             this.buffer_history.splice(this.buffer_history.indexOf(new_buffer), 1);
602             this.buffer_history.unshift(new_buffer);
603         }
604         kill_buffer_hook.run(b);
605         return true;
606     },
608     bury_buffer: function (b) {
609         var new_buffer = this.buffer_history[0];
610         if (b == new_buffer)
611             new_buffer = this.buffer_history[1];
612         if (! new_buffer)
613             throw interactive_error("No other buffer");
614         if (bury_buffer_position != null) {
615             this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
616             this.insert(b, bury_buffer_position, new_buffer);
617         }
618         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
619         this.buffer_history.push(b);
620         this.current = new_buffer;
621         if (bury_buffer_position != null)
622             move_buffer_hook.run(b);
623         return true;
624     },
626     unbury_buffer: function (b) {
627         var c = this.current;
628         if (bury_buffer_position != null) {
629             this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
630             this.buffer_list.splice(this.buffer_list.indexOf(c), 0, b);
631         }
632         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
633         this.buffer_history.unshift(b);
634         this.current = b;
635         if (bury_buffer_position != null)
636             move_buffer_hook.run(b);
637         return true;
638     },
640     for_each: function (f) {
641         var count = this.count;
642         for (var i = 0; i < count; ++i)
643             f(this.get_buffer(i));
644     }
647 function buffer_initialize_window_early (window) {
648     /**
649      * Use content_buffer by default to handle an unusual case where
650      * browser.chromeURI is used perhaps.  In general this default
651      * should not be needed.
652      */
653     var create_initial_buffer =
654         window.args.initial_buffer_creator || buffer_creator(content_buffer);
655     new buffer_container(window, create_initial_buffer);
658 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
662  * initialize_first_buffer_type is a workaround for a XULRunner bug that
663  * first appeared in version 2.0, manifested as missing scrollbars in the
664  * first buffer of any window.  It only affects content-primary browsers,
665  * and the workaround is to initialize the browser as type "content" then
666  * change it to content-primary after a delay.
667  */
668 function initialize_first_buffer_type (window) {
669     window.buffers.current.browser.setAttribute("type", "content-primary");
672 add_hook("window_initialize_late_hook", initialize_first_buffer_type);
675 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
676 function buffer_before_window_close (window) {
677     var bs = window.buffers;
678     var count = bs.count;
679     for (let i = 0; i < count; ++i) {
680         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
681             return false;
682     }
683     return true;
685 add_hook("window_before_close_hook", buffer_before_window_close);
687 function buffer_window_close_handler (window) {
688     var bs = window.buffers;
689     var count = bs.count;
690     for (let i = 0; i < count; ++i) {
691         let b = bs.get_buffer(i);
692         b.destroy();
693     }
695 add_hook("window_close_hook", buffer_window_close_handler);
697 /* open/follow targets */
698 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
699                                // buffer is a content_buffer.
700 const OPEN_NEW_BUFFER = 1;
701 const OPEN_NEW_BUFFER_BACKGROUND = 2;
702 const OPEN_NEW_WINDOW = 3;
704 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
705 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
707 var TARGET_PROMPTS = [" in current buffer",
708                       " in new buffer",
709                       " in new buffer (background)",
710                       " in new window",
711                       "",
712                       " in current frame"];
714 var TARGET_NAMES = ["current buffer",
715                     "new buffer",
716                     "new buffer (background)",
717                     "new window",
718                     "default",
719                     "current frame"];
722 function create_buffer (window, creator, target) {
723     switch (target) {
724     case OPEN_NEW_BUFFER:
725         window.buffers.current = creator(window, null);
726         break;
727     case OPEN_NEW_BUFFER_BACKGROUND:
728         creator(window, null);
729         break;
730     case OPEN_NEW_WINDOW:
731         make_window(creator);
732         break;
733     default:
734         throw new Error("invalid target");
735     }
738 let (queued_buffer_creators = null) {
739     function create_buffer_in_current_window (creator, target, focus_existing) {
740         function process_queued_buffer_creators (window) {
741             for (var i = 0; i < queued_buffer_creators.length; ++i) {
742                 var x = queued_buffer_creators[i];
743                 create_buffer(window, x[0], x[1]);
744             }
745             queued_buffer_creators = null;
746         }
748         if (target == OPEN_NEW_WINDOW)
749             throw new Error("invalid target");
750         var window = get_recent_conkeror_window();
751         if (window) {
752             if (focus_existing)
753                 window.focus();
754             create_buffer(window, creator, target);
755         } else if (queued_buffer_creators != null) {
756             queued_buffer_creators.push([creator,target]);
757         } else {
758             queued_buffer_creators = [];
759             window = make_window(creator);
760             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
761         }
762     }
767  * Read Buffer
768  */
769 define_variable("read_buffer_show_icons", false,
770     "Boolean which says whether read_buffer should show buffer "+
771     "icons in the completions list.\nNote, setting this variable "+
772     "alone does not cause favicons or other kinds of icons to be "+
773     "fetched.  For that, load the `favicon' (or similar other) "+
774     "library.");
776 minibuffer_auto_complete_preferences["buffer"] = true;
777 define_keywords("$buffers", "$default");
778 minibuffer.prototype.read_buffer = function () {
779     var window = this.window;
780     keywords(arguments, $prompt = "Buffer:",
781              $buffers = function (visitor) window.buffers.for_each(visitor),
782              $default = window.buffers.current,
783              $history = "buffer");
784     var completer = all_word_completer(
785         $completions = arguments.$buffers,
786         $get_string = function (x) x.description,
787         $get_description = function (x) x.title,
788         $get_icon = (read_buffer_show_icons ?
789                      function (x) x.icon : null));
790     var result = yield this.read(
791         $keymap = read_buffer_keymap,
792         $prompt = arguments.$prompt,
793         $history = arguments.$history,
794         $completer = completer,
795         $enable_icons = read_buffer_show_icons,
796         $match_required = true,
797         $auto_complete = "buffer",
798         $auto_complete_initial = true,
799         $auto_complete_delay = 0,
800         $default_completion = arguments.$default);
801     yield co_return(result);
805 function buffer_move_forward (window, count) {
806     var buffers = window.buffers;
807     var index = buffers.selected_index;
808     var buffer = buffers.current
809     var total = buffers.count;
810     if (total == 1)
811         return;
812     var new_index = (index + count) % total;
813     if (new_index == index)
814         return;
815     if (new_index < 0)
816         new_index += total;
817     buffers.buffer_list.splice(index, 1);
818     buffers.buffer_list.splice(new_index, 0, buffer);
819     move_buffer_hook.run(buffer);
821 interactive("buffer-move-forward",
822     "Move the current buffer forward in the buffer order.",
823     function (I) { buffer_move_forward(I.window, I.p); });
825 interactive("buffer-move-backward",
826     "Move the current buffer backward in the buffer order.",
827     function (I) { buffer_move_forward(I.window, -I.p); });
830 function buffer_next (window, count) {
831     var index = window.buffers.selected_index;
832     var total = window.buffers.count;
833     if (total == 1)
834         throw new interactive_error("No other buffer");
835     index = (index + count) % total;
836     if (index < 0)
837         index += total;
838     window.buffers.current = window.buffers.get_buffer(index);
840 interactive("buffer-next",
841     "Switch to the next buffer.",
842     function (I) { buffer_next(I.window, I.p); });
843 interactive("buffer-previous",
844     "Switch to the previous buffer.",
845     function (I) { buffer_next(I.window, -I.p); });
847 function switch_to_buffer (window, buffer) {
848     if (buffer && !buffer.dead)
849         window.buffers.current = buffer;
851 interactive("switch-to-buffer",
852     "Prompt for a buffer and switch to it.",
853     function (I) {
854         switch_to_buffer(
855             I.window,
856             (yield I.minibuffer.read_buffer(
857                 $prompt = "Switch to buffer:",
858                 $default = (I.window.buffers.count > 1 ?
859                             I.window.buffers.buffer_history[1] :
860                             I.buffer))));
861     });
863 define_variable("can_kill_last_buffer", true,
864     "When true, kill-buffer can kill the last  buffer in a window, "+
865     "and close the window.");
867 function kill_other_buffers (buffer) {
868     if (!buffer)
869         return;
870     var bs = buffer.window.buffers;
871     var b;
872     while ((b = bs.get_buffer(0)) != buffer)
873         bs.kill_buffer(b);
874     var count = bs.count;
875     while (--count)
876         bs.kill_buffer(bs.get_buffer(1));
878 interactive("kill-other-buffers",
879     "Kill all buffers except current one.\n",
880     function (I) { kill_other_buffers(I.buffer); });
883 function kill_buffer (buffer, force) {
884     if (!buffer)
885         return;
886     var buffers = buffer.window.buffers;
887     if (buffers.count == 1 && buffer == buffers.current) {
888         if (can_kill_last_buffer || force) {
889             delete_window(buffer.window);
890             return;
891         } else
892             throw interactive_error("Can't kill last buffer.");
893     }
894     buffers.kill_buffer(buffer);
896 interactive("kill-buffer",
897     "Kill a buffer specified in the minibuffer.\n" +
898     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
899     "last remaining buffer in a window will cause the window to be closed.",
900     function (I) {
901         kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:")));
902     });
904 interactive("kill-current-buffer",
905     "Kill the current buffer.\n" +
906     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
907     "last remaining buffer in a window will cause the window to be closed.",
908     function (I) { kill_buffer(I.buffer); });
910 interactive("read-buffer-kill-buffer",
911     "Kill the current selected buffer in the completions list "+
912     "in a read buffer minibuffer interaction.",
913     function (I) {
914         var s = I.window.minibuffer.current_state;
915         var i = s.selected_completion_index;
916         var c = s.completions;
917         if (i == -1)
918             return;
919         kill_buffer(c.get_value(i));
920         s.completer.refresh();
921         s.handle_input(I.window.minibuffer);
922     });
924 interactive("bury-buffer",
925     "Bury the current buffer.\nPut the current buffer at the end of " +
926     "the buffer list, so that it is the least likely buffer to be " +
927     "selected by `switch-to-buffer'.",
928     function (I) { I.window.buffers.bury_buffer(I.buffer); });
930 interactive("unbury-buffer",
931     "Unbury the buffer lowest in the buffer-history list.\n"+
932     "With universal argument, prompt for a buffer.  When "+
933     "`bury_buffer_position` is non-null, move the buffer "+
934     "to the current position in the buffer list.",
935     function (I) {
936         var buffers = I.window.buffers;
937         if (I.prefix_argument)
938             var b = yield I.minibuffer.read_buffer(
939                 $prompt = "Switch to buffer:",
940                 $buffers = function (visitor) {
941                     var count = buffers.count;
942                     for (var i = count - 1; i >= 0; --i)
943                         visitor(buffers.buffer_history[i]);
944                 },
945                 $default = buffers.buffer_history[buffers.count - 1]);
946         else
947             b = buffers.buffer_history[buffers.count - 1];
948         buffers.unbury_buffer(b);
949     });
951 function change_directory (buffer, dir) {
952     if (buffer.page != null)
953         delete buffer.page.local.cwd;
954     buffer.local.cwd = make_file(dir);
956 interactive("change-directory",
957     "Change the current directory of the selected buffer.",
958     function (I) {
959         change_directory(
960             I.buffer,
961             (yield I.minibuffer.read_existing_directory_path(
962                 $prompt = "Change to directory:",
963                 $initial_value = make_file(I.local.cwd).path)));
964     });
966 interactive("shell-command", null,
967     function (I) {
968         var cwd = I.local.cwd;
969         var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
970         yield shell_command(cmd, $cwd = cwd);
971     });
975  * selection_is_embed_p is used to test whether the unfocus command can
976  * unfocus an element, even though there is a selection.  This happens
977  * when the focused element is an html:embed.
978  */
979 function selection_is_embed_p (sel, focused_element) {
980     if (sel.rangeCount == 1) {
981         try {
982             var r = sel.getRangeAt(0);
983             var a = r.startContainer.childNodes[r.startOffset];
984             if ((a instanceof Ci.nsIDOMHTMLEmbedElement ||
985                  a instanceof Ci.nsIDOMHTMLObjectElement) &&
986                 a == focused_element)
987             {
988                 return true;
989             }
990         } catch (e) {}
991     }
992     return false;
996  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
997  * frames, iframes, plugins, and also clearing the selection.
998  */
999 define_buffer_local_hook("unfocus_hook");
1000 function unfocus (window, buffer) {
1001     // 1. if there is a selection, clear it.
1002     var selc = buffer.focused_selection_controller;
1003     if (selc) {
1004         var sel = selc.getSelection(selc.SELECTION_NORMAL);
1005         var active = ! sel.isCollapsed;
1006         var embed_p = selection_is_embed_p(sel, buffer.focused_element);
1007         clear_selection(buffer);
1008         if (active && !embed_p) {
1009             window.minibuffer.message("cleared selection");
1010             return;
1011         }
1012     }
1013     // 2. if there is a focused element, unfocus it.
1014     if (buffer.focused_element) {
1015         buffer.focused_element.blur();
1016         // if an element in a detached fragment has focus, blur() will
1017         // not work, and we need to take more drastic measures.  the
1018         // action taken was found through experiment, so it is possibly
1019         // not the most concise way to unfocus such an element.
1020         if (buffer.focused_element) {
1021             buffer.element.focus();
1022             buffer.top_frame.focus();
1023         }
1024         window.minibuffer.message("unfocused element");
1025         return;
1026     }
1027     // 3. if an iframe has focus, we must blur it.
1028     if (buffer.focused_frame_or_null &&
1029         buffer.focused_frame_or_null.frameElement)
1030     {
1031         buffer.focused_frame_or_null.frameElement.blur();
1032     }
1033     // 4. return focus to top-frame from subframes and plugins.
1034     buffer.top_frame.focus();
1035     buffer.top_frame.focus(); // needed to get focus back from plugins
1036     window.minibuffer.message("refocused top frame");
1037     // give page-modes an opportunity to set focus specially
1038     unfocus_hook.run(buffer);
1040 interactive("unfocus",
1041     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
1042     "frames, iframes, plugins, and also for clearing the selection.\n"+
1043     "The action that it takes is based on precedence.  If there is a "+
1044     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
1045     "there is a selection, it will clear the selection.  Otherwise, it "+
1046     "will return focus to the top frame from a focused frame, iframe, "+
1047     "or plugin.  In the case of plugins, since they steal keyboard "+
1048     "control away from Conkeror, the normal way to unfocus them is "+
1049     "to use command-line remoting externally: conkeror -batch -f "+
1050     "unfocus.  Page-modes also have an opportunity to alter the default"+
1051     "focus via the hook, `focus_hook'.",
1052     function (I) {
1053         unfocus(I.window, I.buffer);
1054     });
1057 function for_each_buffer (f) {
1058     for_each_window(function (w) { w.buffers.for_each(f); });
1063  * Buffer Modes
1064  */
1066 define_buffer_local_hook("buffer_mode_change_hook");
1067 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
1069 define_keywords("$display_name", "$doc");
1070 function buffer_mode (name, enable, disable) {
1071     keywords(arguments);
1072     this.name = name.replace("-","_","g");
1073     this.hyphen_name = name.replace("_","-","g");
1074     if (enable)
1075         this._enable = enable;
1076     if (disable)
1077         this._disable = disable;
1078     this.display_name = arguments.$display_name;
1079     this.doc = arguments.$doc;
1080     this.enable_hook = this.name + "_enable_hook";
1081     this.disable_hook = this.name + "_disable_hook";
1083 buffer_mode.prototype = {
1084     constructor: buffer_mode,
1085     name: null,
1086     display_name: null,
1087     doc: null,
1088     enable_hook: null,
1089     disable_hook: null,
1090     _enable: null,
1091     _disable: null,
1092     enable: function (buffer) {
1093         try {
1094             if (this._enable)
1095                 this._enable(buffer);
1096         } finally {
1097             buffer.enabled_modes.push(this.name);
1098             if (conkeror[this.enable_hook])
1099                 conkeror[this.enable_hook].run(buffer);
1100             buffer_mode_change_hook.run(buffer);
1101         }
1102     },
1103     disable: function (buffer) {
1104         try {
1105             if (this._disable)
1106                 this._disable(buffer);
1107         } finally {
1108             var i = buffer.enabled_modes.indexOf(this.name);
1109             if (i > -1)
1110                 buffer.enabled_modes.splice(i, 1);
1111             if (conkeror[this.disable_hook])
1112                 conkeror[this.disable_hook].run(buffer);
1113             buffer_mode_change_hook.run(buffer);
1114         }
1115     }
1117 define_keywords("$constructor");
1118 function define_buffer_mode (name, enable, disable) {
1119     keywords(arguments, $constructor = buffer_mode, $doc = null);
1120     var constructor = arguments.$constructor;
1121     var m = new constructor(name, enable, disable, forward_keywords(arguments));
1122     name = m.name; // normalized
1123     conkeror[name] = m;
1124     define_buffer_local_hook(m.enable_hook);
1125     define_buffer_local_hook(m.disable_hook);
1126     interactive(m.hyphen_name,
1127         arguments.$doc,
1128         function (I) {
1129             var enabledp = (I.buffer.enabled_modes.indexOf(name) > -1);
1130             if (enabledp)
1131                 m.disable(I.buffer);
1132             else
1133                 m.enable(I.buffer);
1134             I.minibuffer.message(m.hyphen_name + (enabledp ? " disabled" : " enabled"));
1135         });
1137 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
1141  * Mode Display in Minibuffer
1142  */
1144 function minibuffer_mode_indicator (window) {
1145     this.window = window;
1146     var element = create_XUL(window, "label");
1147     element.setAttribute("id", "minibuffer-mode-indicator");
1148     element.setAttribute("class", "mode-text-widget");
1149     window.document.getElementById("minibuffer").appendChild(element);
1150     this.element = element;
1151     this.hook_function = method_caller(this, this.update);
1152     add_hook.call(window, "select_buffer_hook", this.hook_function);
1153     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_function);
1154     this.update();
1156 minibuffer_mode_indicator.prototype = {
1157     constructor: minibuffer_mode_indicator,
1158     window: null,
1159     element: null,
1160     hook_function: null,
1161     update: function () {
1162         var buffer = this.window.buffers.current;
1163         var str = buffer.enabled_modes.map(
1164             function (x) {
1165                 return (conkeror[x].display_name || null);
1166             }).filter(function (x) x != null).join(" ");
1167         this.element.value = str;
1168     },
1169     uninstall: function () {
1170         remove_hook.call(this.window, "select_buffer_hook", this.hook_function);
1171         remove_hook.call(this.window, "current_buffer_mode_change_hook", this.hook_function);
1172         this.element.parentNode.removeChild(this.element);
1173     }
1175 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
1176 minibuffer_mode_indicator_mode(true);
1180  * minibuffer-keymaps-display
1181  */
1182 function minibuffer_keymaps_display_update (buffer) {
1183     var element = buffer.window.document
1184         .getElementById("keymaps-display");
1185     if (element) {
1186         var str = buffer.keymaps.reduce(
1187             function (acc, kmap) {
1188                 if (kmap.display_name)
1189                     acc.push(kmap.display_name);
1190                 return acc;
1191             }, []).join("/");
1192         if (element.value != str)
1193             element.value = str;
1194     }
1197 function minibuffer_keymaps_display_initialize (window) {
1198     var element = create_XUL(window, "label");
1199     element.setAttribute("id", "keymaps-display");
1200     element.setAttribute("class", "mode-text-widget");
1201     element.setAttribute("value", "");
1202     var mb = window.document.getElementById("minibuffer");
1203     mb.appendChild(element);
1206 define_global_mode("minibuffer_keymaps_display_mode",
1207     function enable () {
1208         add_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1209         add_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1210         for_each_window(minibuffer_keymaps_display_initialize);
1211     },
1212     function disable () {
1213         remove_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1214         remove_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1215         for_each_window(function (w) {
1216             var element = w.document
1217                 .getElementById("keymaps-display");
1218             if (element)
1219                 element.parentNode.removeChild(element);
1220         });
1221     });
1223 minibuffer_keymaps_display_mode(true);
1227  * minibuffer-keymaps-highlight
1228  */
1229 function minibuffer_keymaps_highlight_update (buffer) {
1230     var mb = buffer.window.document.getElementById("minibuffer");
1231     if (buffer.keymaps.some(function (k) k.notify))
1232         dom_add_class(mb, "highlight");
1233     else
1234         dom_remove_class(mb, "highlight");
1237 define_global_mode("minibuffer_keymaps_highlight_mode",
1238     function enable () {
1239         add_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1240     },
1241     function disable () {
1242         remove_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1243         for_each_window(function (w) {
1244             var mb = w.document.getElementById("minibuffer");
1245             if (mb)
1246                 dom_remove_class("highlight");
1247         });
1248     });
1250 minibuffer_keymaps_highlight_mode(true);
1253 provide("buffer");