remove unused code
[conkeror.git] / modules / buffer.js
blobb128ae03b8f976b6d8bd87e5cad55e563e31bba3
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007-2010 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("select_buffer_hook");
27 define_buffer_local_hook("create_buffer_early_hook");
28 define_buffer_local_hook("create_buffer_hook");
29 define_buffer_local_hook("kill_buffer_hook");
30 define_buffer_local_hook("buffer_scroll_hook");
31 define_buffer_local_hook("buffer_dom_content_loaded_hook");
32 define_buffer_local_hook("buffer_loaded_hook");
34 define_current_buffer_hook("current_buffer_title_change_hook", "buffer_title_change_hook");
35 define_current_buffer_hook("current_buffer_description_change_hook", "buffer_description_change_hook");
36 define_current_buffer_hook("current_buffer_scroll_hook", "buffer_scroll_hook");
37 define_current_buffer_hook("current_buffer_dom_content_loaded_hook", "buffer_dom_content_loaded_hook");
40 define_keywords("$opener");
41 function buffer_creator (type) {
42     var args = forward_keywords(arguments);
43     return function (window) {
44         return new type(window, args);
45     };
48 define_variable("allow_browser_window_close", true,
49     "If this is set to true, if a content buffer page calls " +
50     "window.close() from JavaScript and is not prevented by the " +
51     "normal Mozilla mechanism that restricts pages from closing " +
52     "a window that was not opened by a script, the buffer will be " +
53     "killed, deleting the window as well if it is the only buffer.");
55 function buffer (window) {
56     this.constructor_begin();
57     keywords(arguments);
58     this.opener = arguments.$opener;
59     this.window = window;
60     var element = create_XUL(window, "vbox");
61     element.setAttribute("flex", "1");
62     var browser = create_XUL(window, "browser");
63     browser.setAttribute("type", "content");
64     browser.setAttribute("flex", "1");
65     browser.setAttribute("autocompletepopup", "popup_autocomplete");
66     element.appendChild(browser);
67     this.window.buffers.container.appendChild(element);
68     this.window.buffers.buffer_list.push(this);
69     this.element = element;
70     this.browser = element.firstChild;
71     this.element.conkeror_buffer_object = this;
73     this.local = { __proto__: conkeror };
74     this.page = null;
75     this.enabled_modes = [];
76     this.default_browser_object_classes = {};
78     var buffer = this;
80     this.browser.addEventListener("scroll", function (event) {
81             buffer_scroll_hook.run(buffer);
82         }, true /* capture */);
84     this.browser.addEventListener("DOMContentLoaded", function (event) {
85             buffer_dom_content_loaded_hook.run(buffer);
86         }, true /* capture */);
88     this.browser.addEventListener("load", function (event) {
89             buffer_loaded_hook.run(buffer);
90         }, true /* capture */);
92     this.browser.addEventListener("DOMWindowClose", function (event) {
93             /* This call to preventDefault is very important; without
94              * it, somehow Mozilla does something bad and as a result
95              * the window loses focus, causing keyboard commands to
96              * stop working. */
97             event.preventDefault();
99             if (allow_browser_window_close)
100                 kill_buffer(buffer, true);
101         }, true);
103     this.browser.addEventListener("focus", function (event) {
104         if (buffer.focusblocker &&
105             event.target instanceof Ci.nsIDOMHTMLElement &&
106             buffer.focusblocker(buffer, event))
107         {
108             event.target.blur();
109         } else
110             buffer.set_input_mode();
111     }, true);
113     this.browser.addEventListener("blur", function (event) {
114         buffer.set_input_mode();
115     }, true);
117     this.modalities = [];
119     this.override_keymaps = [];
121     // When create_buffer_hook_early runs, basic buffer properties
122     // will be available, but not the properties subclasses.
123     create_buffer_early_hook.run(this);
125     this.constructor_end();
128 buffer.prototype = {
129     /* Saved focus state */
130     saved_focused_frame: null,
131     saved_focused_element: null,
133     // get title ()   [must be defined by subclasses]
134     // get name ()    [must be defined by subclasses]
135     dead: false, /* This is set when the buffer is killed */
137     keymaps: null,
138     mark_active: false,
140     // The property focusblocker is available for an external module to
141     // put a function on which takes a buffer as its argument and returns
142     // true to block a focus event, or false to let normal processing
143     // occur.  Having this one property explicitly handled by the buffer
144     // class allows for otherwise modular focus-blockers.
145     focusblocker: null,
147     default_message: "",
149     set_default_message: function (str) {
150         this.default_message = str;
151         if (this == this.window.buffers.current)
152             this.window.minibuffer.set_default_message(str);
153     },
155     constructors_running: 0,
157     constructor_begin : function () {
158         this.constructors_running++;
159     },
161     constructor_end: function () {
162         if (--this.constructors_running == 0) {
163             create_buffer_hook.run(this);
164             this.set_input_mode();
165             delete this.opener;
166         }
167     },
169     destroy: function () {
170         // prevent modalities from accessing dead browser
171         this.modalities = [];
172     },
174     set_input_mode: function () {
175         if (this.input_mode)
176             conkeror[this.input_mode](this, false);
177         this.keymaps = [];
178         this.modalities.map(function (m) m(this), this);
179     },
181     /* Browser accessors */
182     get top_frame () { return this.browser.contentWindow; },
183     get document () { return this.browser.contentDocument; },
184     get web_navigation () { return this.browser.webNavigation; },
185     get doc_shell () { return this.browser.docShell; },
186     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
187     get current_uri () { return this.browser.currentURI; },
189     is_child_element: function (element) {
190         return (element && this.is_child_frame(element.ownerDocument.defaultView));
191     },
193     is_child_frame: function (frame) {
194         return (frame && frame.top == this.top_frame);
195     },
197     // This method is like focused_frame, except that if no content
198     // frame actually has focus, this returns null.
199     get focused_frame_or_null () {
200         var frame = this.window.document.commandDispatcher.focusedWindow;
201         if (this.is_child_frame(frame))
202             return frame;
203         return null;
204     },
206     get focused_frame () {
207         var frame = this.window.document.commandDispatcher.focusedWindow;
208         if (this.is_child_frame(frame))
209             return frame;
210         return this.top_frame;
211     },
213     get focused_element () {
214         var element = this.window.document.commandDispatcher.focusedElement;
215         if (this.is_child_element(element))
216             return element;
217         return null;
218     },
220     get focused_selection_controller () {
221         var child_docshells = this.doc_shell.getDocShellEnumerator(
222             Ci.nsIDocShellTreeItem.typeContent,
223             Ci.nsIDocShell.ENUMERATE_FORWARDS);
224         while (child_docshells.hasMoreElements()) {
225             let ds = child_docshells.getNext()
226                 .QueryInterface(Ci.nsIDocShell);
227             if (ds.hasFocus) {
228                 let display = ds.QueryInterface(Ci.nsIInterfaceRequestor)
229                     .getInterface(Ci.nsISelectionDisplay);
230                 if (! display)
231                     return null;
232                 return display.QueryInterface(Ci.nsISelectionController);
233             }
234         }
235         return this.doc_shell
236             .QueryInterface(Ci.nsIInterfaceRequestor)
237             .getInterface(Ci.nsISelectionDisplay)
238             .QueryInterface(Ci.nsISelectionController);
239     },
241     do_command: function (command) {
242         function attempt_command (element, command) {
243             var controller;
244             if (element.controllers
245                 && (controller = element.controllers.getControllerForCommand(command)) != null
246                 && controller.isCommandEnabled(command))
247             {
248                 controller.doCommand(command);
249                 return true;
250             }
251             return false;
252         }
254         var element = this.focused_element;
255         if (element && attempt_command(element, command))
256             return;
257         var win = this.focused_frame;
258         while (true) {
259             if (attempt_command(win, command))
260                 return;
261             if (!win.parent || win == win.parent)
262                 break;
263             win = win.parent;
264         }
265     },
267     handle_kill: function () {
268         this.dead = true;
269         this.browser = null;
270         this.element = null;
271         this.saved_focused_frame = null;
272         this.saved_focused_element = null;
273         kill_buffer_hook.run(this);
274     }
277 function with_current_buffer (buffer, callback) {
278     return callback(new interactive_context(buffer));
281 function check_buffer (obj, type) {
282     if (!(obj instanceof type))
283         throw interactive_error("Buffer has invalid type.");
284     if (obj.dead)
285         throw interactive_error("Buffer has already been killed.");
286     return obj;
289 function caret_enabled (buffer) {
290     return buffer.browser.getAttribute('showcaret');
293 function clear_selection (buffer) {
294     let sel_ctrl = buffer.focused_selection_controller;
295     if (sel_ctrl) {
296         let sel = sel_ctrl.getSelection(sel_ctrl.SELECTION_NORMAL);
297         if (caret_enabled(buffer)) {
298             if (sel.anchorNode)
299                 sel.collapseToStart();
300         } else {
301             sel.removeAllRanges();
302         }
303     }
307 function buffer_container (window, create_initial_buffer) {
308     this.window = window;
309     this.container = window.document.getElementById("buffer-container");
310     this.buffer_list = [];
311     window.buffers = this;
312     create_initial_buffer(window, this.container.firstChild);
315 buffer_container.prototype = {
316     constructor: buffer_container,
318     get current () {
319         return this.container.selectedPanel.conkeror_buffer_object;
320     },
322     set current (buffer) {
323         var old_value = this.current;
324         if (old_value == buffer)
325             return;
327         this.buffer_list.splice(this.buffer_list.indexOf(buffer), 1);
328         this.buffer_list.unshift(buffer);
330         this._switch_away_from(this.current);
331         this._switch_to(buffer);
333         // Run hooks
334         select_buffer_hook.run(buffer);
335     },
337     _switch_away_from: function (old_value) {
338         // Save focus state
339         old_value.saved_focused_frame = old_value.focused_frame;
340         old_value.saved_focused_element = old_value.focused_element;
342         old_value.browser.setAttribute("type", "content");
343     },
345     _switch_to: function (buffer) {
346         // Select new buffer in the XUL deck
347         this.container.selectedPanel = buffer.element;
349         buffer.browser.setAttribute("type", "content-primary");
351         /**
352          * This next focus call seems to be needed to avoid focus
353          * somehow getting lost (and the keypress handler therefore
354          * not getting called at all) when killing buffers.
355          */
356         this.window.focus();
358         // Restore focus state
359         buffer.browser.focus();
360         if (buffer.saved_focused_element)
361             set_focus_no_scroll(this.window, buffer.saved_focused_element);
362         else if (buffer.saved_focused_frame)
363             set_focus_no_scroll(this.window, buffer.saved_focused_frame);
365         buffer.saved_focused_element = null;
366         buffer.saved_focused_frame = null;
368         this.window.minibuffer.set_default_message(buffer.default_message);
369     },
371     get count () {
372         return this.container.childNodes.length;
373     },
375     get_buffer: function (index) {
376         if (index >= 0 && index < this.count)
377             return this.container.childNodes.item(index).conkeror_buffer_object;
378         return null;
379     },
381     get selected_index () {
382         var nodes = this.container.childNodes;
383         var count = nodes.length;
384         for (var i = 0; i < count; ++i)
385             if (nodes.item(i) == this.container.selectedPanel)
386                 return i;
387         return null;
388     },
390     index_of: function (b) {
391         var nodes = this.container.childNodes;
392         var count = nodes.length;
393         for (var i = 0; i < count; ++i)
394             if (nodes.item(i) == b.element)
395                 return i;
396         return null;
397     },
399     get unique_name_list () {
400         var existing_names = new string_hashset();
401         var bufs = [];
402         this.for_each(function(b) {
403                 var base_name = b.name;
404                 var name = base_name;
405                 var index = 1;
406                 while (existing_names.contains(name)) {
407                     ++index;
408                     name = base_name + "<" + index + ">";
409                 }
410                 existing_names.add(name);
411                 bufs.push([name, b]);
412             });
413         return bufs;
414     },
416     kill_buffer: function (b) {
417         if (b.dead)
418             return true;
419         var count = this.count;
420         if (count <= 1)
421             return false;
422         var new_buffer = this.buffer_list[0];
423         var changed = false;
424         if (b == new_buffer) {
425             new_buffer = this.buffer_list[1];
426             changed = true;
427         }
428         this._switch_away_from(this.current);
429         // The removeChild call below may trigger events in progress
430         // listeners.  This call to `destroy' gives buffer subclasses a
431         // chance to remove such listeners, so that they cannot try to
432         // perform UI actions based upon a xul:browser that no longer
433         // exists.
434         b.destroy();
435         this.container.removeChild(b.element);
436         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
437         this._switch_to(new_buffer);
438         if (changed) {
439             select_buffer_hook.run(new_buffer);
440             this.buffer_list.splice(this.buffer_list.indexOf(new_buffer), 1);
441             this.buffer_list.unshift(new_buffer);
442         }
443         b.handle_kill();
444         return true;
445     },
447     bury_buffer: function (b) {
448         var new_buffer = this.buffer_list[0];
449         if (b == new_buffer)
450             new_buffer = this.buffer_list[1];
451         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
452         this.buffer_list.push(b);
453         this.current = new_buffer;
454         return true;
455     },
457     for_each: function (f) {
458         var count = this.count;
459         for (var i = 0; i < count; ++i)
460             f(this.get_buffer(i));
461     }
464 function buffer_initialize_window_early (window) {
465     /**
466      * Use content_buffer by default to handle an unusual case where
467      * browser.chromeURI is used perhaps.  In general this default
468      * should not be needed.
469      */
470     var create_initial_buffer =
471         window.args.initial_buffer_creator || buffer_creator(content_buffer);
472     new buffer_container(window, create_initial_buffer);
475 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
478 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
479 function buffer_before_window_close (window) {
480     var bs = window.buffers;
481     var count = bs.count;
482     for (let i = 0; i < count; ++i) {
483         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
484             return false;
485     }
486     return true;
488 add_hook("window_before_close_hook", buffer_before_window_close);
490 function buffer_window_close_handler (window) {
491     var bs = window.buffers;
492     var count = bs.count;
493     for (let i = 0; i < count; ++i) {
494         let b = bs.get_buffer(i);
495         b.handle_kill();
496     }
498 add_hook("window_close_hook", buffer_window_close_handler);
500 /* open/follow targets */
501 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
502                                // buffer is a content_buffer.
503 const OPEN_NEW_BUFFER = 1;
504 const OPEN_NEW_BUFFER_BACKGROUND = 2;
505 const OPEN_NEW_WINDOW = 3;
507 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
508 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
510 var TARGET_PROMPTS = [" in current buffer",
511                       " in new buffer",
512                       " in new buffer (background)",
513                       " in new window",
514                       "",
515                       " in current frame"];
517 var TARGET_NAMES = ["current buffer",
518                     "new buffer",
519                     "new buffer (background)",
520                     "new window",
521                     "default",
522                     "current frame"];
525 function create_buffer (window, creator, target) {
526     switch (target) {
527     case OPEN_NEW_BUFFER:
528         window.buffers.current = creator(window, null);
529         break;
530     case OPEN_NEW_BUFFER_BACKGROUND:
531         creator(window, null);
532         break;
533     case OPEN_NEW_WINDOW:
534         make_window(creator);
535         break;
536     default:
537         throw new Error("invalid target");
538     }
541 let (queued_buffer_creators = null) {
542     function create_buffer_in_current_window (creator, target, focus_existing) {
543         function process_queued_buffer_creators (window) {
544             for (var i = 0; i < queued_buffer_creators.length; ++i) {
545                 var x = queued_buffer_creators[i];
546                 create_buffer(window, x[0], x[1]);
547             }
548             queued_buffer_creators = null;
549         }
551         if (target == OPEN_NEW_WINDOW)
552             throw new Error("invalid target");
553         var window = get_recent_conkeror_window();
554         if (window) {
555             if (focus_existing)
556                 window.focus();
557             create_buffer(window, creator, target);
558         } else if (queued_buffer_creators != null) {
559             queued_buffer_creators.push([creator,target]);
560         } else {
561             queued_buffer_creators = [];
562             window = make_window(creator);
563             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
564         }
565     }
570  * Read Buffer
571  */
572 minibuffer_auto_complete_preferences["buffer"] = true;
573 define_keywords("$default");
574 minibuffer.prototype.read_buffer = function () {
575     var window = this.window;
576     var buffer = this.window.buffers.current;
577     keywords(arguments, $prompt = "Buffer:",
578              $default = buffer,
579              $history = "buffer");
580     var completer = all_word_completer(
581         $completions = function (visitor) window.buffers.for_each(visitor),
582         $get_string = function (x) x.description,
583         $get_description = function (x) x.title);
584     var result = yield this.read(
585         $keymap = read_buffer_keymap,
586         $prompt = arguments.$prompt,
587         $history = arguments.$history,
588         $completer = completer,
589         $match_required = true,
590         $auto_complete = "buffer",
591         $auto_complete_initial = true,
592         $auto_complete_delay = 0,
593         $default_completion = arguments.$default);
594     yield co_return(result);
598 interactive("buffer-reset-input-mode",
599     "Force a reset of the input mode.  Used by quote-next.",
600     function (I) {
601         I.buffer.set_input_mode();
602     });
605 function buffer_next (window, count) {
606     var index = window.buffers.selected_index;
607     var total = window.buffers.count;
608     if (total == 1)
609         throw new interactive_error("No other buffer");
610     index = (index + count) % total;
611     if (index < 0)
612         index += total;
613     window.buffers.current = window.buffers.get_buffer(index);
615 interactive("buffer-next",
616     "Switch to the next buffer.",
617     function (I) { buffer_next(I.window, I.p); });
618 interactive("buffer-previous",
619     "Switch to the previous buffer.",
620     function (I) { buffer_next(I.window, -I.p); });
622 function switch_to_buffer (window, buffer) {
623     if (buffer && !buffer.dead)
624         window.buffers.current = buffer;
626 interactive("switch-to-buffer",
627     "Switch to a buffer specified in the minibuffer.",
628     function (I) {
629         switch_to_buffer(
630             I.window,
631             (yield I.minibuffer.read_buffer(
632                 $prompt = "Switch to buffer:",
633                 $default = (I.window.buffers.count > 1 ?
634                             I.window.buffers.buffer_list[1] :
635                             I.buffer))));
636     });
638 define_variable("can_kill_last_buffer", true,
639     "If this is set to true, kill-buffer can kill the last "+
640     "remaining buffer, and close the window.");
642 function kill_other_buffers (buffer) {
643     if (!buffer)
644         return;
645     var bs = buffer.window.buffers;
646     var b;
647     while ((b = bs.get_buffer(0)) != buffer)
648         bs.kill_buffer(b);
649     var count = bs.count;
650     while (--count)
651         bs.kill_buffer(bs.get_buffer(1));
653 interactive("kill-other-buffers",
654     "Kill all buffers except current one.\n",
655     function (I) { kill_other_buffers(I.buffer); });
658 function kill_buffer (buffer, force) {
659     if (!buffer)
660         return;
661     var buffers = buffer.window.buffers;
662     if (buffers.count == 1 && buffer == buffers.current) {
663         if (can_kill_last_buffer || force) {
664             delete_window(buffer.window);
665             return;
666         } else
667             throw interactive_error("Can't kill last buffer.");
668     }
669     buffers.kill_buffer(buffer);
671 interactive("kill-buffer",
672     "Kill a buffer specified in the minibuffer.\n" +
673     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
674     "last remaining buffer in a window will cause the window to be closed.",
675     function (I) {
676         kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:")));
677     });
679 interactive("kill-current-buffer",
680     "Kill the current buffer.\n" +
681     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
682     "last remaining buffer in a window will cause the window to be closed.",
683     function (I) { kill_buffer(I.buffer); });
685 interactive("read-buffer-kill-buffer",
686     "Kill the current selected buffer in the completions list "+
687     "in a read buffer minibuffer interaction.",
688     function (I) {
689         var s = I.window.minibuffer.current_state;
690         var i = s.selected_completion_index;
691         var c = s.completions;
692         if (i == -1)
693             return;
694         kill_buffer(c.get_value(i));
695         s.completer.refresh();
696         s.handle_input(I.window.minibuffer);
697     });
699 interactive("bury-buffer",
700     "Bury the current buffer.\n Put the current buffer at the end of " +
701     "the buffer list, so that it is the least likely buffer to be " +
702     "selected by `switch-to-buffer'.",
703     function (I) { I.window.buffers.bury_buffer(I.buffer); });
705 function change_directory (buffer, dir) {
706     if (buffer.page != null)
707         delete buffer.page.local.cwd;
708     buffer.local.cwd = make_file(dir);
710 interactive("change-directory",
711     "Change the current directory of the selected buffer.",
712     function (I) {
713         change_directory(
714             I.buffer,
715             (yield I.minibuffer.read_existing_directory_path(
716                 $prompt = "Change to directory:",
717                 $initial_value = make_file(I.local.cwd).path)));
718     });
720 interactive("shell-command", null,
721     function (I) {
722         var cwd = I.local.cwd;
723         var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
724         yield shell_command(cmd, $cwd = cwd);
725     });
729  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
730  * frames, iframes, plugins, and also clearing the selection.
731  */
732 define_buffer_local_hook("unfocus_hook");
733 function unfocus (window, buffer) {
734     // 1. if there is a selection, clear it.
735     var selc = buffer.focused_selection_controller;
736     if (selc) {
737         var sel = selc.getSelection(selc.SELECTION_NORMAL);
738         var active = ! sel.isCollapsed;
739         clear_selection(buffer);
740         if (active) {
741             window.minibuffer.message("cleared selection");
742             return;
743         }
744     }
745     // 2. if there is a focused element, unfocus it.
746     if (buffer.focused_element) {
747         buffer.focused_element.blur();
748         // if an element in a detached fragment has focus, blur() will
749         // not work, and we need to take more drastic measures.  the
750         // action taken was found through experiment, so it is possibly
751         // not the most concise way to unfocus such an element.
752         if (buffer.focused_element) {
753             buffer.element.focus();
754             buffer.top_frame.focus();
755         }
756         window.minibuffer.message("unfocused element");
757         return;
758     }
759     // 3. if an iframe has focus, we must blur it.
760     if (buffer.focused_frame_or_null &&
761         buffer.focused_frame_or_null.frameElement)
762     {
763         buffer.focused_frame_or_null.frameElement.blur();
764     }
765     // 4. return focus to top-frame from subframes and plugins.
766     buffer.top_frame.focus();
767     buffer.top_frame.focus(); // needed to get focus back from plugins
768     window.minibuffer.message("refocused top frame");
769     // give page-modes an opportunity to set focus specially
770     unfocus_hook.run(buffer);
772 interactive("unfocus",
773     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
774     "frames, iframes, plugins, and also for clearing the selection.  "+
775     "The action that it takes is based on precedence.  If there is a "+
776     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
777     "there is a selection, it will clear the selection.  Otherwise, it "+
778     "will return focus to the top frame from a focused frame, iframe, "+
779     "or plugin.  In the case of plugins, since they steal keyboard "+
780     "control away from Conkeror, the normal way to unfocus them is "+
781     "to use command-line remoting externally: conkeror -batch -f "+
782     "unfocus.  Page-modes also have an opportunity to alter the default"+
783     "focus via the hook, `focus_hook'.",
784     function (I) {
785         unfocus(I.window, I.buffer);
786     });
789 function for_each_buffer (f) {
790     for_each_window(function (w) { w.buffers.for_each(f); });
795  * BUFFER MODES
796  */
798 var mode_functions = {};
799 var mode_display_names = {};
801 define_buffer_local_hook("buffer_mode_change_hook");
802 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
804 define_keywords("$display_name", "$class", "$enable", "$disable", "$doc");
805 function define_buffer_mode (name) {
806     keywords(arguments);
808     var hyphen_name = name.replace("_","-","g");
809     var display_name = arguments.$display_name;
810     var mode_class = arguments.$class;
811     var enable = arguments.$enable;
812     var disable = arguments.$disable;
814     mode_display_names[name] = display_name;
816     var can_disable;
818     if (disable == false) {
819         can_disable = false;
820         disable = null;
821     } else
822         can_disable = true;
824     var state = (mode_class != null) ? mode_class : (name + "_enabled");
825     var enable_hook_name = name + "_enable_hook";
826     var disable_hook_name = name + "_disable_hook";
827     define_buffer_local_hook(enable_hook_name);
828     define_buffer_local_hook(disable_hook_name);
830     var change_hook_name = null;
832     if (mode_class) {
833         mode_functions[name] = { enable: enable,
834                                  disable: disable,
835                                  mode_class: mode_class,
836                                  disable_hook_name: disable_hook_name };
837         change_hook_name = mode_class + "_change_hook";
838         define_buffer_local_hook(change_hook_name);
839     }
841     function func (buffer, arg) {
842         var old_state = buffer[state];
843         var cur_state = (old_state == name);
844         var new_state = (arg == null) ? !cur_state : (arg > 0);
845         if ((new_state == cur_state) || (!can_disable && !new_state))
846             // perhaps show a message if (!can_disable && !new_state)
847             // to tell the user that this mode cannot be disabled.  do
848             // we have any existing modes that would benefit by it?
849             return null;
850         if (new_state) {
851             if (mode_class && old_state != null)  {
852                 // Another buffer-mode of our same mode-class is
853                 // enabled.  Buffer-modes within a mode-class are
854                 // mutually exclusive, so turn the old one off.
855                 buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(old_state), 1);
856                 let x = mode_functions[old_state];
857                 let y = x.disable;
858                 if (y) y(buffer);
859                 conkeror[x.disable_hook_name].run(buffer);
860             }
861             buffer[state] = name;
862             if (enable)
863                 enable(buffer);
864             conkeror[enable_hook_name].run(buffer);
865             buffer.enabled_modes.push(name);
866         } else {
867             buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(name), 1);
868             disable(buffer);
869             conkeror[disable_hook_name].run(buffer);
870             buffer[state] = null;
871         }
872         if (change_hook_name)
873             conkeror[change_hook_name].run(buffer, buffer[state]);
874         buffer_mode_change_hook.run(buffer);
875         return new_state;
876     }
878     conkeror[name] = func;
879     interactive(hyphen_name, arguments.$doc, function (I) {
880         var arg = I.P;
881         var new_state = func(I.buffer, arg && univ_arg_to_number(arg));
882         I.minibuffer.message(hyphen_name + (new_state ? " enabled" : " disabled"));
883     });
885 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
888 function minibuffer_mode_indicator (window) {
889     this.window = window;
890     var element = create_XUL(window, "label");
891     element.setAttribute("id", "minibuffer-mode-indicator");
892     element.collapsed = true;
893     element.setAttribute("class", "minibuffer");
894     window.document.getElementById("minibuffer").appendChild(element);
895     this.element = element;
896     this.hook_func = method_caller(this, this.update);
897     add_hook.call(window, "select_buffer_hook", this.hook_func);
898     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_func);
899     this.update();
901 minibuffer_mode_indicator.prototype = {
902     update: function () {
903         var buf = this.window.buffers.current;
904         var modes = buf.enabled_modes;
905         var str = modes.map(
906             function (x) {
907                 let y = mode_display_names[x];
908                 if (y)
909                     return "[" + y + "]";
910                 else
911                     return null;
912             }).filter(function (x) x != null).join(" ");
913         this.element.collapsed = (str.length == 0);
914         this.element.value = str;
915     },
916     uninstall: function () {
917         remove_hook.call(window, "select_buffer_hook", this.hook_fun);
918         remove_hook.call(window, "current_buffer_mode_change_hook", this.hook_fun);
919         this.element.parentNode.removeChild(this.element);
920     }
922 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
923 minibuffer_mode_indicator_mode(true);
928  * INPUT MODES
929  */
930 define_current_buffer_hook("current_buffer_input_mode_change_hook", "input_mode_change_hook");
931 define_keywords("$display_name", "$doc");
932 function define_input_mode (base_name, keymap_name) {
933     keywords(arguments);
934     var name = base_name + "_input_mode";
935     define_buffer_mode(name,
936                        $class = "input_mode",
937                        $enable = function (buffer) {
938                            check_buffer(buffer, content_buffer);
939                            buffer.keymaps.push(conkeror[keymap_name]);
940                        },
941                        $disable = function (buffer) {
942                            var i = buffer.keymaps.indexOf(conkeror[keymap_name]);
943                            if (i > -1)
944                                buffer.keymaps.splice(i, 1);
945                        },
946                        forward_keywords(arguments));
948 ignore_function_for_get_caller_source_code_reference("define_input_mode");
951 function minibuffer_input_mode_indicator (window) {
952     this.window = window;
953     this.hook_func = method_caller(this, this.update);
954     add_hook.call(window, "select_buffer_hook", this.hook_func);
955     add_hook.call(window, "current_buffer_input_mode_change_hook", this.hook_func);
956     this.update();
959 minibuffer_input_mode_indicator.prototype = {
960     update: function () {
961         var buf = this.window.buffers.current;
962         var mode = buf.input_mode;
963         var classname = mode ? ("minibuffer-" + buf.input_mode.replace("_","-","g")) : "";
964         this.window.minibuffer.element.className = classname;
965     },
966     uninstall: function () {
967         remove_hook.call(window, "select_buffer_hook", this.hook_func);
968         remove_hook.call(window, "current_buffer_input_mode_change_hook", this.hook_func);
969     }
972 define_global_window_mode("minibuffer_input_mode_indicator", "window_initialize_hook");
973 minibuffer_input_mode_indicator_mode(true);
975 provide("buffer");