fix 2 docstrings
[conkeror.git] / modules / buffer.js
blob98ed0a80eba72f4cc664822e74747874bff23d96
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");
33 define_buffer_local_hook("set_input_mode_hook");
35 define_current_buffer_hook("current_buffer_title_change_hook", "buffer_title_change_hook");
36 define_current_buffer_hook("current_buffer_description_change_hook", "buffer_description_change_hook");
37 define_current_buffer_hook("current_buffer_scroll_hook", "buffer_scroll_hook");
38 define_current_buffer_hook("current_buffer_dom_content_loaded_hook", "buffer_dom_content_loaded_hook");
41 define_keywords("$opener");
42 function buffer_creator (type) {
43     var args = forward_keywords(arguments);
44     return function (window) {
45         return new type(window, args);
46     };
49 define_variable("allow_browser_window_close", true,
50     "If this is set to true, if a content buffer page calls " +
51     "window.close() from JavaScript and is not prevented by the " +
52     "normal Mozilla mechanism that restricts pages from closing " +
53     "a window that was not opened by a script, the buffer will be " +
54     "killed, deleting the window as well if it is the only buffer.");
56 function buffer_modality (buffer) {
57     buffer.keymaps.push(default_global_keymap);
60 function buffer (window) {
61     this.constructor_begin();
62     keywords(arguments);
63     this.opener = arguments.$opener;
64     this.window = window;
65     var element = create_XUL(window, "vbox");
66     element.setAttribute("flex", "1");
67     var browser = create_XUL(window, "browser");
68     if (window.buffers.count == 0)
69         browser.setAttribute("type", "content-primary");
70     else
71         browser.setAttribute("type", "content");
72     browser.setAttribute("flex", "1");
73     browser.setAttribute("autocompletepopup", "popup_autocomplete");
74     element.appendChild(browser);
75     this.window.buffers.container.appendChild(element);
76     this.window.buffers.buffer_list.push(this);
77     this.element = element;
78     this.browser = element.firstChild;
79     this.element.conkeror_buffer_object = this;
81     this.local = { __proto__: conkeror };
82     this.page = null;
83     this.enabled_modes = [];
84     this.default_browser_object_classes = {};
86     var buffer = this;
88     this.browser.addEventListener("scroll", function (event) {
89             buffer_scroll_hook.run(buffer);
90         }, true /* capture */);
92     this.browser.addEventListener("DOMContentLoaded", function (event) {
93             buffer_dom_content_loaded_hook.run(buffer);
94         }, true /* capture */);
96     this.browser.addEventListener("load", function (event) {
97             buffer_loaded_hook.run(buffer);
98         }, true /* capture */);
100     this.browser.addEventListener("DOMWindowClose", function (event) {
101             /* This call to preventDefault is very important; without
102              * it, somehow Mozilla does something bad and as a result
103              * the window loses focus, causing keyboard commands to
104              * stop working. */
105             event.preventDefault();
107             if (allow_browser_window_close)
108                 kill_buffer(buffer, true);
109         }, true);
111     this.browser.addEventListener("focus", function (event) {
112         if (buffer.focusblocker &&
113             event.target instanceof Ci.nsIDOMHTMLElement &&
114             buffer.focusblocker(buffer, event))
115         {
116             event.target.blur();
117         } else
118             buffer.set_input_mode();
119     }, true);
121     this.browser.addEventListener("blur", function (event) {
122         buffer.set_input_mode();
123     }, true);
125     this.modalities = [buffer_modality];
127     // When create_buffer_hook_early runs, basic buffer properties
128     // will be available, but not the properties subclasses.
129     create_buffer_early_hook.run(this);
131     this.constructor_end();
133 buffer.prototype = {
134     constructor: buffer,
136     /* Saved focus state */
137     saved_focused_frame: null,
138     saved_focused_element: null,
140     // get title ()   [must be defined by subclasses]
141     // get name ()    [must be defined by subclasses]
142     dead: false, /* This is set when the buffer is killed */
144     keymaps: null,
145     mark_active: false,
147     // The property focusblocker is available for an external module to
148     // put a function on which takes a buffer as its argument and returns
149     // true to block a focus event, or false to let normal processing
150     // occur.  Having this one property explicitly handled by the buffer
151     // class allows for otherwise modular focus-blockers.
152     focusblocker: null,
154     default_message: "",
156     set_default_message: function (str) {
157         this.default_message = str;
158         if (this == this.window.buffers.current)
159             this.window.minibuffer.set_default_message(str);
160     },
162     constructors_running: 0,
164     constructor_begin: function () {
165         this.constructors_running++;
166     },
168     constructor_end: function () {
169         if (--this.constructors_running == 0) {
170             create_buffer_hook.run(this);
171             this.set_input_mode();
172             delete this.opener;
173         }
174     },
176     destroy: function () {
177         this.dead = true;
178         this.browser = null;
179         this.element = null;
180         this.saved_focused_frame = null;
181         this.saved_focused_element = null;
182         // prevent modalities from accessing dead browser
183         this.modalities = [];
184     },
186     set_input_mode: function () {
187         if (this != this.window.buffers.current)
188             return;
189         this.keymaps = [];
190         this.modalities.map(function (m) m(this), this);
191         set_input_mode_hook.run(this);
192     },
194     override_keymaps: function (keymaps) {
195         if (keymaps) {
196             this.keymaps = keymaps;
197             this.set_input_mode = function () {
198                 set_input_mode_hook.run(this);
199             };
200         } else
201             delete this.set_input_mode;
202         this.set_input_mode();
203     },
205     /* Browser accessors */
206     get top_frame () { return this.browser.contentWindow; },
207     get document () { return this.browser.contentDocument; },
208     get web_navigation () { return this.browser.webNavigation; },
209     get doc_shell () { return this.browser.docShell; },
210     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
211     get current_uri () { return this.browser.currentURI; },
213     is_child_element: function (element) {
214         return (element && this.is_child_frame(element.ownerDocument.defaultView));
215     },
217     is_child_frame: function (frame) {
218         return (frame && frame.top == this.top_frame);
219     },
221     // This method is like focused_frame, except that if no content
222     // frame actually has focus, this returns null.
223     get focused_frame_or_null () {
224         var frame = this.window.document.commandDispatcher.focusedWindow;
225         if (this.is_child_frame(frame))
226             return frame;
227         return null;
228     },
230     get focused_frame () {
231         var frame = this.window.document.commandDispatcher.focusedWindow;
232         if (this.is_child_frame(frame))
233             return frame;
234         return this.top_frame;
235     },
237     get focused_element () {
238         var element = this.window.document.commandDispatcher.focusedElement;
239         if (this.is_child_element(element))
240             return element;
241         return null;
242     },
244     get focused_selection_controller () {
245         return this.focused_frame
246             .QueryInterface(Ci.nsIInterfaceRequestor)
247             .getInterface(Ci.nsIWebNavigation)
248             .QueryInterface(Ci.nsIInterfaceRequestor)
249             .getInterface(Ci.nsISelectionDisplay)
250             .QueryInterface(Ci.nsISelectionController);
251     },
253     do_command: function (command) {
254         function attempt_command (element, command) {
255             var controller;
256             if (element.controllers
257                 && (controller = element.controllers.getControllerForCommand(command)) != null
258                 && controller.isCommandEnabled(command))
259             {
260                 controller.doCommand(command);
261                 return true;
262             }
263             return false;
264         }
266         var element = this.focused_element;
267         if (element && attempt_command(element, command))
268             return;
269         var win = this.focused_frame;
270         while (true) {
271             if (attempt_command(win, command))
272                 return;
273             if (!win.parent || win == win.parent)
274                 break;
275             win = win.parent;
276         }
277     }
280 function with_current_buffer (buffer, callback) {
281     return callback(new interactive_context(buffer));
284 function check_buffer (obj, type) {
285     if (!(obj instanceof type))
286         throw interactive_error("Buffer has invalid type.");
287     if (obj.dead)
288         throw interactive_error("Buffer has already been killed.");
289     return obj;
292 function caret_enabled (buffer) {
293     return buffer.browser.getAttribute('showcaret');
296 function clear_selection (buffer) {
297     let sel_ctrl = buffer.focused_selection_controller;
298     if (sel_ctrl) {
299         let sel = sel_ctrl.getSelection(sel_ctrl.SELECTION_NORMAL);
300         if (caret_enabled(buffer)) {
301             if (sel.anchorNode)
302                 sel.collapseToStart();
303         } else {
304             sel.removeAllRanges();
305         }
306     }
310 function buffer_container (window, create_initial_buffer) {
311     this.window = window;
312     this.container = window.document.getElementById("buffer-container");
313     this.buffer_list = [];
314     window.buffers = this;
315     create_initial_buffer(window);
317 buffer_container.prototype = {
318     constructor: buffer_container,
320     get current () {
321         return this.container.selectedPanel.conkeror_buffer_object;
322     },
324     set current (buffer) {
325         var old_value = this.current;
326         if (old_value == buffer)
327             return;
329         this.buffer_list.splice(this.buffer_list.indexOf(buffer), 1);
330         this.buffer_list.unshift(buffer);
332         this._switch_away_from(this.current);
333         this._switch_to(buffer);
335         // Run hooks
336         select_buffer_hook.run(buffer);
337     },
339     _switch_away_from: function (old_value) {
340         // Save focus state
341         old_value.saved_focused_frame = old_value.focused_frame;
342         old_value.saved_focused_element = old_value.focused_element;
344         old_value.browser.setAttribute("type", "content");
345     },
347     _switch_to: function (buffer) {
348         // Select new buffer in the XUL deck
349         this.container.selectedPanel = buffer.element;
351         buffer.browser.setAttribute("type", "content-primary");
353         /**
354          * This next focus call seems to be needed to avoid focus
355          * somehow getting lost (and the keypress handler therefore
356          * not getting called at all) when killing buffers.
357          */
358         this.window.focus();
360         // Restore focus state
361         buffer.browser.focus();
362         if (buffer.saved_focused_element)
363             set_focus_no_scroll(this.window, buffer.saved_focused_element);
364         else if (buffer.saved_focused_frame)
365             set_focus_no_scroll(this.window, buffer.saved_focused_frame);
367         buffer.saved_focused_element = null;
368         buffer.saved_focused_frame = null;
370         buffer.set_input_mode();
372         this.window.minibuffer.set_default_message(buffer.default_message);
373     },
375     get count () {
376         return this.container.childNodes.length;
377     },
379     get_buffer: function (index) {
380         if (index >= 0 && index < this.count)
381             return this.container.childNodes.item(index).conkeror_buffer_object;
382         return null;
383     },
385     get selected_index () {
386         var nodes = this.container.childNodes;
387         var count = nodes.length;
388         for (var i = 0; i < count; ++i)
389             if (nodes.item(i) == this.container.selectedPanel)
390                 return i;
391         return null;
392     },
394     index_of: function (b) {
395         var nodes = this.container.childNodes;
396         var count = nodes.length;
397         for (var i = 0; i < count; ++i)
398             if (nodes.item(i) == b.element)
399                 return i;
400         return null;
401     },
403     get unique_name_list () {
404         var existing_names = new string_hashset();
405         var bufs = [];
406         this.for_each(function(b) {
407                 var base_name = b.name;
408                 var name = base_name;
409                 var index = 1;
410                 while (existing_names.contains(name)) {
411                     ++index;
412                     name = base_name + "<" + index + ">";
413                 }
414                 existing_names.add(name);
415                 bufs.push([name, b]);
416             });
417         return bufs;
418     },
420     kill_buffer: function (b) {
421         if (b.dead)
422             return true;
423         var count = this.count;
424         if (count <= 1)
425             return false;
426         var new_buffer = this.buffer_list[0];
427         var changed = false;
428         if (b == new_buffer) {
429             new_buffer = this.buffer_list[1];
430             changed = true;
431         }
432         this._switch_away_from(this.current);
433         // The removeChild call below may trigger events in progress
434         // listeners.  This call to `destroy' gives buffer subclasses a
435         // chance to remove such listeners, so that they cannot try to
436         // perform UI actions based upon a xul:browser that no longer
437         // exists.
438         var element = b.element;
439         b.destroy();
440         this.container.removeChild(element);
441         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
442         this._switch_to(new_buffer);
443         if (changed) {
444             select_buffer_hook.run(new_buffer);
445             this.buffer_list.splice(this.buffer_list.indexOf(new_buffer), 1);
446             this.buffer_list.unshift(new_buffer);
447         }
448         kill_buffer_hook.run(b);
449         return true;
450     },
452     bury_buffer: function (b) {
453         var new_buffer = this.buffer_list[0];
454         if (b == new_buffer)
455             new_buffer = this.buffer_list[1];
456         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
457         this.buffer_list.push(b);
458         this.current = new_buffer;
459         return true;
460     },
462     for_each: function (f) {
463         var count = this.count;
464         for (var i = 0; i < count; ++i)
465             f(this.get_buffer(i));
466     }
469 function buffer_initialize_window_early (window) {
470     /**
471      * Use content_buffer by default to handle an unusual case where
472      * browser.chromeURI is used perhaps.  In general this default
473      * should not be needed.
474      */
475     var create_initial_buffer =
476         window.args.initial_buffer_creator || buffer_creator(content_buffer);
477     new buffer_container(window, create_initial_buffer);
480 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
483 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
484 function buffer_before_window_close (window) {
485     var bs = window.buffers;
486     var count = bs.count;
487     for (let i = 0; i < count; ++i) {
488         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
489             return false;
490     }
491     return true;
493 add_hook("window_before_close_hook", buffer_before_window_close);
495 function buffer_window_close_handler (window) {
496     var bs = window.buffers;
497     var count = bs.count;
498     for (let i = 0; i < count; ++i) {
499         let b = bs.get_buffer(i);
500         b.destroy();
501     }
503 add_hook("window_close_hook", buffer_window_close_handler);
505 /* open/follow targets */
506 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
507                                // buffer is a content_buffer.
508 const OPEN_NEW_BUFFER = 1;
509 const OPEN_NEW_BUFFER_BACKGROUND = 2;
510 const OPEN_NEW_WINDOW = 3;
512 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
513 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
515 var TARGET_PROMPTS = [" in current buffer",
516                       " in new buffer",
517                       " in new buffer (background)",
518                       " in new window",
519                       "",
520                       " in current frame"];
522 var TARGET_NAMES = ["current buffer",
523                     "new buffer",
524                     "new buffer (background)",
525                     "new window",
526                     "default",
527                     "current frame"];
530 function create_buffer (window, creator, target) {
531     switch (target) {
532     case OPEN_NEW_BUFFER:
533         window.buffers.current = creator(window, null);
534         break;
535     case OPEN_NEW_BUFFER_BACKGROUND:
536         creator(window, null);
537         break;
538     case OPEN_NEW_WINDOW:
539         make_window(creator);
540         break;
541     default:
542         throw new Error("invalid target");
543     }
546 let (queued_buffer_creators = null) {
547     function create_buffer_in_current_window (creator, target, focus_existing) {
548         function process_queued_buffer_creators (window) {
549             for (var i = 0; i < queued_buffer_creators.length; ++i) {
550                 var x = queued_buffer_creators[i];
551                 create_buffer(window, x[0], x[1]);
552             }
553             queued_buffer_creators = null;
554         }
556         if (target == OPEN_NEW_WINDOW)
557             throw new Error("invalid target");
558         var window = get_recent_conkeror_window();
559         if (window) {
560             if (focus_existing)
561                 window.focus();
562             create_buffer(window, creator, target);
563         } else if (queued_buffer_creators != null) {
564             queued_buffer_creators.push([creator,target]);
565         } else {
566             queued_buffer_creators = [];
567             window = make_window(creator);
568             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
569         }
570     }
575  * Read Buffer
576  */
577 minibuffer_auto_complete_preferences["buffer"] = true;
578 define_keywords("$default");
579 minibuffer.prototype.read_buffer = function () {
580     var window = this.window;
581     var buffer = this.window.buffers.current;
582     keywords(arguments, $prompt = "Buffer:",
583              $default = buffer,
584              $history = "buffer");
585     var completer = all_word_completer(
586         $completions = function (visitor) window.buffers.for_each(visitor),
587         $get_string = function (x) x.description,
588         $get_description = function (x) x.title);
589     var result = yield this.read(
590         $keymap = read_buffer_keymap,
591         $prompt = arguments.$prompt,
592         $history = arguments.$history,
593         $completer = completer,
594         $match_required = true,
595         $auto_complete = "buffer",
596         $auto_complete_initial = true,
597         $auto_complete_delay = 0,
598         $default_completion = arguments.$default);
599     yield co_return(result);
603 function buffer_next (window, count) {
604     var index = window.buffers.selected_index;
605     var total = window.buffers.count;
606     if (total == 1)
607         throw new interactive_error("No other buffer");
608     index = (index + count) % total;
609     if (index < 0)
610         index += total;
611     window.buffers.current = window.buffers.get_buffer(index);
613 interactive("buffer-next",
614     "Switch to the next buffer.",
615     function (I) { buffer_next(I.window, I.p); });
616 interactive("buffer-previous",
617     "Switch to the previous buffer.",
618     function (I) { buffer_next(I.window, -I.p); });
620 function switch_to_buffer (window, buffer) {
621     if (buffer && !buffer.dead)
622         window.buffers.current = buffer;
624 interactive("switch-to-buffer",
625     "Switch to a buffer specified in the minibuffer.",
626     function (I) {
627         switch_to_buffer(
628             I.window,
629             (yield I.minibuffer.read_buffer(
630                 $prompt = "Switch to buffer:",
631                 $default = (I.window.buffers.count > 1 ?
632                             I.window.buffers.buffer_list[1] :
633                             I.buffer))));
634     });
636 define_variable("can_kill_last_buffer", true,
637     "If this is set to true, kill-buffer can kill the last "+
638     "remaining buffer, and close the window.");
640 function kill_other_buffers (buffer) {
641     if (!buffer)
642         return;
643     var bs = buffer.window.buffers;
644     var b;
645     while ((b = bs.get_buffer(0)) != buffer)
646         bs.kill_buffer(b);
647     var count = bs.count;
648     while (--count)
649         bs.kill_buffer(bs.get_buffer(1));
651 interactive("kill-other-buffers",
652     "Kill all buffers except current one.\n",
653     function (I) { kill_other_buffers(I.buffer); });
656 function kill_buffer (buffer, force) {
657     if (!buffer)
658         return;
659     var buffers = buffer.window.buffers;
660     if (buffers.count == 1 && buffer == buffers.current) {
661         if (can_kill_last_buffer || force) {
662             delete_window(buffer.window);
663             return;
664         } else
665             throw interactive_error("Can't kill last buffer.");
666     }
667     buffers.kill_buffer(buffer);
669 interactive("kill-buffer",
670     "Kill a buffer specified in the minibuffer.\n" +
671     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
672     "last remaining buffer in a window will cause the window to be closed.",
673     function (I) {
674         kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:")));
675     });
677 interactive("kill-current-buffer",
678     "Kill the current buffer.\n" +
679     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
680     "last remaining buffer in a window will cause the window to be closed.",
681     function (I) { kill_buffer(I.buffer); });
683 interactive("read-buffer-kill-buffer",
684     "Kill the current selected buffer in the completions list "+
685     "in a read buffer minibuffer interaction.",
686     function (I) {
687         var s = I.window.minibuffer.current_state;
688         var i = s.selected_completion_index;
689         var c = s.completions;
690         if (i == -1)
691             return;
692         kill_buffer(c.get_value(i));
693         s.completer.refresh();
694         s.handle_input(I.window.minibuffer);
695     });
697 interactive("bury-buffer",
698     "Bury the current buffer.\n Put the current buffer at the end of " +
699     "the buffer list, so that it is the least likely buffer to be " +
700     "selected by `switch-to-buffer'.",
701     function (I) { I.window.buffers.bury_buffer(I.buffer); });
703 function change_directory (buffer, dir) {
704     if (buffer.page != null)
705         delete buffer.page.local.cwd;
706     buffer.local.cwd = make_file(dir);
708 interactive("change-directory",
709     "Change the current directory of the selected buffer.",
710     function (I) {
711         change_directory(
712             I.buffer,
713             (yield I.minibuffer.read_existing_directory_path(
714                 $prompt = "Change to directory:",
715                 $initial_value = make_file(I.local.cwd).path)));
716     });
718 interactive("shell-command", null,
719     function (I) {
720         var cwd = I.local.cwd;
721         var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
722         yield shell_command(cmd, $cwd = cwd);
723     });
727  * selection_is_embed_p is used to test whether the unfocus command can
728  * unfocus an element, even though there is a selection.  This happens
729  * when the focused element is an html:embed.
730  */
731 function selection_is_embed_p (sel, focused_element) {
732     if (sel.rangeCount == 1) {
733         try {
734             var r = sel.getRangeAt(0);
735             var a = r.startContainer.childNodes[r.startOffset];
736             if ((a instanceof Ci.nsIDOMHTMLEmbedElement ||
737                  a instanceof Ci.nsIDOMHTMLObjectElement) &&
738                 a == focused_element)
739             {
740                 return true;
741             }
742         } catch (e) {}
743     }
744     return false;
748  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
749  * frames, iframes, plugins, and also clearing the selection.
750  */
751 define_buffer_local_hook("unfocus_hook");
752 function unfocus (window, buffer) {
753     // 1. if there is a selection, clear it.
754     var selc = buffer.focused_selection_controller;
755     if (selc) {
756         var sel = selc.getSelection(selc.SELECTION_NORMAL);
757         var active = ! sel.isCollapsed;
758         var embed_p = selection_is_embed_p(sel, buffer.focused_element);
759         clear_selection(buffer);
760         if (active && !embed_p) {
761             window.minibuffer.message("cleared selection");
762             return;
763         }
764     }
765     // 2. if there is a focused element, unfocus it.
766     if (buffer.focused_element) {
767         buffer.focused_element.blur();
768         // if an element in a detached fragment has focus, blur() will
769         // not work, and we need to take more drastic measures.  the
770         // action taken was found through experiment, so it is possibly
771         // not the most concise way to unfocus such an element.
772         if (buffer.focused_element) {
773             buffer.element.focus();
774             buffer.top_frame.focus();
775         }
776         window.minibuffer.message("unfocused element");
777         return;
778     }
779     // 3. if an iframe has focus, we must blur it.
780     if (buffer.focused_frame_or_null &&
781         buffer.focused_frame_or_null.frameElement)
782     {
783         buffer.focused_frame_or_null.frameElement.blur();
784     }
785     // 4. return focus to top-frame from subframes and plugins.
786     buffer.top_frame.focus();
787     buffer.top_frame.focus(); // needed to get focus back from plugins
788     window.minibuffer.message("refocused top frame");
789     // give page-modes an opportunity to set focus specially
790     unfocus_hook.run(buffer);
792 interactive("unfocus",
793     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
794     "frames, iframes, plugins, and also for clearing the selection.\n"+
795     "The action that it takes is based on precedence.  If there is a "+
796     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
797     "there is a selection, it will clear the selection.  Otherwise, it "+
798     "will return focus to the top frame from a focused frame, iframe, "+
799     "or plugin.  In the case of plugins, since they steal keyboard "+
800     "control away from Conkeror, the normal way to unfocus them is "+
801     "to use command-line remoting externally: conkeror -batch -f "+
802     "unfocus.  Page-modes also have an opportunity to alter the default"+
803     "focus via the hook, `focus_hook'.",
804     function (I) {
805         unfocus(I.window, I.buffer);
806     });
809 function for_each_buffer (f) {
810     for_each_window(function (w) { w.buffers.for_each(f); });
815  * BUFFER MODES
816  */
818 var mode_functions = {};
819 var mode_display_names = {};
821 define_buffer_local_hook("buffer_mode_change_hook");
822 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
824 define_keywords("$display_name", "$class", "$enable", "$disable", "$doc");
825 function define_buffer_mode (name) {
826     keywords(arguments);
828     var hyphen_name = name.replace("_","-","g");
829     var display_name = arguments.$display_name;
830     var mode_class = arguments.$class;
831     var enable = arguments.$enable;
832     var disable = arguments.$disable;
834     mode_display_names[name] = display_name;
836     var can_disable;
838     if (disable == false) {
839         can_disable = false;
840         disable = null;
841     } else
842         can_disable = true;
844     var state = (mode_class != null) ? mode_class : (name + "_enabled");
845     var enable_hook_name = name + "_enable_hook";
846     var disable_hook_name = name + "_disable_hook";
847     define_buffer_local_hook(enable_hook_name);
848     define_buffer_local_hook(disable_hook_name);
850     var change_hook_name = null;
852     if (mode_class) {
853         mode_functions[name] = { enable: enable,
854                                  disable: disable,
855                                  mode_class: mode_class,
856                                  disable_hook_name: disable_hook_name };
857         change_hook_name = mode_class + "_change_hook";
858         define_buffer_local_hook(change_hook_name);
859     }
861     function func (buffer, arg) {
862         var old_state = buffer[state];
863         var cur_state = (old_state == name);
864         var new_state = (arg == null) ? !cur_state : (arg > 0);
865         if ((new_state == cur_state) || (!can_disable && !new_state))
866             // perhaps show a message if (!can_disable && !new_state)
867             // to tell the user that this mode cannot be disabled.  do
868             // we have any existing modes that would benefit by it?
869             return null;
870         if (new_state) {
871             if (mode_class && old_state != null)  {
872                 // Another buffer-mode of our same mode-class is
873                 // enabled.  Buffer-modes within a mode-class are
874                 // mutually exclusive, so turn the old one off.
875                 buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(old_state), 1);
876                 let x = mode_functions[old_state];
877                 let y = x.disable;
878                 if (y) y(buffer);
879                 conkeror[x.disable_hook_name].run(buffer);
880             }
881             buffer[state] = name;
882             if (enable)
883                 enable(buffer);
884             conkeror[enable_hook_name].run(buffer);
885             buffer.enabled_modes.push(name);
886         } else {
887             buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(name), 1);
888             disable(buffer);
889             conkeror[disable_hook_name].run(buffer);
890             buffer[state] = null;
891         }
892         if (change_hook_name)
893             conkeror[change_hook_name].run(buffer, buffer[state]);
894         buffer_mode_change_hook.run(buffer);
895         return new_state;
896     }
898     conkeror[name] = func;
899     interactive(hyphen_name, arguments.$doc, function (I) {
900         var arg = I.P;
901         var new_state = func(I.buffer, arg && univ_arg_to_number(arg));
902         I.minibuffer.message(hyphen_name + (new_state ? " enabled" : " disabled"));
903     });
905 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
908 function minibuffer_mode_indicator (window) {
909     this.window = window;
910     var element = create_XUL(window, "label");
911     element.setAttribute("id", "minibuffer-mode-indicator");
912     element.setAttribute("class", "mode-text-widget");
913     window.document.getElementById("minibuffer").appendChild(element);
914     this.element = element;
915     this.hook_func = method_caller(this, this.update);
916     add_hook.call(window, "select_buffer_hook", this.hook_func);
917     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_func);
918     this.update();
920 minibuffer_mode_indicator.prototype = {
921     constructor: minibuffer_mode_indicator,
922     update: function () {
923         var buf = this.window.buffers.current;
924         var modes = buf.enabled_modes;
925         var str = modes.map(
926             function (x) {
927                 let y = mode_display_names[x];
928                 if (y)
929                     return y;
930                 else
931                     return null;
932             }).filter(function (x) x != null).join(" ");
933         this.element.value = str;
934     },
935     uninstall: function () {
936         remove_hook.call(this.window, "select_buffer_hook", this.hook_fun);
937         remove_hook.call(this.window, "current_buffer_mode_change_hook", this.hook_fun);
938         this.element.parentNode.removeChild(this.element);
939     }
941 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
942 minibuffer_mode_indicator_mode(true);
946  * minibuffer-keymaps-display
947  */
948 function minibuffer_keymaps_display_update (buffer) {
949     var element = buffer.window.document
950         .getElementById("keymaps-display");
951     if (element) {
952         var str = buffer.keymaps.reduce(
953             function (acc, kmap) {
954                 if (kmap.display_name)
955                     acc.push(kmap.display_name);
956                 return acc;
957             }, []).join("/");
958         if (element.value != str)
959             element.value = str;
960     }
963 function minibuffer_keymaps_display_initialize (window) {
964     var element = create_XUL(window, "label");
965     element.setAttribute("id", "keymaps-display");
966     element.setAttribute("class", "mode-text-widget");
967     element.setAttribute("value", "");
968     var mb = window.document.getElementById("minibuffer");
969     mb.appendChild(element);
972 define_global_mode("minibuffer_keymaps_display_mode",
973     function enable () {
974         add_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
975         add_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
976         for_each_window(minibuffer_keymaps_display_initialize);
977     },
978     function disable () {
979         remove_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
980         remove_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
981         for_each_window(function (w) {
982             var element = w.document
983                 .getElementById("keymaps-display");
984             if (element)
985                 element.parentNode.removeChild(element);
986         });
987     });
989 minibuffer_keymaps_display_mode(true);
993  * minibuffer-keymaps-highlight
994  */
995 function minibuffer_keymaps_highlight_update (buffer) {
996     var mb = buffer.window.document.getElementById("minibuffer");
997     if (buffer.keymaps.some(function (k) k.notify))
998         dom_add_class(mb, "highlight");
999     else
1000         dom_remove_class(mb, "highlight");
1003 define_global_mode("minibuffer_keymaps_highlight_mode",
1004     function enable () {
1005         add_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1006     },
1007     function disable () {
1008         remove_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1009         for_each_window(function (w) {
1010             var mb = w.document.getElementById("minibuffer");
1011             if (mb)
1012                 dom_remove_class("highlight");
1013         });
1014     });
1016 minibuffer_keymaps_highlight_mode(true);
1019 provide("buffer");