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