minibuffer.js: whitespace
[conkeror.git] / modules / buffer.js
blobb9fe8610e2d9c439cc621eb8a7d7701a3ac45950
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         this.dead = true;
171         this.browser = null;
172         this.element = null;
173         this.saved_focused_frame = null;
174         this.saved_focused_element = null;
175         // prevent modalities from accessing dead browser
176         this.modalities = [];
177     },
179     set_input_mode: function () {
180         if (this.input_mode)
181             conkeror[this.input_mode](this, false);
182         this.keymaps = [];
183         this.modalities.map(function (m) m(this), this);
184     },
186     /* Browser accessors */
187     get top_frame () { return this.browser.contentWindow; },
188     get document () { return this.browser.contentDocument; },
189     get web_navigation () { return this.browser.webNavigation; },
190     get doc_shell () { return this.browser.docShell; },
191     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
192     get current_uri () { return this.browser.currentURI; },
194     is_child_element: function (element) {
195         return (element && this.is_child_frame(element.ownerDocument.defaultView));
196     },
198     is_child_frame: function (frame) {
199         return (frame && frame.top == this.top_frame);
200     },
202     // This method is like focused_frame, except that if no content
203     // frame actually has focus, this returns null.
204     get focused_frame_or_null () {
205         var frame = this.window.document.commandDispatcher.focusedWindow;
206         if (this.is_child_frame(frame))
207             return frame;
208         return null;
209     },
211     get focused_frame () {
212         var frame = this.window.document.commandDispatcher.focusedWindow;
213         if (this.is_child_frame(frame))
214             return frame;
215         return this.top_frame;
216     },
218     get focused_element () {
219         var element = this.window.document.commandDispatcher.focusedElement;
220         if (this.is_child_element(element))
221             return element;
222         return null;
223     },
225     get focused_selection_controller () {
226         var child_docshells = this.doc_shell.getDocShellEnumerator(
227             Ci.nsIDocShellTreeItem.typeContent,
228             Ci.nsIDocShell.ENUMERATE_FORWARDS);
229         while (child_docshells.hasMoreElements()) {
230             let ds = child_docshells.getNext()
231                 .QueryInterface(Ci.nsIDocShell);
232             if (ds.hasFocus) {
233                 let display = ds.QueryInterface(Ci.nsIInterfaceRequestor)
234                     .getInterface(Ci.nsISelectionDisplay);
235                 if (! display)
236                     return null;
237                 return display.QueryInterface(Ci.nsISelectionController);
238             }
239         }
240         return this.doc_shell
241             .QueryInterface(Ci.nsIInterfaceRequestor)
242             .getInterface(Ci.nsISelectionDisplay)
243             .QueryInterface(Ci.nsISelectionController);
244     },
246     do_command: function (command) {
247         function attempt_command (element, command) {
248             var controller;
249             if (element.controllers
250                 && (controller = element.controllers.getControllerForCommand(command)) != null
251                 && controller.isCommandEnabled(command))
252             {
253                 controller.doCommand(command);
254                 return true;
255             }
256             return false;
257         }
259         var element = this.focused_element;
260         if (element && attempt_command(element, command))
261             return;
262         var win = this.focused_frame;
263         while (true) {
264             if (attempt_command(win, command))
265                 return;
266             if (!win.parent || win == win.parent)
267                 break;
268             win = win.parent;
269         }
270     }
273 function with_current_buffer (buffer, callback) {
274     return callback(new interactive_context(buffer));
277 function check_buffer (obj, type) {
278     if (!(obj instanceof type))
279         throw interactive_error("Buffer has invalid type.");
280     if (obj.dead)
281         throw interactive_error("Buffer has already been killed.");
282     return obj;
285 function caret_enabled (buffer) {
286     return buffer.browser.getAttribute('showcaret');
289 function clear_selection (buffer) {
290     let sel_ctrl = buffer.focused_selection_controller;
291     if (sel_ctrl) {
292         let sel = sel_ctrl.getSelection(sel_ctrl.SELECTION_NORMAL);
293         if (caret_enabled(buffer)) {
294             if (sel.anchorNode)
295                 sel.collapseToStart();
296         } else {
297             sel.removeAllRanges();
298         }
299     }
303 function buffer_container (window, create_initial_buffer) {
304     this.window = window;
305     this.container = window.document.getElementById("buffer-container");
306     this.buffer_list = [];
307     window.buffers = this;
308     create_initial_buffer(window, this.container.firstChild);
311 buffer_container.prototype = {
312     constructor: buffer_container,
314     get current () {
315         return this.container.selectedPanel.conkeror_buffer_object;
316     },
318     set current (buffer) {
319         var old_value = this.current;
320         if (old_value == buffer)
321             return;
323         this.buffer_list.splice(this.buffer_list.indexOf(buffer), 1);
324         this.buffer_list.unshift(buffer);
326         this._switch_away_from(this.current);
327         this._switch_to(buffer);
329         // Run hooks
330         select_buffer_hook.run(buffer);
331     },
333     _switch_away_from: function (old_value) {
334         // Save focus state
335         old_value.saved_focused_frame = old_value.focused_frame;
336         old_value.saved_focused_element = old_value.focused_element;
338         old_value.browser.setAttribute("type", "content");
339     },
341     _switch_to: function (buffer) {
342         // Select new buffer in the XUL deck
343         this.container.selectedPanel = buffer.element;
345         buffer.browser.setAttribute("type", "content-primary");
347         /**
348          * This next focus call seems to be needed to avoid focus
349          * somehow getting lost (and the keypress handler therefore
350          * not getting called at all) when killing buffers.
351          */
352         this.window.focus();
354         // Restore focus state
355         buffer.browser.focus();
356         if (buffer.saved_focused_element)
357             set_focus_no_scroll(this.window, buffer.saved_focused_element);
358         else if (buffer.saved_focused_frame)
359             set_focus_no_scroll(this.window, buffer.saved_focused_frame);
361         buffer.saved_focused_element = null;
362         buffer.saved_focused_frame = null;
364         this.window.minibuffer.set_default_message(buffer.default_message);
365     },
367     get count () {
368         return this.container.childNodes.length;
369     },
371     get_buffer: function (index) {
372         if (index >= 0 && index < this.count)
373             return this.container.childNodes.item(index).conkeror_buffer_object;
374         return null;
375     },
377     get selected_index () {
378         var nodes = this.container.childNodes;
379         var count = nodes.length;
380         for (var i = 0; i < count; ++i)
381             if (nodes.item(i) == this.container.selectedPanel)
382                 return i;
383         return null;
384     },
386     index_of: function (b) {
387         var nodes = this.container.childNodes;
388         var count = nodes.length;
389         for (var i = 0; i < count; ++i)
390             if (nodes.item(i) == b.element)
391                 return i;
392         return null;
393     },
395     get unique_name_list () {
396         var existing_names = new string_hashset();
397         var bufs = [];
398         this.for_each(function(b) {
399                 var base_name = b.name;
400                 var name = base_name;
401                 var index = 1;
402                 while (existing_names.contains(name)) {
403                     ++index;
404                     name = base_name + "<" + index + ">";
405                 }
406                 existing_names.add(name);
407                 bufs.push([name, b]);
408             });
409         return bufs;
410     },
412     kill_buffer: function (b) {
413         if (b.dead)
414             return true;
415         var count = this.count;
416         if (count <= 1)
417             return false;
418         var new_buffer = this.buffer_list[0];
419         var changed = false;
420         if (b == new_buffer) {
421             new_buffer = this.buffer_list[1];
422             changed = true;
423         }
424         this._switch_away_from(this.current);
425         // The removeChild call below may trigger events in progress
426         // listeners.  This call to `destroy' gives buffer subclasses a
427         // chance to remove such listeners, so that they cannot try to
428         // perform UI actions based upon a xul:browser that no longer
429         // exists.
430         var element = b.element;
431         b.destroy();
432         this.container.removeChild(element);
433         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
434         this._switch_to(new_buffer);
435         if (changed) {
436             select_buffer_hook.run(new_buffer);
437             this.buffer_list.splice(this.buffer_list.indexOf(new_buffer), 1);
438             this.buffer_list.unshift(new_buffer);
439         }
440         kill_buffer_hook.run(b);
441         return true;
442     },
444     bury_buffer: function (b) {
445         var new_buffer = this.buffer_list[0];
446         if (b == new_buffer)
447             new_buffer = this.buffer_list[1];
448         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
449         this.buffer_list.push(b);
450         this.current = new_buffer;
451         return true;
452     },
454     for_each: function (f) {
455         var count = this.count;
456         for (var i = 0; i < count; ++i)
457             f(this.get_buffer(i));
458     }
461 function buffer_initialize_window_early (window) {
462     /**
463      * Use content_buffer by default to handle an unusual case where
464      * browser.chromeURI is used perhaps.  In general this default
465      * should not be needed.
466      */
467     var create_initial_buffer =
468         window.args.initial_buffer_creator || buffer_creator(content_buffer);
469     new buffer_container(window, create_initial_buffer);
472 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
475 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
476 function buffer_before_window_close (window) {
477     var bs = window.buffers;
478     var count = bs.count;
479     for (let i = 0; i < count; ++i) {
480         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
481             return false;
482     }
483     return true;
485 add_hook("window_before_close_hook", buffer_before_window_close);
487 function buffer_window_close_handler (window) {
488     var bs = window.buffers;
489     var count = bs.count;
490     for (let i = 0; i < count; ++i) {
491         let b = bs.get_buffer(i);
492         b.destroy();
493     }
495 add_hook("window_close_hook", buffer_window_close_handler);
497 /* open/follow targets */
498 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
499                                // buffer is a content_buffer.
500 const OPEN_NEW_BUFFER = 1;
501 const OPEN_NEW_BUFFER_BACKGROUND = 2;
502 const OPEN_NEW_WINDOW = 3;
504 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
505 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
507 var TARGET_PROMPTS = [" in current buffer",
508                       " in new buffer",
509                       " in new buffer (background)",
510                       " in new window",
511                       "",
512                       " in current frame"];
514 var TARGET_NAMES = ["current buffer",
515                     "new buffer",
516                     "new buffer (background)",
517                     "new window",
518                     "default",
519                     "current frame"];
522 function create_buffer (window, creator, target) {
523     switch (target) {
524     case OPEN_NEW_BUFFER:
525         window.buffers.current = creator(window, null);
526         break;
527     case OPEN_NEW_BUFFER_BACKGROUND:
528         creator(window, null);
529         break;
530     case OPEN_NEW_WINDOW:
531         make_window(creator);
532         break;
533     default:
534         throw new Error("invalid target");
535     }
538 let (queued_buffer_creators = null) {
539     function create_buffer_in_current_window (creator, target, focus_existing) {
540         function process_queued_buffer_creators (window) {
541             for (var i = 0; i < queued_buffer_creators.length; ++i) {
542                 var x = queued_buffer_creators[i];
543                 create_buffer(window, x[0], x[1]);
544             }
545             queued_buffer_creators = null;
546         }
548         if (target == OPEN_NEW_WINDOW)
549             throw new Error("invalid target");
550         var window = get_recent_conkeror_window();
551         if (window) {
552             if (focus_existing)
553                 window.focus();
554             create_buffer(window, creator, target);
555         } else if (queued_buffer_creators != null) {
556             queued_buffer_creators.push([creator,target]);
557         } else {
558             queued_buffer_creators = [];
559             window = make_window(creator);
560             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
561         }
562     }
567  * Read Buffer
568  */
569 minibuffer_auto_complete_preferences["buffer"] = true;
570 define_keywords("$default");
571 minibuffer.prototype.read_buffer = function () {
572     var window = this.window;
573     var buffer = this.window.buffers.current;
574     keywords(arguments, $prompt = "Buffer:",
575              $default = buffer,
576              $history = "buffer");
577     var completer = all_word_completer(
578         $completions = function (visitor) window.buffers.for_each(visitor),
579         $get_string = function (x) x.description,
580         $get_description = function (x) x.title);
581     var result = yield this.read(
582         $keymap = read_buffer_keymap,
583         $prompt = arguments.$prompt,
584         $history = arguments.$history,
585         $completer = completer,
586         $match_required = true,
587         $auto_complete = "buffer",
588         $auto_complete_initial = true,
589         $auto_complete_delay = 0,
590         $default_completion = arguments.$default);
591     yield co_return(result);
595 interactive("buffer-reset-input-mode",
596     "Force a reset of the input mode.  Used by quote-next.",
597     function (I) {
598         I.buffer.set_input_mode();
599     });
602 function buffer_next (window, count) {
603     var index = window.buffers.selected_index;
604     var total = window.buffers.count;
605     if (total == 1)
606         throw new interactive_error("No other buffer");
607     index = (index + count) % total;
608     if (index < 0)
609         index += total;
610     window.buffers.current = window.buffers.get_buffer(index);
612 interactive("buffer-next",
613     "Switch to the next buffer.",
614     function (I) { buffer_next(I.window, I.p); });
615 interactive("buffer-previous",
616     "Switch to the previous buffer.",
617     function (I) { buffer_next(I.window, -I.p); });
619 function switch_to_buffer (window, buffer) {
620     if (buffer && !buffer.dead)
621         window.buffers.current = buffer;
623 interactive("switch-to-buffer",
624     "Switch to a buffer specified in the minibuffer.",
625     function (I) {
626         switch_to_buffer(
627             I.window,
628             (yield I.minibuffer.read_buffer(
629                 $prompt = "Switch to buffer:",
630                 $default = (I.window.buffers.count > 1 ?
631                             I.window.buffers.buffer_list[1] :
632                             I.buffer))));
633     });
635 define_variable("can_kill_last_buffer", true,
636     "If this is set to true, kill-buffer can kill the last "+
637     "remaining buffer, and close the window.");
639 function kill_other_buffers (buffer) {
640     if (!buffer)
641         return;
642     var bs = buffer.window.buffers;
643     var b;
644     while ((b = bs.get_buffer(0)) != buffer)
645         bs.kill_buffer(b);
646     var count = bs.count;
647     while (--count)
648         bs.kill_buffer(bs.get_buffer(1));
650 interactive("kill-other-buffers",
651     "Kill all buffers except current one.\n",
652     function (I) { kill_other_buffers(I.buffer); });
655 function kill_buffer (buffer, force) {
656     if (!buffer)
657         return;
658     var buffers = buffer.window.buffers;
659     if (buffers.count == 1 && buffer == buffers.current) {
660         if (can_kill_last_buffer || force) {
661             delete_window(buffer.window);
662             return;
663         } else
664             throw interactive_error("Can't kill last buffer.");
665     }
666     buffers.kill_buffer(buffer);
668 interactive("kill-buffer",
669     "Kill a buffer specified in the minibuffer.\n" +
670     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
671     "last remaining buffer in a window will cause the window to be closed.",
672     function (I) {
673         kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:")));
674     });
676 interactive("kill-current-buffer",
677     "Kill the current buffer.\n" +
678     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
679     "last remaining buffer in a window will cause the window to be closed.",
680     function (I) { kill_buffer(I.buffer); });
682 interactive("read-buffer-kill-buffer",
683     "Kill the current selected buffer in the completions list "+
684     "in a read buffer minibuffer interaction.",
685     function (I) {
686         var s = I.window.minibuffer.current_state;
687         var i = s.selected_completion_index;
688         var c = s.completions;
689         if (i == -1)
690             return;
691         kill_buffer(c.get_value(i));
692         s.completer.refresh();
693         s.handle_input(I.window.minibuffer);
694     });
696 interactive("bury-buffer",
697     "Bury the current buffer.\n Put the current buffer at the end of " +
698     "the buffer list, so that it is the least likely buffer to be " +
699     "selected by `switch-to-buffer'.",
700     function (I) { I.window.buffers.bury_buffer(I.buffer); });
702 function change_directory (buffer, dir) {
703     if (buffer.page != null)
704         delete buffer.page.local.cwd;
705     buffer.local.cwd = make_file(dir);
707 interactive("change-directory",
708     "Change the current directory of the selected buffer.",
709     function (I) {
710         change_directory(
711             I.buffer,
712             (yield I.minibuffer.read_existing_directory_path(
713                 $prompt = "Change to directory:",
714                 $initial_value = make_file(I.local.cwd).path)));
715     });
717 interactive("shell-command", null,
718     function (I) {
719         var cwd = I.local.cwd;
720         var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
721         yield shell_command(cmd, $cwd = cwd);
722     });
726  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
727  * frames, iframes, plugins, and also clearing the selection.
728  */
729 define_buffer_local_hook("unfocus_hook");
730 function unfocus (window, buffer) {
731     // 1. if there is a selection, clear it.
732     var selc = buffer.focused_selection_controller;
733     if (selc) {
734         var sel = selc.getSelection(selc.SELECTION_NORMAL);
735         var active = ! sel.isCollapsed;
736         clear_selection(buffer);
737         if (active) {
738             window.minibuffer.message("cleared selection");
739             return;
740         }
741     }
742     // 2. if there is a focused element, unfocus it.
743     if (buffer.focused_element) {
744         buffer.focused_element.blur();
745         // if an element in a detached fragment has focus, blur() will
746         // not work, and we need to take more drastic measures.  the
747         // action taken was found through experiment, so it is possibly
748         // not the most concise way to unfocus such an element.
749         if (buffer.focused_element) {
750             buffer.element.focus();
751             buffer.top_frame.focus();
752         }
753         window.minibuffer.message("unfocused element");
754         return;
755     }
756     // 3. if an iframe has focus, we must blur it.
757     if (buffer.focused_frame_or_null &&
758         buffer.focused_frame_or_null.frameElement)
759     {
760         buffer.focused_frame_or_null.frameElement.blur();
761     }
762     // 4. return focus to top-frame from subframes and plugins.
763     buffer.top_frame.focus();
764     buffer.top_frame.focus(); // needed to get focus back from plugins
765     window.minibuffer.message("refocused top frame");
766     // give page-modes an opportunity to set focus specially
767     unfocus_hook.run(buffer);
769 interactive("unfocus",
770     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
771     "frames, iframes, plugins, and also for clearing the selection.  "+
772     "The action that it takes is based on precedence.  If there is a "+
773     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
774     "there is a selection, it will clear the selection.  Otherwise, it "+
775     "will return focus to the top frame from a focused frame, iframe, "+
776     "or plugin.  In the case of plugins, since they steal keyboard "+
777     "control away from Conkeror, the normal way to unfocus them is "+
778     "to use command-line remoting externally: conkeror -batch -f "+
779     "unfocus.  Page-modes also have an opportunity to alter the default"+
780     "focus via the hook, `focus_hook'.",
781     function (I) {
782         unfocus(I.window, I.buffer);
783     });
786 function for_each_buffer (f) {
787     for_each_window(function (w) { w.buffers.for_each(f); });
792  * BUFFER MODES
793  */
795 var mode_functions = {};
796 var mode_display_names = {};
798 define_buffer_local_hook("buffer_mode_change_hook");
799 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
801 define_keywords("$display_name", "$class", "$enable", "$disable", "$doc");
802 function define_buffer_mode (name) {
803     keywords(arguments);
805     var hyphen_name = name.replace("_","-","g");
806     var display_name = arguments.$display_name;
807     var mode_class = arguments.$class;
808     var enable = arguments.$enable;
809     var disable = arguments.$disable;
811     mode_display_names[name] = display_name;
813     var can_disable;
815     if (disable == false) {
816         can_disable = false;
817         disable = null;
818     } else
819         can_disable = true;
821     var state = (mode_class != null) ? mode_class : (name + "_enabled");
822     var enable_hook_name = name + "_enable_hook";
823     var disable_hook_name = name + "_disable_hook";
824     define_buffer_local_hook(enable_hook_name);
825     define_buffer_local_hook(disable_hook_name);
827     var change_hook_name = null;
829     if (mode_class) {
830         mode_functions[name] = { enable: enable,
831                                  disable: disable,
832                                  mode_class: mode_class,
833                                  disable_hook_name: disable_hook_name };
834         change_hook_name = mode_class + "_change_hook";
835         define_buffer_local_hook(change_hook_name);
836     }
838     function func (buffer, arg) {
839         var old_state = buffer[state];
840         var cur_state = (old_state == name);
841         var new_state = (arg == null) ? !cur_state : (arg > 0);
842         if ((new_state == cur_state) || (!can_disable && !new_state))
843             // perhaps show a message if (!can_disable && !new_state)
844             // to tell the user that this mode cannot be disabled.  do
845             // we have any existing modes that would benefit by it?
846             return null;
847         if (new_state) {
848             if (mode_class && old_state != null)  {
849                 // Another buffer-mode of our same mode-class is
850                 // enabled.  Buffer-modes within a mode-class are
851                 // mutually exclusive, so turn the old one off.
852                 buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(old_state), 1);
853                 let x = mode_functions[old_state];
854                 let y = x.disable;
855                 if (y) y(buffer);
856                 conkeror[x.disable_hook_name].run(buffer);
857             }
858             buffer[state] = name;
859             if (enable)
860                 enable(buffer);
861             conkeror[enable_hook_name].run(buffer);
862             buffer.enabled_modes.push(name);
863         } else {
864             buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(name), 1);
865             disable(buffer);
866             conkeror[disable_hook_name].run(buffer);
867             buffer[state] = null;
868         }
869         if (change_hook_name)
870             conkeror[change_hook_name].run(buffer, buffer[state]);
871         buffer_mode_change_hook.run(buffer);
872         return new_state;
873     }
875     conkeror[name] = func;
876     interactive(hyphen_name, arguments.$doc, function (I) {
877         var arg = I.P;
878         var new_state = func(I.buffer, arg && univ_arg_to_number(arg));
879         I.minibuffer.message(hyphen_name + (new_state ? " enabled" : " disabled"));
880     });
882 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
885 function minibuffer_mode_indicator (window) {
886     this.window = window;
887     var element = create_XUL(window, "label");
888     element.setAttribute("id", "minibuffer-mode-indicator");
889     element.collapsed = true;
890     element.setAttribute("class", "minibuffer");
891     window.document.getElementById("minibuffer").appendChild(element);
892     this.element = element;
893     this.hook_func = method_caller(this, this.update);
894     add_hook.call(window, "select_buffer_hook", this.hook_func);
895     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_func);
896     this.update();
898 minibuffer_mode_indicator.prototype = {
899     update: function () {
900         var buf = this.window.buffers.current;
901         var modes = buf.enabled_modes;
902         var str = modes.map(
903             function (x) {
904                 let y = mode_display_names[x];
905                 if (y)
906                     return "[" + y + "]";
907                 else
908                     return null;
909             }).filter(function (x) x != null).join(" ");
910         this.element.collapsed = (str.length == 0);
911         this.element.value = str;
912     },
913     uninstall: function () {
914         remove_hook.call(window, "select_buffer_hook", this.hook_fun);
915         remove_hook.call(window, "current_buffer_mode_change_hook", this.hook_fun);
916         this.element.parentNode.removeChild(this.element);
917     }
919 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
920 minibuffer_mode_indicator_mode(true);
925  * INPUT MODES
926  */
927 define_current_buffer_hook("current_buffer_input_mode_change_hook", "input_mode_change_hook");
928 define_keywords("$display_name", "$doc");
929 function define_input_mode (base_name, keymap_name) {
930     keywords(arguments);
931     var name = base_name + "_input_mode";
932     define_buffer_mode(name,
933                        $class = "input_mode",
934                        $enable = function (buffer) {
935                            check_buffer(buffer, content_buffer);
936                            buffer.keymaps.push(conkeror[keymap_name]);
937                        },
938                        $disable = function (buffer) {
939                            var i = buffer.keymaps.indexOf(conkeror[keymap_name]);
940                            if (i > -1)
941                                buffer.keymaps.splice(i, 1);
942                        },
943                        forward_keywords(arguments));
945 ignore_function_for_get_caller_source_code_reference("define_input_mode");
948 function minibuffer_input_mode_indicator (window) {
949     this.window = window;
950     this.hook_func = method_caller(this, this.update);
951     add_hook.call(window, "select_buffer_hook", this.hook_func);
952     add_hook.call(window, "current_buffer_input_mode_change_hook", this.hook_func);
953     this.update();
956 minibuffer_input_mode_indicator.prototype = {
957     update: function () {
958         var buf = this.window.buffers.current;
959         var mode = buf.input_mode;
960         var classname = mode ? ("minibuffer-" + buf.input_mode.replace("_","-","g")) : "";
961         this.window.minibuffer.element.className = classname;
962     },
963     uninstall: function () {
964         remove_hook.call(window, "select_buffer_hook", this.hook_func);
965         remove_hook.call(window, "current_buffer_input_mode_change_hook", this.hook_func);
966     }
969 define_global_window_mode("minibuffer_input_mode_indicator", "window_initialize_hook");
970 minibuffer_input_mode_indicator_mode(true);
972 provide("buffer");