Prepare new Debian package
[conkeror.git] / modules / buffer.js
blobce04ee1858ff38876deafab3ddc3577a15dba363
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,
160     mark_active: false,
162     // The property focusblocker is available for an external module to
163     // put a function on which takes a buffer as its argument and returns
164     // true to block a focus event, or false to let normal processing
165     // occur.  Having this one property explicitly handled by the buffer
166     // class allows for otherwise modular focus-blockers.
167     focusblocker: null,
169     default_message : "",
171     set_default_message : function (str) {
172         this.default_message = str;
173         if (this == this.window.buffers.current)
174             this.window.minibuffer.set_default_message(str);
175     },
177     constructors_running : 0,
179     constructor_begin : function () {
180         this.constructors_running++;
181     },
183     constructor_end : function () {
184         if (--this.constructors_running == 0) {
185             create_buffer_hook.run(this);
186             this.set_input_mode();
187             delete this.opener;
188         }
189     },
191     destroy: function () {},
193     set_input_mode: function () {
194         if (this.input_mode)
195             conkeror[this.input_mode](this, false);
196         this.keymaps = [];
197         this.modalities.map(function (m) m(this), this);
198     },
200     /* Browser accessors */
201     get top_frame () { return this.browser.contentWindow; },
202     get document () { return this.browser.contentDocument; },
203     get web_navigation () { return this.browser.webNavigation; },
204     get doc_shell () { return this.browser.docShell; },
205     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
206     get current_uri () { return this.browser.currentURI; },
208     is_child_element : function (element) {
209         return (element && this.is_child_frame(element.ownerDocument.defaultView));
210     },
212     is_child_frame : function (frame) {
213         return (frame && frame.top == this.top_frame);
214     },
216     // This method is like focused_frame, except that if no content
217     // frame actually has focus, this returns null.
218     get focused_frame_or_null () {
219         var frame = this.window.document.commandDispatcher.focusedWindow;
220         var top = this.top_frame;
221         if (this.is_child_frame(frame))
222             return frame;
223         return null;
224     },
226     get focused_frame () {
227         var frame = this.window.document.commandDispatcher.focusedWindow;
228         var top = this.top_frame;
229         if (this.is_child_frame(frame))
230             return frame;
231         return this.top_frame;
232     },
234     get focused_element () {
235         var element = this.window.document.commandDispatcher.focusedElement;
236         if (this.is_child_element(element))
237             return element;
238         return null;
239     },
241     do_command : function (command) {
242         function attempt_command (element, command) {
243             var controller;
244             if (element.controllers
245                 && (controller = element.controllers.getControllerForCommand(command)) != null
246                 && controller.isCommandEnabled(command))
247             {
248                 controller.doCommand(command);
249                 return true;
250             }
251             return false;
252         }
254         var element = this.focused_element;
255         if (element && attempt_command(element, command))
256             return;
257         var win = this.focused_frame;
258         do  {
259             if (attempt_command(win, command))
260                 return;
261             if (!win.parent || win == win.parent)
262                 break;
263             win = win.parent;
264         } while (true);
265     },
267     handle_kill : function () {
268         this.dead = true;
269         this.browser = null;
270         this.element = null;
271         this.saved_focused_frame = null;
272         this.saved_focused_element = null;
273         kill_buffer_hook.run(this);
274     }
277 function with_current_buffer (buffer, callback) {
278     return callback(new interactive_context(buffer));
281 function check_buffer (obj, type) {
282     if (!(obj instanceof type))
283         throw interactive_error("Buffer has invalid type.");
284     if (obj.dead)
285         throw interactive_error("Buffer has already been killed.");
286     return obj;
289 function buffer_container (window, create_initial_buffer) {
290     this.window = window;
291     this.container = window.document.getElementById("buffer-container");
292     this.buffer_list = [];
293     window.buffers = this;
295     create_initial_buffer(window, this.container.firstChild);
298 buffer_container.prototype = {
299     constructor : buffer_container,
301     get current () {
302         return this.container.selectedPanel.conkeror_buffer_object;
303     },
305     set current (buffer) {
306         var old_value = this.current;
307         if (old_value == buffer)
308             return;
310         this.buffer_list.splice(this.buffer_list.indexOf(buffer), 1);
311         this.buffer_list.unshift(buffer);
313         this._switch_away_from(this.current);
314         this._switch_to(buffer);
316         // Run hooks
317         select_buffer_hook.run(buffer);
318     },
320     _switch_away_from : function (old_value) {
321         // Save focus state
322         old_value.saved_focused_frame = old_value.focused_frame;
323         old_value.saved_focused_element = old_value.focused_element;
325         old_value.browser.setAttribute("type", "content");
326     },
328     _switch_to : function (buffer) {
329         // Select new buffer in the XUL deck
330         this.container.selectedPanel = buffer.element;
332         buffer.browser.setAttribute("type", "content-primary");
334         /**
335          * This next focus call seems to be needed to avoid focus
336          * somehow getting lost (and the keypress handler therefore
337          * not getting called at all) when killing buffers.
338          */
339         this.window.focus();
341         // Restore focus state
342         if (buffer.saved_focused_element)
343             set_focus_no_scroll(this.window, buffer.saved_focused_element);
344         else if (buffer.saved_focused_frame)
345             set_focus_no_scroll(this.window, buffer.saved_focused_frame);
347         buffer.saved_focused_element = null;
348         buffer.saved_focused_frame = null;
350         this.window.minibuffer.set_default_message(buffer.default_message);
351     },
353     get count () {
354         return this.container.childNodes.length;
355     },
357     get_buffer : function (index) {
358         if (index >= 0 && index < this.count)
359             return this.container.childNodes.item(index).conkeror_buffer_object;
360         return null;
361     },
363     get selected_index () {
364         var nodes = this.container.childNodes;
365         var count = nodes.length;
366         for (var i = 0; i < count; ++i)
367             if (nodes.item(i) == this.container.selectedPanel)
368                 return i;
369         return null;
370     },
372     index_of : function (b) {
373         var nodes = this.container.childNodes;
374         var count = nodes.length;
375         for (var i = 0; i < count; ++i)
376             if (nodes.item(i) == b.element)
377                 return i;
378         return null;
379     },
381     get unique_name_list () {
382         var existing_names = new string_hashset();
383         var bufs = [];
384         this.for_each(function(b) {
385                 var base_name = b.name;
386                 var name = base_name;
387                 var index = 1;
388                 while (existing_names.contains(name))
389                 {
390                     ++index;
391                     name = base_name + "<" + index + ">";
392                 }
393                 existing_names.add(name);
394                 bufs.push([name, b]);
395             });
396         return bufs;
397     },
399     kill_buffer : function (b) {
400         if (b.dead)
401             return true;
402         var count = this.count;
403         if (count <= 1)
404             return false;
405         var new_buffer = this.buffer_list[0];
406         var changed = false;
407         if (b == new_buffer) {
408             new_buffer = this.buffer_list[1];
409             changed = true;
410         }
411         this._switch_away_from(this.current);
412         // The removeChild call below may trigger events in progress
413         // listeners.  This call to `destroy' gives buffer subclasses a
414         // chance to remove such listeners, so that they cannot try to
415         // perform UI actions based upon a xul:browser that no longer
416         // exists.
417         b.destroy();
418         this.container.removeChild(b.element);
419         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
420         this._switch_to(new_buffer);
421         if (changed) {
422             select_buffer_hook.run(new_buffer);
423             this.buffer_list.splice(this.buffer_list.indexOf(new_buffer), 1);
424             this.buffer_list.unshift(new_buffer);
425         }
426         b.handle_kill();
427         return true;
428     },
430     bury_buffer : function(b) {
431       var new_buffer = this.buffer_list[0];
432       if (b == new_buffer) new_buffer = this.buffer_list[1];
433       this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
434       this.buffer_list.push(b);
435       this.current = new_buffer;
436       return true;
437     },
439     for_each : function (f) {
440         var count = this.count;
441         for (var i = 0; i < count; ++i)
442             f(this.get_buffer(i));
443     }
446 function buffer_initialize_window_early (window) {
447     /**
448      * Use content_buffer by default to handle an unusual case where
449      * browser.chromeURI is used perhaps.  In general this default
450      * should not be needed.
451      */
453     var create_initial_buffer
454         = window.args.initial_buffer_creator || buffer_creator(content_buffer);
455     new buffer_container(window, create_initial_buffer);
458 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
461 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
462 function buffer_before_window_close (window) {
463     var bs = window.buffers;
464     var count = bs.count;
465     for (let i = 0; i < count; ++i) {
466         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
467             return false;
468     }
469     return true;
471 add_hook("window_before_close_hook", buffer_before_window_close);
473 function buffer_window_close_handler (window) {
474     var bs = window.buffers;
475     var count = bs.count;
476     for (let i = 0; i < count; ++i) {
477         let b = bs.get_buffer(i);
478         b.handle_kill();
479     }
481 add_hook("window_close_hook", buffer_window_close_handler);
483 /* open/follow targets */
484 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
485                                // buffer is a content_buffer.
486 const OPEN_NEW_BUFFER = 1;
487 const OPEN_NEW_BUFFER_BACKGROUND = 2;
488 const OPEN_NEW_WINDOW = 3;
490 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
491 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
493 var TARGET_PROMPTS = [" in current buffer",
494                       " in new buffer",
495                       " in new buffer (background)",
496                       " in new window",
497                       "",
498                       " in current frame"];
500 var TARGET_NAMES = ["current buffer",
501                     "new buffer",
502                     "new buffer (background)",
503                     "new window",
504                     "default",
505                     "current frame"];
508 function create_buffer (window, creator, target) {
509     switch (target) {
510     case OPEN_NEW_BUFFER:
511         window.buffers.current = creator(window, null);
512         break;
513     case OPEN_NEW_BUFFER_BACKGROUND:
514         creator(window, null);
515         break;
516     case OPEN_NEW_WINDOW:
517         make_window(creator);
518         break;
519     default:
520         throw new Error("invalid target");
521     }
524 let (queued_buffer_creators = null) {
525     function create_buffer_in_current_window (creator, target, focus_existing) {
526         function process_queued_buffer_creators (window) {
527             for (var i = 0; i < queued_buffer_creators.length; ++i) {
528                 var x = queued_buffer_creators[i];
529                 create_buffer(window, x[0], x[1]);
530             }
531             queued_buffer_creators = null;
532         }
534         if (target == OPEN_NEW_WINDOW)
535             throw new Error("invalid target");
536         var window = get_recent_conkeror_window();
537         if (window) {
538             if (focus_existing)
539                 window.focus();
540             create_buffer(window, creator, target);
541         } else if (queued_buffer_creators != null) {
542             queued_buffer_creators.push([creator,target]);
543         } else {
544             queued_buffer_creators = [];
545             window = make_window(creator);
546             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
547         }
548     }
553  * Read Buffer
554  */
555 minibuffer_auto_complete_preferences["buffer"] = true;
556 define_keywords("$default");
557 minibuffer.prototype.read_buffer = function () {
558     var window = this.window;
559     var buffer = this.window.buffers.current;
560     keywords(arguments, $prompt = "Buffer:",
561              $default = buffer,
562              $history = "buffer");
563     var completer = all_word_completer(
564         $completions = function (visitor) window.buffers.for_each(visitor),
565         $get_string = function (x) x.description,
566         $get_description = function (x) x.title);
567     var result = yield this.read(
568         $keymap = read_buffer_keymap,
569         $prompt = arguments.$prompt,
570         $history = arguments.$history,
571         $completer = completer,
572         $match_required = true,
573         $auto_complete = "buffer",
574         $auto_complete_initial = true,
575         $auto_complete_delay = 0,
576         $default_completion = arguments.$default);
577     yield co_return(result);
581 interactive("buffer-reset-input-mode",
582     "Force a reset of the input mode.  Used by quote-next.",
583     function (I) {
584         I.buffer.set_input_mode();
585     });
588 function buffer_next (window, count) {
589     var index = window.buffers.selected_index;
590     var total = window.buffers.count;
591     if (total == 1)
592         throw new interactive_error("No other buffer");
593     index = (index + count) % total;
594     if (index < 0)
595         index += total;
596     window.buffers.current = window.buffers.get_buffer(index);
598 interactive("buffer-next",
599             "Switch to the next buffer.",
600             function (I) {buffer_next(I.window, I.p);});
601 interactive("buffer-previous",
602             "Switch to the previous buffer.",
603             function (I) {buffer_next(I.window, -I.p);});
605 function switch_to_buffer (window, buffer) {
606     if (buffer && !buffer.dead)
607         window.buffers.current = buffer;
609 interactive("switch-to-buffer",
610             "Switch to a buffer specified in the minibuffer.",
611             function (I) {
612                 switch_to_buffer(
613                     I.window,
614                     (yield I.minibuffer.read_buffer(
615                         $prompt = "Switch to buffer:",
616                         $default = (I.window.buffers.count > 1 ?
617                                     I.window.buffers.buffer_list[1] :
618                                     I.buffer))));
619             });
621 define_variable("can_kill_last_buffer", true,
622     "If this is set to true, kill-buffer can kill the last "+
623     "remaining buffer, and close the window.");
625 function kill_other_buffers (buffer) {
626     if (!buffer)
627         return;
628     var bs = buffer.window.buffers;
629     var b;
631     while ((b = bs.get_buffer(0)) != buffer)
632             bs.kill_buffer(b);
633     var count = bs.count;
634     while (--count)
635             bs.kill_buffer(bs.get_buffer(1));
637 interactive("kill-other-buffers",
638             "Kill all buffers except current one.\n",
639             function (I) { kill_other_buffers(I.buffer); });
642 function kill_buffer (buffer, force) {
643     if (!buffer)
644         return;
645     var buffers = buffer.window.buffers;
646     if (buffers.count == 1 && buffer == buffers.current) {
647         if (can_kill_last_buffer || force) {
648             delete_window(buffer.window);
649             return;
650         }
651         else
652             throw interactive_error("Can't kill last buffer.");
653     }
654     buffers.kill_buffer(buffer);
656 interactive("kill-buffer",
657             "Kill a buffer specified in the minibuffer.\n" +
658             "If `can_kill_last_buffer' is set to true, an attempt to kill the last remaining " +
659             "buffer in a window will cause the window to be closed.",
660             function (I) { kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:"))); });
662 interactive("kill-current-buffer",
663             "Kill the current buffer.\n" +
664             "If `can_kill_last_buffer' is set to true, an attempt to kill the last remaining " +
665             "buffer in a window will cause the window to be closed.",
666             function (I) { kill_buffer(I.buffer); });
668 interactive("read-buffer-kill-buffer",
669     "Kill the current selected buffer in the completions list "+
670     "in a read buffer minibuffer interaction.",
671     function (I) {
672         var s = I.window.minibuffer.current_state;
673         var i = s.selected_completion_index;
674         var c = s.completions;
675         if (i == -1)
676             return;
677         kill_buffer(c.get_value(i));
678         s.completer.refresh();
679         s.handle_input(I.window.minibuffer);
680     });
682 interactive("bury-buffer",
683             "Bury the current buffer.\n Put the current buffer at the end of " +
684             "the buffer list, so that it is the least likely buffer to be " +
685             "selected by `switch-to-buffer'.",
686             function (I) {I.window.buffers.bury_buffer(I.buffer);});
688 function change_directory (buffer, dir) {
689     if (buffer.page != null)
690         delete buffer.page.local.cwd;
691     buffer.local.cwd = make_file(dir);
693 interactive("change-directory",
694             "Change the current directory of the selected buffer.",
695             function (I) {
696                 change_directory(
697                     I.buffer,
698                     (yield I.minibuffer.read_existing_directory_path(
699                         $prompt = "Change to directory:",
700                         $initial_value = make_file(I.local.cwd).path)));
701             });
703 interactive("shell-command", null, function (I) {
704     var cwd = I.local.cwd;
705     var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
706     yield shell_command(cmd, $cwd = cwd);
711  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
712  * frames, iframes, plugins, and also clearing the selection.
713  */
714 define_buffer_local_hook("unfocus_hook");
715 function unfocus (window, buffer) {
716     // 1. if there is a selection, clear it.
717     var selc = getFocusedSelCtrl(buffer);
718     if (selc && selc.getSelection(selc.SELECTION_NORMAL).isCollapsed == false) {
719         clear_selection(buffer);
720         window.minibuffer.message("cleared selection");
721         return;
722     }
723     // 2. if there is a focused element, unfocus it.
724     if (buffer.focused_element) {
725         buffer.focused_element.blur();
726         // if an element in a detached fragment has focus, blur() will
727         // not work, and we need to take more drastic measures.  the
728         // action taken was found through experiment, so it is possibly
729         // not the most concise way to unfocus such an element.
730         if (buffer.focused_element) {
731             buffer.element.focus();
732             buffer.top_frame.focus();
733         }
734         window.minibuffer.message("unfocused element");
735         return;
736     }
737     // 3. return focus to top-frame from subframes and plugins.
738     buffer.top_frame.focus();
739     buffer.top_frame.focus(); // needed to get focus back from plugins
740     window.minibuffer.message("refocused top frame");
741     // give page-modes an opportunity to set focus specially
742     unfocus_hook.run(buffer);
744 interactive("unfocus",
745     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
746     "frames, iframes, plugins, and also for clearing the selection.  "+
747     "The action that it takes is based on precedence.  If there is a "+
748     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
749     "there is a selection, it will clear the selection.  Otherwise, it "+
750     "will return focus to the top frame from a focused frame, iframe, "+
751     "or plugin.  In the case of plugins, since they steal keyboard "+
752     "control away from Conkeror, the normal way to unfocus them is "+
753     "to use command-line remoting externally: conkeror -batch -f "+
754     "unfocus.  Page-modes also have an opportunity to alter the default"+
755     "focus via the hook, `focus_hook'.",
756     function (I) {
757         unfocus(I.window, I.buffer);
758     });
761 function for_each_buffer (f) {
762     for_each_window(function (w) { w.buffers.for_each(f); });
767  * BUFFER MODES
768  */
770 var mode_functions = {};
771 var mode_display_names = {};
773 define_buffer_local_hook("buffer_mode_change_hook");
774 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
776 define_keywords("$display_name", "$class", "$enable", "$disable", "$doc");
777 function define_buffer_mode (name) {
778     keywords(arguments);
780     var hyphen_name = name.replace("_","-","g");
781     var display_name = arguments.$display_name;
782     var mode_class = arguments.$class;
783     var enable = arguments.$enable;
784     var disable = arguments.$disable;
786     mode_display_names[name] = display_name;
788     var can_disable;
790     if (disable == false) {
791         can_disable = false;
792         disable = null;
793     } else
794         can_disable = true;
796     var state = (mode_class != null) ? mode_class : (name + "_enabled");
797     var enable_hook_name = name + "_enable_hook";
798     var disable_hook_name = name + "_disable_hook";
799     define_buffer_local_hook(enable_hook_name);
800     define_buffer_local_hook(disable_hook_name);
802     var change_hook_name = null;
804     if (mode_class) {
805         mode_functions[name] = {enable: enable,
806                                 disable: disable,
807                                 mode_class: mode_class,
808                                 disable_hook_name: disable_hook_name};
809         change_hook_name = mode_class + "_change_hook";
810         define_buffer_local_hook(change_hook_name);
811     }
813     function func (buffer, arg) {
814         var old_state = buffer[state];
815         var cur_state = (old_state == name);
816         var new_state = (arg == null) ? !cur_state : (arg > 0);
817         if ((new_state == cur_state) || (!can_disable && !new_state))
818             // perhaps show a message if (!can_disable && !new_state)
819             // to tell the user that this mode cannot be disabled.  do
820             // we have any existing modes that would benefit by it?
821             return null;
822         if (new_state) {
823             if (mode_class && old_state != null)  {
824                 // Another buffer-mode of our same mode-class is
825                 // enabled.  Buffer-modes within a mode-class are
826                 // mutually exclusive, so turn the old one off.
827                 buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(old_state), 1);
828                 let x = mode_functions[old_state];
829                 let y = x.disable;
830                 if (y) y(buffer);
831                 conkeror[x.disable_hook_name].run(buffer);
832             }
833             buffer[state] = name;
834             if (enable)
835                 enable(buffer);
836             conkeror[enable_hook_name].run(buffer);
837             buffer.enabled_modes.push(name);
838         } else {
839             buffer.enabled_modes.splice(buffer.enabled_modes.indexOf(name), 1);
840             disable(buffer);
841             conkeror[disable_hook_name].run(buffer);
842             buffer[state] = null;
843         }
844         if (change_hook_name)
845             conkeror[change_hook_name].run(buffer, buffer[state]);
846         buffer_mode_change_hook.run(buffer);
847         return new_state;
848     }
850     conkeror[name] = func;
851     interactive(hyphen_name, arguments.$doc, function (I) {
852         var arg = I.P;
853         var new_state = func(I.buffer, arg && univ_arg_to_number(arg));
854         I.minibuffer.message(hyphen_name + (new_state ? " enabled" : " disabled"));
855     });
857 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
860 function minibuffer_mode_indicator (window) {
861     this.window = window;
862     var element = create_XUL(window, "label");
863     element.setAttribute("id", "minibuffer-mode-indicator");
864     element.collapsed = true;
865     element.setAttribute("class", "minibuffer");
866     window.document.getElementById("minibuffer").appendChild(element);
867     this.element = element;
868     this.hook_func = method_caller(this, this.update);
869     add_hook.call(window, "select_buffer_hook", this.hook_func);
870     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_func);
871     this.update();
873 minibuffer_mode_indicator.prototype = {
874     update : function () {
875         var buf = this.window.buffers.current;
876         var modes = buf.enabled_modes;
877         var str = modes.map( function (x) {
878             let y = mode_display_names[x];
879             if (y)
880                 return "[" + y + "]";
881             else
882                 return null;
883         } ).filter( function (x) x != null ).join(" ");
884         this.element.collapsed = (str.length == 0);
885         this.element.value = str;
886     },
887     uninstall : function () {
888         remove_hook.call(window, "select_buffer_hook", this.hook_fun);
889         remove_hook.call(window, "current_buffer_mode_change_hook", this.hook_fun);
890         this.element.parentNode.removeChild(this.element);
891     }
893 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
894 minibuffer_mode_indicator_mode(true);
899  * INPUT MODES
900  */
901 define_current_buffer_hook("current_buffer_input_mode_change_hook", "input_mode_change_hook");
902 define_keywords("$display_name", "$doc");
903 function define_input_mode (base_name, keymap_name) {
904     keywords(arguments);
905     var name = base_name + "_input_mode";
906     define_buffer_mode(name,
907                        $class = "input_mode",
908                        $enable = function (buffer) {
909                            check_buffer(buffer, content_buffer);
910                            buffer.keymaps.push(conkeror[keymap_name]);
911                        },
912                        $disable = function (buffer) {
913                            var i = buffer.keymaps.indexOf(conkeror[keymap_name]);
914                            if (i > -1)
915                                buffer.keymaps.splice(i, 1);
916                        },
917                        forward_keywords(arguments));
919 ignore_function_for_get_caller_source_code_reference("define_input_mode");
922 function minibuffer_input_mode_indicator (window) {
923     this.window = window;
924     this.hook_func = method_caller(this, this.update);
925     add_hook.call(window, "select_buffer_hook", this.hook_func);
926     add_hook.call(window, "current_buffer_input_mode_change_hook", this.hook_func);
927     this.update();
930 minibuffer_input_mode_indicator.prototype = {
931     update : function () {
932         var buf = this.window.buffers.current;
933         var mode = buf.input_mode;
934         var classname = mode ? ("minibuffer-" + buf.input_mode.replace("_","-","g")) : "";
935         this.window.minibuffer.element.className = classname;
936     },
937     uninstall : function () {
938         remove_hook.call(window, "select_buffer_hook", this.hook_func);
939         remove_hook.call(window, "current_buffer_input_mode_change_hook", this.hook_func);
940     }
943 define_global_window_mode("minibuffer_input_mode_indicator", "window_initialize_hook");
944 minibuffer_input_mode_indicator_mode(true);