whitespace
[conkeror.git] / modules / buffer.js
blobffad0012171a8c33e9252c949491a13be2296c6a
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007-2009 John J. Foerch
4  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
5  *
6  * Use, modification, and distribution are subject to the terms specified in the
7  * COPYING file.
8 **/
10 var define_buffer_local_hook = local_hook_definer("window");
12 function define_current_buffer_hook (hook_name, existing_hook) {
13     define_buffer_local_hook(hook_name);
14     add_hook(existing_hook, function (buffer) {
15             if (!buffer.window.buffers || buffer != buffer.window.buffers.current)
16                 return;
17             var hook = conkeror[hook_name];
18             hook.run.apply(hook, Array.prototype.slice.call(arguments));
19         });
22 define_buffer_local_hook("buffer_title_change_hook");
23 define_buffer_local_hook("buffer_description_change_hook");
24 define_buffer_local_hook("select_buffer_hook");
25 define_buffer_local_hook("create_buffer_early_hook");
26 define_buffer_local_hook("create_buffer_hook");
27 define_buffer_local_hook("kill_buffer_hook");
28 define_buffer_local_hook("buffer_scroll_hook");
29 define_buffer_local_hook("buffer_dom_content_loaded_hook");
30 define_buffer_local_hook("buffer_loaded_hook");
32 define_current_buffer_hook("current_buffer_title_change_hook", "buffer_title_change_hook");
33 define_current_buffer_hook("current_buffer_description_change_hook", "buffer_description_change_hook");
34 define_current_buffer_hook("current_buffer_scroll_hook", "buffer_scroll_hook");
35 define_current_buffer_hook("current_buffer_dom_content_loaded_hook", "buffer_dom_content_loaded_hook");
38 define_keywords("$element", "$opener");
39 function buffer_creator (type) {
40     var args = forward_keywords(arguments);
41     return function (window, element) {
42         return new type(window, element, args);
43     };
46 define_variable("allow_browser_window_close", true,
47     "If this is set to true, if a content buffer page calls " +
48     "window.close() from JavaScript and is not prevented by the " +
49     "normal Mozilla mechanism that restricts pages from closing " +
50     "a window that was not opened by a script, the buffer will be " +
51     "killed, deleting the window as well if it is the only buffer.");
53 function buffer (window, element) {
54     this.constructor_begin();
55     keywords(arguments);
56     this.opener = arguments.$opener;
57     this.window = window;
58     if (element == null) {
59         element = create_XUL(window, "vbox");
60         element.setAttribute("flex", "1");
61         var browser = create_XUL(window, "browser");
62         browser.setAttribute("type", "content");
63         browser.setAttribute("flex", "1");
64         browser.setAttribute("autocompletepopup", "popup_autocomplete");
65         element.appendChild(browser);
66         this.window.buffers.container.appendChild(element);
67     } else {
68         /* Manually set up session history.
69          *
70          * This is needed because when constructor for the XBL binding
71          * (mozilla/toolkit/content/widgets/browser.xml#browser) for
72          * the initial browser element of the window is called, the
73          * docShell is not yet initialized and setting up the session
74          * history will fail.  To work around this problem, we do as
75          * tabbrowser.xml (Firefox) does and set the initial browser
76          * to have the disablehistory=true attribute, and then repeat
77          * the work that would normally be done in the XBL
78          * constructor.
79          */
81         // This code is taken from mozilla/browser/base/content/browser.js
82         let browser = element.firstChild;
83         browser.webNavigation.sessionHistory =
84             Cc["@mozilla.org/browser/shistory;1"].createInstance(Ci.nsISHistory);
85         observer_service.addObserver(browser, "browser:purge-session-history", false);
87         // remove the disablehistory attribute so the browser cleans up, as
88         // though it had done this work itself
89         browser.removeAttribute("disablehistory");
91         // enable global history
92         browser.docShell.QueryInterface(Ci.nsIDocShellHistory).useGlobalHistory = true;
93     }
94     this.window.buffers.buffer_list.push(this);
95     this.element = element;
96     this.browser = element.firstChild;
97     this.element.conkeror_buffer_object = this;
99     this.local = { __proto__ : conkeror };
100     this.page = null;
101     this.enabled_modes = [];
102     this.default_browser_object_classes = {};
104     var buffer = this;
106     this.browser.addEventListener("scroll", function (event) {
107             buffer_scroll_hook.run(buffer);
108         }, true /* capture */);
110     this.browser.addEventListener("DOMContentLoaded", function (event) {
111             buffer_dom_content_loaded_hook.run(buffer);
112         }, true /* capture */);
114     this.browser.addEventListener("load", function (event) {
115             buffer_loaded_hook.run(buffer);
116         }, true /* capture */);
118     this.browser.addEventListener("DOMWindowClose", function (event) {
119             /* This call to preventDefault is very important; without
120              * it, somehow Mozilla does something bad and as a result
121              * the window loses focus, causing keyboard commands to
122              * stop working. */
123             event.preventDefault();
125             if (allow_browser_window_close)
126                 kill_buffer(buffer, true);
127         }, true);
129     this.browser.addEventListener("focus", function (event) {
130         if (buffer.focusblocker &&
131             event.target instanceof Ci.nsIDOMHTMLElement &&
132             buffer.focusblocker(buffer, event))
133         {
134             event.target.blur();
135         } else
136             buffer.set_input_mode();
137     }, true);
138     this.modalities = [];
140     this.override_keymaps = [];
142     // When create_buffer_hook_early runs, basic buffer properties
143     // will be available, but not the properties subclasses.
144     create_buffer_early_hook.run(this);
146     this.constructor_end();
149 buffer.prototype = {
150     /* Saved focus state */
151     saved_focused_frame : null,
152     saved_focused_element : null,
153     on_switch_to : null,
154     on_switch_away : null,
155     // get title ()   [must be defined by subclasses]
156     // get name ()    [must be defined by subclasses]
157     dead : false, /* This is set when the buffer is killed */
159     keymaps: null,
161     // The property focusblocker is available for an external module to
162     // put a function on which takes a buffer as its argument and returns
163     // true to block a focus event, or false to let normal processing
164     // occur.  Having this one property explicitly handled by the buffer
165     // class allows for otherwise modular focus-blockers.
166     focusblocker: null,
168     default_message : "",
170     set_default_message : function (str) {
171         this.default_message = str;
172         if (this == this.window.buffers.current)
173             this.window.minibuffer.set_default_message(str);
174     },
176     constructors_running : 0,
178     constructor_begin : function () {
179         this.constructors_running++;
180     },
182     constructor_end : function () {
183         if (--this.constructors_running == 0) {
184             create_buffer_hook.run(this);
185             this.set_input_mode();
186             delete this.opener;
187         }
188     },
190     destroy: function () {},
192     set_input_mode: function () {
193         if (this.input_mode)
194             conkeror[this.input_mode](this, false);
195         this.keymaps = [];
196         this.modalities.map(function (m) m(this), this);
197     },
199     /* Browser accessors */
200     get top_frame () { return this.browser.contentWindow; },
201     get document () { return this.browser.contentDocument; },
202     get web_navigation () { return this.browser.webNavigation; },
203     get doc_shell () { return this.browser.docShell; },
204     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
205     get current_uri () { return this.browser.currentURI; },
207     is_child_element : function (element) {
208         return (element && this.is_child_frame(element.ownerDocument.defaultView));
209     },
211     is_child_frame : function (frame) {
212         return (frame && frame.top == this.top_frame);
213     },
215     // This method is like focused_frame, except that if no content
216     // frame actually has focus, this returns null.
217     get focused_frame_or_null () {
218         var frame = this.window.document.commandDispatcher.focusedWindow;
219         var top = this.top_frame;
220         if (this.is_child_frame(frame))
221             return frame;
222         return null;
223     },
225     get focused_frame () {
226         var frame = this.window.document.commandDispatcher.focusedWindow;
227         var top = this.top_frame;
228         if (this.is_child_frame(frame))
229             return frame;
230         return this.top_frame;
231     },
233     get focused_element () {
234         var element = this.window.document.commandDispatcher.focusedElement;
235         if (this.is_child_element(element))
236             return element;
237         return null;
238     },
240     do_command : function (command) {
241         function attempt_command (element, command) {
242             var controller;
243             if (element.controllers
244                 && (controller = element.controllers.getControllerForCommand(command)) != null
245                 && controller.isCommandEnabled(command))
246             {
247                 controller.doCommand(command);
248                 return true;
249             }
250             return false;
251         }
253         var element = this.focused_element;
254         if (element && attempt_command(element, command))
255             return;
256         var win = this.focused_frame;
257         do  {
258             if (attempt_command(win, command))
259                 return;
260             if (!win.parent || win == win.parent)
261                 break;
262             win = win.parent;
263         } while (true);
264     },
266     handle_kill : function () {
267         this.dead = true;
268         this.browser = null;
269         this.element = null;
270         this.saved_focused_frame = null;
271         this.saved_focused_element = null;
272         kill_buffer_hook.run(this);
273     }
276 function with_current_buffer (buffer, callback) {
277     return callback(new interactive_context(buffer));
280 function check_buffer (obj, type) {
281     if (!(obj instanceof type))
282         throw interactive_error("Buffer has invalid type.");
283     if (obj.dead)
284         throw interactive_error("Buffer has already been killed.");
285     return obj;
288 function buffer_container (window, create_initial_buffer) {
289     this.window = window;
290     this.container = window.document.getElementById("buffer-container");
291     this.buffer_list = [];
292     window.buffers = this;
294     create_initial_buffer(window, this.container.firstChild);
297 buffer_container.prototype = {
298     constructor : buffer_container,
300     get current () {
301         return this.container.selectedPanel.conkeror_buffer_object;
302     },
304     set current (buffer) {
305         var old_value = this.current;
306         if (old_value == buffer)
307             return;
309         this.buffer_list.splice(this.buffer_list.indexOf(buffer), 1);
310         this.buffer_list.unshift(buffer);
312         this._switch_away_from(this.current);
313         this._switch_to(buffer);
315         // Run hooks
316         select_buffer_hook.run(buffer);
317     },
319     _switch_away_from : function (old_value) {
320         // Save focus state
321         old_value.saved_focused_frame = old_value.focused_frame;
322         old_value.saved_focused_element = old_value.focused_element;
324         old_value.browser.setAttribute("type", "content");
325     },
327     _switch_to : function (buffer) {
328         // Select new buffer in the XUL deck
329         this.container.selectedPanel = buffer.element;
331         buffer.browser.setAttribute("type", "content-primary");
333         /**
334          * This next focus call seems to be needed to avoid focus
335          * somehow getting lost (and the keypress handler therefore
336          * not getting called at all) when killing buffers.
337          */
338         this.window.focus();
340         // Restore focus state
341         if (buffer.saved_focused_element)
342             set_focus_no_scroll(this.window, buffer.saved_focused_element);
343         else if (buffer.saved_focused_frame)
344             set_focus_no_scroll(this.window, buffer.saved_focused_frame);
346         buffer.saved_focused_element = null;
347         buffer.saved_focused_frame = null;
349         this.window.minibuffer.set_default_message(buffer.default_message);
350     },
352     get count () {
353         return this.container.childNodes.length;
354     },
356     get_buffer : function (index) {
357         if (index >= 0 && index < this.count)
358             return this.container.childNodes.item(index).conkeror_buffer_object;
359         return null;
360     },
362     get selected_index () {
363         var nodes = this.container.childNodes;
364         var count = nodes.length;
365         for (var i = 0; i < count; ++i)
366             if (nodes.item(i) == this.container.selectedPanel)
367                 return i;
368         return null;
369     },
371     index_of : function (b) {
372         var nodes = this.container.childNodes;
373         var count = nodes.length;
374         for (var i = 0; i < count; ++i)
375             if (nodes.item(i) == b.element)
376                 return i;
377         return null;
378     },
380     get unique_name_list () {
381         var existing_names = new string_hashset();
382         var bufs = [];
383         this.for_each(function(b) {
384                 var base_name = b.name;
385                 var name = base_name;
386                 var index = 1;
387                 while (existing_names.contains(name))
388                 {
389                     ++index;
390                     name = base_name + "<" + index + ">";
391                 }
392                 existing_names.add(name);
393                 bufs.push([name, b]);
394             });
395         return bufs;
396     },
398     kill_buffer : function (b) {
399         if (b.dead)
400             return true;
401         var count = this.count;
402         if (count <= 1)
403             return false;
404         var new_buffer = this.buffer_list[0];
405         var changed = false;
406         if (b == new_buffer) {
407             new_buffer = this.buffer_list[1];
408             changed = true;
409         }
410         this._switch_away_from(this.current);
411         // The removeChild call below may trigger events in progress
412         // listeners.  This call to `destroy' gives buffer subclasses a
413         // chance to remove such listeners, so that they cannot try to
414         // perform UI actions based upon a xul:browser that no longer
415         // exists.
416         b.destroy();
417         this.container.removeChild(b.element);
418         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
419         this._switch_to(new_buffer);
420         if (changed) {
421             select_buffer_hook.run(new_buffer);
422             this.buffer_list.splice(this.buffer_list.indexOf(new_buffer), 1);
423             this.buffer_list.unshift(new_buffer);
424         }
425         b.handle_kill();
426         return true;
427     },
429     bury_buffer : function(b) {
430       var new_buffer = this.buffer_list[0];
431       if (b == new_buffer) new_buffer = this.buffer_list[1];
432       this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
433       this.buffer_list.push(b);
434       this.current = new_buffer;
435       return true;
436     },
438     for_each : function (f) {
439         var count = this.count;
440         for (var i = 0; i < count; ++i)
441             f(this.get_buffer(i));
442     }
445 function buffer_initialize_window_early (window) {
446     /**
447      * Use content_buffer by default to handle an unusual case where
448      * browser.chromeURI is used perhaps.  In general this default
449      * should not be needed.
450      */
452     var create_initial_buffer
453         = window.args.initial_buffer_creator || buffer_creator(content_buffer);
454     new buffer_container(window, create_initial_buffer);
457 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
460 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
461 function buffer_before_window_close (window) {
462     var bs = window.buffers;
463     var count = bs.count;
464     for (let i = 0; i < count; ++i) {
465         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
466             return false;
467     }
468     return true;
470 add_hook("window_before_close_hook", buffer_before_window_close);
472 function buffer_window_close_handler (window) {
473     var bs = window.buffers;
474     var count = bs.count;
475     for (let i = 0; i < count; ++i) {
476         let b = bs.get_buffer(i);
477         b.handle_kill();
478     }
480 add_hook("window_close_hook", buffer_window_close_handler);
482 /* open/follow targets */
483 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
484                                // buffer is a content_buffer.
485 const OPEN_NEW_BUFFER = 1;
486 const OPEN_NEW_BUFFER_BACKGROUND = 2;
487 const OPEN_NEW_WINDOW = 3;
489 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
490 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
492 var TARGET_PROMPTS = [" in current buffer",
493                       " in new buffer",
494                       " in new buffer (background)",
495                       " in new window",
496                       "",
497                       " in current frame"];
499 var TARGET_NAMES = ["current buffer",
500                     "new buffer",
501                     "new buffer (background)",
502                     "new window",
503                     "default",
504                     "current frame"];
507 function create_buffer (window, creator, target) {
508     switch (target) {
509     case OPEN_NEW_BUFFER:
510         window.buffers.current = creator(window, null);
511         break;
512     case OPEN_NEW_BUFFER_BACKGROUND:
513         creator(window, null);
514         break;
515     case OPEN_NEW_WINDOW:
516         make_window(creator);
517         break;
518     default:
519         throw new Error("invalid target");
520     }
523 let (queued_buffer_creators = null) {
524     function create_buffer_in_current_window (creator, target, focus_existing) {
525         function process_queued_buffer_creators (window) {
526             for (var i = 0; i < queued_buffer_creators.length; ++i) {
527                 var x = queued_buffer_creators[i];
528                 create_buffer(window, x[0], x[1]);
529             }
530             queued_buffer_creators = null;
531         }
533         if (target == OPEN_NEW_WINDOW)
534             throw new Error("invalid target");
535         var window = get_recent_conkeror_window();
536         if (window) {
537             if (focus_existing)
538                 window.focus();
539             create_buffer(window, creator, target);
540         } else if (queued_buffer_creators != null) {
541             queued_buffer_creators.push([creator,target]);
542         } else {
543             queued_buffer_creators = [];
544             window = make_window(creator);
545             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
546         }
547     }
552  * Read Buffer
553  */
554 minibuffer_auto_complete_preferences["buffer"] = true;
555 define_keywords("$default");
556 minibuffer.prototype.read_buffer = function () {
557     var window = this.window;
558     var buffer = this.window.buffers.current;
559     keywords(arguments, $prompt = "Buffer:",
560              $default = buffer,
561              $history = "buffer");
562     var completer = all_word_completer(
563         $completions = function (visitor) window.buffers.for_each(visitor),
564         $get_string = function (x) x.description,
565         $get_description = function (x) x.title);
566     var result = yield this.read(
567         $keymap = read_buffer_keymap,
568         $prompt = arguments.$prompt,
569         $history = arguments.$history,
570         $completer = completer,
571         $match_required = true,
572         $auto_complete = "buffer",
573         $auto_complete_initial = true,
574         $auto_complete_delay = 0,
575         $default_completion = arguments.$default);
576     yield co_return(result);
580 interactive("buffer-reset-input-mode",
581     "Force a reset of the input mode.  Used by quote-next.",
582     function (I) {
583         I.buffer.set_input_mode();
584     });
587 function buffer_next (window, count) {
588     var index = window.buffers.selected_index;
589     var total = window.buffers.count;
590     if (total == 1)
591         throw new interactive_error("No other buffer");
592     index = (index + count) % total;
593     if (index < 0)
594         index += total;
595     window.buffers.current = window.buffers.get_buffer(index);
597 interactive("buffer-next",
598             "Switch to the next buffer.",
599             function (I) {buffer_next(I.window, I.p);});
600 interactive("buffer-previous",
601             "Switch to the previous buffer.",
602             function (I) {buffer_next(I.window, -I.p);});
604 function switch_to_buffer (window, buffer) {
605     if (buffer && !buffer.dead)
606         window.buffers.current = buffer;
608 interactive("switch-to-buffer",
609             "Switch to a buffer specified in the minibuffer.",
610             function (I) {
611                 switch_to_buffer(
612                     I.window,
613                     (yield I.minibuffer.read_buffer(
614                         $prompt = "Switch to buffer:",
615                         $default = (I.window.buffers.count > 1 ?
616                                     I.window.buffers.buffer_list[1] :
617                                     I.buffer))));
618             });
620 define_variable("can_kill_last_buffer", true,
621     "If this is set to true, kill-buffer can kill the last "+
622     "remaining buffer, and close the window.");
624 function kill_other_buffers (buffer) {
625     if (!buffer)
626         return;
627     var bs = buffer.window.buffers;
628     var b;
630     while ((b = bs.get_buffer(0)) != buffer)
631             bs.kill_buffer(b);
632     var count = bs.count;
633     while (--count)
634             bs.kill_buffer(bs.get_buffer(1));
636 interactive("kill-other-buffers",
637             "Kill all buffers except current one.\n",
638             function (I) { kill_other_buffers(I.buffer); });
641 function kill_buffer (buffer, force) {
642     if (!buffer)
643         return;
644     var buffers = buffer.window.buffers;
645     if (buffers.count == 1 && buffer == buffers.current) {
646         if (can_kill_last_buffer || force) {
647             delete_window(buffer.window);
648             return;
649         }
650         else
651             throw interactive_error("Can't kill last buffer.");
652     }
653     buffers.kill_buffer(buffer);
655 interactive("kill-buffer",
656             "Kill a buffer specified in the minibuffer.\n" +
657             "If `can_kill_last_buffer' is set to true, an attempt to kill the last remaining " +
658             "buffer in a window will cause the window to be closed.",
659             function (I) { kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:"))); });
661 interactive("kill-current-buffer",
662             "Kill the current buffer.\n" +
663             "If `can_kill_last_buffer' is set to true, an attempt to kill the last remaining " +
664             "buffer in a window will cause the window to be closed.",
665             function (I) { kill_buffer(I.buffer); });
667 interactive("read-buffer-kill-buffer",
668     "Kill the current selected buffer in the completions list "+
669     "in a read buffer minibuffer interaction.",
670     function (I) {
671         var s = I.window.minibuffer.current_state;
672         var i = s.selected_completion_index;
673         var c = s.completions;
674         if (i == -1)
675             return;
676         kill_buffer(c.get_value(i));
677         s.completer.refresh();
678         s.handle_input(I.window.minibuffer);
679     });
681 interactive("bury-buffer",
682             "Bury the current buffer.\n Put the current buffer at the end of " +
683             "the buffer list, so that it is the least likely buffer to be " +
684             "selected by `switch-to-buffer'.",
685             function (I) {I.window.buffers.bury_buffer(I.buffer);});
687 function change_directory (buffer, dir) {
688     if (buffer.page != null)
689         delete buffer.page.local.cwd;
690     buffer.local.cwd = make_file(dir);
692 interactive("change-directory",
693             "Change the current directory of the selected buffer.",
694             function (I) {
695                 change_directory(
696                     I.buffer,
697                     (yield I.minibuffer.read_existing_directory_path(
698                         $prompt = "Change to directory:",
699                         $initial_value = make_file(I.local.cwd).path)));
700             });
702 interactive("shell-command", null, function (I) {
703     var cwd = I.local.cwd;
704     var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
705     yield shell_command(cmd, $cwd = cwd);
710  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
711  * frames, iframes, plugins, and also clearing the selection.
712  */
713 define_buffer_local_hook("unfocus_hook");
714 function unfocus (window, buffer) {
715     // 1. if there is a selection, clear it.
716     var selc = getFocusedSelCtrl(buffer);
717     if (selc && selc.getSelection(selc.SELECTION_NORMAL).isCollapsed == false) {
718         clear_selection(buffer);
719         window.minibuffer.message("cleared selection");
720         return;
721     }
722     // 2. if there is a focused element, unfocus it.
723     if (buffer.focused_element) {
724         buffer.focused_element.blur();
725         // if an element in a detached fragment has focus, blur() will
726         // not work, and we need to take more drastic measures.  the
727         // action taken was found through experiment, so it is possibly
728         // not the most concise way to unfocus such an element.
729         if (buffer.focused_element) {
730             buffer.element.focus();
731             buffer.top_frame.focus();
732         }
733         window.minibuffer.message("unfocused element");
734         return;
735     }
736     // 3. return focus to top-frame from subframes and plugins.
737     buffer.top_frame.focus();
738     buffer.top_frame.focus(); // needed to get focus back from plugins
739     window.minibuffer.message("refocused top frame");
740     // give page-modes an opportunity to set focus specially
741     unfocus_hook.run(buffer);
743 interactive("unfocus",
744     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
745     "frames, iframes, plugins, and also for clearing the selection.  "+
746     "The action that it takes is based on precedence.  If there is a "+
747     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
748     "there is a selection, it will clear the selection.  Otherwise, it "+
749     "will return focus to the top frame from a focused frame, iframe, "+
750     "or plugin.  In the case of plugins, since they steal keyboard "+
751     "control away from Conkeror, the normal way to unfocus them is "+
752     "to use command-line remoting externally: conkeror -batch -f "+
753     "unfocus.  Page-modes also have an opportunity to alter the default"+
754     "focus via the hook, `focus_hook'.",
755     function (I) {
756         unfocus(I.window, I.buffer);
757     });
760 function for_each_buffer (f) {
761     for_each_window(function (w) { w.buffers.for_each(f); });
766  * BUFFER MODES
767  */
769 var mode_functions = {};
770 var mode_display_names = {};
772 define_buffer_local_hook("buffer_mode_change_hook");
773 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
775 define_keywords("$display_name", "$class", "$enable", "$disable", "$doc");
776 function define_buffer_mode (name) {
777     keywords(arguments);
779     var hyphen_name = name.replace("_","-","g");
780     var display_name = arguments.$display_name;
781     var mode_class = arguments.$class;
782     var enable = arguments.$enable;
783     var disable = arguments.$disable;
785     mode_display_names[name] = display_name;
787     var can_disable;
789     if (disable == false) {
790         can_disable = false;
791         disable = null;
792     } else
793         can_disable = true;
795     var state = (mode_class != null) ? mode_class : (name + "_enabled");
796     var enable_hook_name = name + "_enable_hook";
797     var disable_hook_name = name + "_disable_hook";
798     define_buffer_local_hook(enable_hook_name);
799     define_buffer_local_hook(disable_hook_name);
801     var change_hook_name = null;
803     if (mode_class) {
804         mode_functions[name] = {enable: enable,
805                                 disable: disable,
806                                 mode_class: mode_class,
807                                 disable_hook_name: disable_hook_name};
808         change_hook_name = mode_class + "_change_hook";
809         define_buffer_local_hook(change_hook_name);
810     }
812     function func (buffer, arg) {
813         var old_state = buffer[state];
814         var cur_state = (old_state == name);
815         var new_state = (arg == null) ? !cur_state : (arg > 0);
816         if ((new_state == cur_state) || (!can_disable && !new_state))
817             // perhaps show a message if (!can_disable && !new_state)
818             // to tell the user that this mode cannot be disabled.  do
819             // we have any existing modes that would benefit by it?
820             return null;
821         if (new_state) {
822             if (mode_class && old_state != null)  {
823                 // Another buffer-mode of our same mode-class is
824                 // enabled.  Buffer-modes within a mode-class are
825                 // mutually exclusive, so turn the old one off.
826                 buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(old_state), 1);
827                 let x = mode_functions[old_state];
828                 let y = x.disable;
829                 if (y) y(buffer);
830                 conkeror[x.disable_hook_name].run(buffer);
831             }
832             buffer[state] = name;
833             if (enable)
834                 enable(buffer);
835             conkeror[enable_hook_name].run(buffer);
836             buffer.enabled_modes.push(name);
837         } else {
838             buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(name), 1);
839             disable(buffer);
840             conkeror[disable_hook_name].run(buffer);
841             buffer[state] = null;
842         }
843         if (change_hook_name)
844             conkeror[change_hook_name].run(buffer, buffer[state]);
845         buffer_mode_change_hook.run(buffer);
846         return new_state;
847     }
849     conkeror[name] = func;
850     interactive(hyphen_name, arguments.$doc, function (I) {
851         var arg = I.P;
852         var new_state = func(I.buffer, arg && univ_arg_to_number(arg));
853         I.minibuffer.message(hyphen_name + (new_state ? " enabled" : " disabled"));
854     });
856 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
859 function minibuffer_mode_indicator (window) {
860     this.window = window;
861     var element = create_XUL(window, "label");
862     element.setAttribute("id", "minibuffer-mode-indicator");
863     element.collapsed = true;
864     element.setAttribute("class", "minibuffer");
865     window.document.getElementById("minibuffer").appendChild(element);
866     this.element = element;
867     this.hook_func = method_caller(this, this.update);
868     add_hook.call(window, "select_buffer_hook", this.hook_func);
869     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_func);
870     this.update();
872 minibuffer_mode_indicator.prototype = {
873     update : function () {
874         var buf = this.window.buffers.current;
875         var modes = buf.enabled_modes;
876         var str = modes.map( function (x) {
877             let y = mode_display_names[x];
878             if (y)
879                 return "[" + y + "]";
880             else
881                 return null;
882         } ).filter( function (x) x != null ).join(" ");
883         this.element.collapsed = (str.length == 0);
884         this.element.value = str;
885     },
886     uninstall : function () {
887         remove_hook.call(window, "select_buffer_hook", this.hook_fun);
888         remove_hook.call(window, "current_buffer_mode_change_hook", this.hook_fun);
889         this.element.parentNode.removeChild(this.element);
890     }
892 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
893 minibuffer_mode_indicator_mode(true);
898  * INPUT MODES
899  */
900 define_current_buffer_hook("current_buffer_input_mode_change_hook", "input_mode_change_hook");
901 define_keywords("$display_name", "$doc");
902 function define_input_mode (base_name, keymap_name) {
903     keywords(arguments);
904     var name = base_name + "_input_mode";
905     define_buffer_mode(name,
906                        $class = "input_mode",
907                        $enable = function (buffer) {
908                            check_buffer(buffer, content_buffer);
909                            buffer.keymaps.push(conkeror[keymap_name]);
910                        },
911                        $disable = function (buffer) {
912                            var i = buffer.keymaps.indexOf(conkeror[keymap_name]);
913                            if (i > -1)
914                                buffer.keymaps.splice(i, 1);
915                        },
916                        forward_keywords(arguments));
918 ignore_function_for_get_caller_source_code_reference("define_input_mode");
921 function minibuffer_input_mode_indicator (window) {
922     this.window = window;
923     this.hook_func = method_caller(this, this.update);
924     add_hook.call(window, "select_buffer_hook", this.hook_func);
925     add_hook.call(window, "current_buffer_input_mode_change_hook", this.hook_func);
926     this.update();
929 minibuffer_input_mode_indicator.prototype = {
930     update : function () {
931         var buf = this.window.buffers.current;
932         var mode = buf.input_mode;
933         var classname = mode ? ("minibuffer-" + buf.input_mode.replace("_","-","g")) : "";
934         this.window.minibuffer.element.className = classname;
935     },
936     uninstall : function () {
937         remove_hook.call(window, "select_buffer_hook", this.hook_func);
938         remove_hook.call(window, "current_buffer_input_mode_change_hook", this.hook_func);
939     }
942 define_global_window_mode("minibuffer_input_mode_indicator", "window_initialize_hook");
943 minibuffer_input_mode_indicator_mode(true);