Debian package: consistently use "touch $@" for stamp files
[conkeror.git] / modules / buffer.js
blob73719d25c4f8dc4a85db0f4c713c6b6864f48c8e
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007-2012 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("buffer_icon_change_hook");
25 define_buffer_local_hook("select_buffer_hook");
26 define_buffer_local_hook("create_buffer_early_hook");
27 define_buffer_local_hook("create_buffer_late_hook");
28 define_buffer_local_hook("create_buffer_hook");
29 define_buffer_local_hook("kill_buffer_hook");
30 define_buffer_local_hook("move_buffer_hook");
31 define_buffer_local_hook("buffer_scroll_hook");
32 define_buffer_local_hook("buffer_dom_content_loaded_hook");
33 define_buffer_local_hook("buffer_loaded_hook");
34 define_buffer_local_hook("set_input_mode_hook");
35 define_buffer_local_hook("zoom_hook");
37 define_current_buffer_hook("current_buffer_title_change_hook", "buffer_title_change_hook");
38 define_current_buffer_hook("current_buffer_description_change_hook", "buffer_description_change_hook");
39 define_current_buffer_hook("current_buffer_icon_change_hook", "buffer_icon_change_hook");
40 define_current_buffer_hook("current_buffer_scroll_hook", "buffer_scroll_hook");
41 define_current_buffer_hook("current_buffer_dom_content_loaded_hook", "buffer_dom_content_loaded_hook");
42 define_current_buffer_hook("current_buffer_zoom_hook", "zoom_hook");
45 function buffer_position_before (container, b, i) {
46     return i;
49 function buffer_position_after (container, b, i) {
50     return i + 1;
53 function buffer_position_end (container, b, i) {
54     return container.count;
57 function buffer_position_end_by_type (container, b, i) {
58     // after last buffer of same type
59     var count = container.count;
60     var p = count - 1;
61     while (p >= 0 &&
62            container.get_buffer(p).constructor != b.constructor)
63     {
64         p--;
65     }
66     if (p == -1)
67         return count;
68     else
69         return p + 1;
72 define_variable("new_buffer_position", buffer_position_end,
73     "Used to compute the position in the buffer-list at which "+
74     "to insert new buffers which do not have an opener.  These "+
75     "include buffers created by typing an url or webjump, or "+
76     "buffers created via command-line remoting.  The value "+
77     "should be a number giving the index or a function of three "+
78     "arguments that returns the index at which to insert the "+
79     "new buffer.  The first argument is the buffer_container "+
80     "into which the new buffer is being inserted.  The second "+
81     "argument is the buffer to be inserted.  The third argument "+
82     "is the position of the currently selected buffer.  Several "+
83     "such functions are provided, including, buffer_position_before, "+
84     "buffer_position_after, buffer_position_end, and "+
85     "buffer_position_end_by_type.");
87 define_variable("new_buffer_with_opener_position", buffer_position_after,
88     "Used to compute the position in the buffer-list at which "+
89     "to insert new buffers which have an opener in the same "+
90     "window.  These include buffers created by following a link "+
91     "or frame, and contextual help buffers.  The allowed values "+
92     "are the same as those for `new_buffer_position', except that "+
93     "the second argument passed to the function is the index of "+
94     "the opener instead of the index of the current buffer (often "+
95     "one and the same).");
97 define_variable("bury_buffer_position", null,
98     "Used to compute the position in the buffer-list to move a "+
99     "buried buffer to.  A value of null prevents bury-buffer "+
100     "from moving the buffer at all.  Other allowed values are "+
101     "the same as those for `new_buffer_position', except that "+
102     "the second argument passed to the function is the index of "+
103     "the new buffer that will be selected after burying the "+
104     "current buffer.");
106 define_variable("allow_browser_window_close", true,
107     "If this is set to true, if a content buffer page calls " +
108     "window.close() from JavaScript and is not prevented by the " +
109     "normal Mozilla mechanism that restricts pages from closing " +
110     "a window that was not opened by a script, the buffer will be " +
111     "killed, deleting the window as well if it is the only buffer.");
113 define_keywords("$opener", "$position");
114 function buffer_creator (type) {
115     var args = forward_keywords(arguments);
116     return function (window) {
117         return new type(window, args);
118     };
121 function buffer_modality (buffer) {
122     buffer.keymaps.push(default_global_keymap);
125 function buffer (window) {
126     this.constructor_begin();
127     keywords(arguments, $position = this.default_position);
128     this.opener = arguments.$opener;
129     this.window = window;
130     var element = create_XUL(window, "vbox");
131     element.setAttribute("flex", "1");
132     var browser = create_XUL(window, "browser");
133     browser.setAttribute("type", "content");
134     browser.setAttribute("flex", "1");
135     browser.setAttribute("autocompletepopup", "popup_autocomplete");
136     element.appendChild(browser);
137     this.window.buffers.container.appendChild(element);
138     this.window.buffers.insert(this, arguments.$position, this.opener);
139     this.window.buffers.buffer_history.push(this);
140     this.element = element;
141     this.browser = element.firstChild;
142     this.element.conkeror_buffer_object = this;
144     this.local = { __proto__: conkeror };
145     this.page = null;
146     this.enabled_modes = [];
147     this.default_browser_object_classes = {};
149     var buffer = this;
151     this.browser.addEventListener("scroll", function (event) {
152             buffer_scroll_hook.run(buffer);
153         }, true /* capture */);
155     this.browser.addEventListener("DOMContentLoaded", function (event) {
156             buffer_dom_content_loaded_hook.run(buffer);
157         }, true /* capture */);
159     this.window.setTimeout(function () { create_buffer_late_hook.run(buffer); }, 0);
161     this.browser.addEventListener("load", function (event) {
162             if (event.target == buffer.document)
163                 buffer_loaded_hook.run(buffer);
164         }, true /* capture */);
166     this.browser.addEventListener("DOMWindowClose", function (event) {
167             /* This call to preventDefault is very important; without
168              * it, somehow Mozilla does something bad and as a result
169              * the window loses focus, causing keyboard commands to
170              * stop working. */
171             event.preventDefault();
173             if (allow_browser_window_close)
174                 kill_buffer(buffer, true);
175         }, true);
177     this.browser.addEventListener("focus", function (event) {
178         if (buffer.focusblocker &&
179             event.target instanceof Ci.nsIDOMHTMLElement &&
180             buffer.focusblocker(buffer, event))
181         {
182             event.target.blur();
183         } else
184             buffer.set_input_mode();
185     }, true);
187     this.browser.addEventListener("blur", function (event) {
188         buffer.set_input_mode();
189     }, true);
191     this.modalities = [buffer_modality];
193     // When create_buffer_early_hook runs, basic buffer properties
194     // will be available, but not the properties subclasses.
195     create_buffer_early_hook.run(this);
197     this.constructor_end();
199 buffer.prototype = {
200     constructor: buffer,
201     toString: function () "#<buffer>",
203     // default_position is the default value for the $position keyword to
204     // the buffer constructor.  This property can be set on the prototype
205     // of a subclass in order to override new_buffer_position and
206     // new_buffer_with_opener_position for specific types of buffers.
207     default_position: null,
209     /* Saved focus state */
210     saved_focused_frame: null,
211     saved_focused_element: null,
213     // get title ()   [must be defined by subclasses]
214     // get name ()    [must be defined by subclasses]
215     dead: false, /* This is set when the buffer is killed */
217     keymaps: null,
218     mark_active: false,
220     // The property focusblocker is available for an external module to
221     // put a function on which takes a buffer as its argument and returns
222     // true to block a focus event, or false to let normal processing
223     // occur.  Having this one property explicitly handled by the buffer
224     // class allows for otherwise modular focus-blockers.
225     focusblocker: null,
227     // icon is a string url of an icon to use for this buffer.  Setting it
228     // causes buffer_icon_change_hook to be run.
229     _icon: null,
230     get icon () this._icon,
231     set icon (x) {
232         if (this._icon != x) {
233             this._icon = x;
234             buffer_icon_change_hook.run(this);
235         }
236     },
238     default_message: "",
240     set_default_message: function (str) {
241         this.default_message = str;
242         if (this == this.window.buffers.current)
243             this.window.minibuffer.set_default_message(str);
244     },
246     constructors_running: 0,
248     constructor_begin: function () {
249         this.constructors_running++;
250     },
252     constructor_end: function () {
253         if (--this.constructors_running == 0) {
254             create_buffer_hook.run(this);
255             this.set_input_mode();
256             delete this.opener;
257         }
258     },
260     destroy: function () {
261         this.dead = true;
262         this.browser = null;
263         this.element = null;
264         this.saved_focused_frame = null;
265         this.saved_focused_element = null;
266         // prevent modalities from accessing dead browser
267         this.modalities = [];
268     },
270     set_input_mode: function () {
271         if (this != this.window.buffers.current)
272             return;
273         this.keymaps = [];
274         this.modalities.map(function (m) m(this), this);
275         set_input_mode_hook.run(this);
276     },
278     override_keymaps: function (keymaps) {
279         if (keymaps) {
280             this.keymaps = keymaps;
281             this.set_input_mode = function () {
282                 set_input_mode_hook.run(this);
283             };
284         } else
285             delete this.set_input_mode;
286         this.set_input_mode();
287     },
289     /* Browser accessors */
290     get top_frame () { return this.browser.contentWindow; },
291     get document () { return this.browser.contentDocument; },
292     get web_navigation () { return this.browser.webNavigation; },
293     get doc_shell () { return this.browser.docShell; },
294     get markup_document_viewer () { return this.browser.markupDocumentViewer; },
295     get current_uri () { return this.browser.currentURI; },
297     is_child_element: function (element) {
298         return (element && this.is_child_frame(element.ownerDocument.defaultView));
299     },
301     is_child_frame: function (frame) {
302         return (frame && frame.top == this.top_frame);
303     },
305     // This method is like focused_frame, except that if no content
306     // frame actually has focus, this returns null.
307     get focused_frame_or_null () {
308         var frame = this.window.document.commandDispatcher.focusedWindow;
309         if (this.is_child_frame(frame))
310             return frame;
311         return null;
312     },
314     get focused_frame () {
315         var frame = this.window.document.commandDispatcher.focusedWindow;
316         if (this.is_child_frame(frame))
317             return frame;
318         return this.top_frame;
319     },
321     get focused_element () {
322         var element = this.window.document.commandDispatcher.focusedElement;
323         if (this.is_child_element(element))
324             return element;
325         return null;
326     },
328     get focused_selection_controller () {
329         return this.focused_frame
330             .QueryInterface(Ci.nsIInterfaceRequestor)
331             .getInterface(Ci.nsIWebNavigation)
332             .QueryInterface(Ci.nsIInterfaceRequestor)
333             .getInterface(Ci.nsISelectionDisplay)
334             .QueryInterface(Ci.nsISelectionController);
335     },
337     do_command: function (command) {
338         function attempt_command (element, command) {
339             var controller;
340             if (element.controllers
341                 && (controller = element.controllers.getControllerForCommand(command)) != null
342                 && controller.isCommandEnabled(command))
343             {
344                 controller.doCommand(command);
345                 return true;
346             }
347             return false;
348         }
350         var element = this.focused_element;
351         if (element && attempt_command(element, command))
352             return;
353         var win = this.focused_frame;
354         while (true) {
355             if (attempt_command(win, command))
356                 return;
357             if (!win.parent || win == win.parent)
358                 break;
359             win = win.parent;
360         }
361     }
364 function with_current_buffer (buffer, callback) {
365     return callback(new interactive_context(buffer));
368 function check_buffer (obj, type) {
369     if (!(obj instanceof type))
370         throw interactive_error("Buffer has invalid type.");
371     if (obj.dead)
372         throw interactive_error("Buffer has already been killed.");
373     return obj;
376 function caret_enabled (buffer) {
377     return buffer.browser.getAttribute('showcaret');
380 function clear_selection (buffer) {
381     let sel_ctrl = buffer.focused_selection_controller;
382     if (sel_ctrl) {
383         let sel = sel_ctrl.getSelection(sel_ctrl.SELECTION_NORMAL);
384         if (caret_enabled(buffer)) {
385             if (sel.anchorNode)
386                 sel.collapseToStart();
387         } else {
388             sel.removeAllRanges();
389         }
390     }
394 function buffer_container (window, create_initial_buffer) {
395     this.window = window;
396     this.container = window.document.getElementById("buffer-container");
397     this.buffer_list = [];
398     this.buffer_history = [];
399     window.buffers = this;
400     create_initial_buffer(window);
402 buffer_container.prototype = {
403     constructor: buffer_container,
404     toString: function () "#<buffer_container>",
406     insert: function (buffer, position, opener) {
407         var i = this.index_of(opener);
408         if (position == null) {
409             if (i == null)
410                 position = new_buffer_position;
411             else
412                 position = new_buffer_with_opener_position;
413         }
414         if (i == null)
415             i = this.selected_index || 0;
416         try {
417             if (position instanceof Function)
418                 var p = position(this, buffer, i);
419             else
420                 p = position;
421             this.buffer_list.splice(p, 0, buffer);
422         } catch (e) {
423             this.buffer_list.splice(0, 0, buffer);
424             dumpln("Error inserting buffer, inserted at 0.");
425             dump_error(e);
426         }
427     },
429     get current () {
430         return this.container.selectedPanel.conkeror_buffer_object;
431     },
433     set current (buffer) {
434         var old_value = this.current;
435         if (old_value == buffer)
436             return;
438         this.buffer_history.splice(this.buffer_history.indexOf(buffer), 1);
439         this.buffer_history.unshift(buffer);
441         this._switch_away_from(this.current);
442         this._switch_to(buffer);
444         // Run hooks
445         select_buffer_hook.run(buffer);
446     },
448     _switch_away_from: function (old_value) {
449         // Save focus state
450         old_value.saved_focused_frame = old_value.focused_frame;
451         old_value.saved_focused_element = old_value.focused_element;
453         if ('isActive' in old_value.browser.docShell)
454             old_value.browser.docShell.isActive = false;
455         old_value.browser.setAttribute("type", "content");
456     },
458     _switch_to: function (buffer) {
459         // Select new buffer in the XUL deck
460         this.container.selectedPanel = buffer.element;
462         buffer.browser.setAttribute("type", "content-primary");
463         if ('isActive' in buffer.browser.docShell)
464             buffer.browser.docShell.isActive = true;
466         /**
467          * This next focus call seems to be needed to avoid focus
468          * somehow getting lost (and the keypress handler therefore
469          * not getting called at all) when killing buffers.
470          */
471         this.window.focus();
473         // Restore focus state
474         buffer.browser.focus();
475         if (buffer.saved_focused_element)
476             set_focus_no_scroll(this.window, buffer.saved_focused_element);
477         else if (buffer.saved_focused_frame)
478             set_focus_no_scroll(this.window, buffer.saved_focused_frame);
480         buffer.saved_focused_element = null;
481         buffer.saved_focused_frame = null;
483         buffer.set_input_mode();
485         this.window.minibuffer.set_default_message(buffer.default_message);
486     },
488     get count () {
489         return this.buffer_list.length;
490     },
492     get_buffer: function (index) {
493         if (index >= 0 && index < this.count)
494             return this.buffer_list[index]
495         return null;
496     },
498     get selected_index () {
499         var nodes = this.buffer_list;
500         var count = nodes.length;
501         for (var i = 0; i < count; ++i)
502             if (nodes[i] == this.container.selectedPanel.conkeror_buffer_object)
503                 return i;
504         return null;
505     },
507     index_of: function (b) {
508         var nodes = this.buffer_list;
509         var count = nodes.length;
510         for (var i = 0; i < count; ++i)
511             if (nodes[i] == b)
512                 return i;
513         return null;
514     },
516     get unique_name_list () {
517         var existing_names = {};
518         var bufs = [];
519         this.for_each(function(b) {
520                 var base_name = b.name;
521                 var name = base_name;
522                 var index = 1;
523                 while (existing_names[name]) {
524                     ++index;
525                     name = base_name + "<" + index + ">";
526                 }
527                 existing_names[name] = true;
528                 bufs.push([name, b]);
529             });
530         return bufs;
531     },
533     kill_buffer: function (b) {
534         if (b.dead)
535             return true;
536         var count = this.count;
537         if (count <= 1)
538             return false;
539         var new_buffer = this.buffer_history[0];
540         var changed = false;
541         if (b == new_buffer) {
542             new_buffer = this.buffer_history[1];
543             changed = true;
544         }
545         this._switch_away_from(this.current);
546         // The removeChild call below may trigger events in progress
547         // listeners.  This call to `destroy' gives buffer subclasses a
548         // chance to remove such listeners, so that they cannot try to
549         // perform UI actions based upon a xul:browser that no longer
550         // exists.
551         var element = b.element;
552         b.destroy();
553         this.container.removeChild(element);
554         this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
555         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
556         this._switch_to(new_buffer);
557         if (changed) {
558             select_buffer_hook.run(new_buffer);
559             this.buffer_history.splice(this.buffer_history.indexOf(new_buffer), 1);
560             this.buffer_history.unshift(new_buffer);
561         }
562         kill_buffer_hook.run(b);
563         return true;
564     },
566     bury_buffer: function (b) {
567         var new_buffer = this.buffer_history[0];
568         if (b == new_buffer)
569             new_buffer = this.buffer_history[1];
570         if (! new_buffer)
571             throw interactive_error("No other buffer");
572         if (bury_buffer_position != null) {
573             this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
574             this.insert(b, bury_buffer_position, new_buffer);
575         }
576         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
577         this.buffer_history.push(b);
578         this.current = new_buffer;
579         if (bury_buffer_position != null)
580             move_buffer_hook.run(b);
581         return true;
582     },
584     unbury_buffer: function (b) {
585         var c = this.current;
586         if (bury_buffer_position != null) {
587             this.buffer_list.splice(this.buffer_list.indexOf(b), 1);
588             this.buffer_list.splice(this.buffer_list.indexOf(c), 0, b);
589         }
590         this.buffer_history.splice(this.buffer_history.indexOf(b), 1);
591         this.buffer_history.unshift(b);
592         this.current = b;
593         if (bury_buffer_position != null)
594             move_buffer_hook.run(b);
595         return true;
596     },
598     for_each: function (f) {
599         var count = this.count;
600         for (var i = 0; i < count; ++i)
601             f(this.get_buffer(i));
602     }
605 function buffer_initialize_window_early (window) {
606     /**
607      * Use content_buffer by default to handle an unusual case where
608      * browser.chromeURI is used perhaps.  In general this default
609      * should not be needed.
610      */
611     var create_initial_buffer =
612         window.args.initial_buffer_creator || buffer_creator(content_buffer);
613     new buffer_container(window, create_initial_buffer);
616 add_hook("window_initialize_early_hook", buffer_initialize_window_early);
620  * initialize_first_buffer_type is a workaround for a XULRunner bug that
621  * first appeared in version 2.0, manifested as missing scrollbars in the
622  * first buffer of any window.  It only affects content-primary browsers,
623  * and the workaround is to initialize the browser as type "content" then
624  * change it to content-primary after a delay.
625  */
626 function initialize_first_buffer_type (window) {
627     window.buffers.current.browser.setAttribute("type", "content-primary");
630 add_hook("window_initialize_late_hook", initialize_first_buffer_type);
633 define_buffer_local_hook("buffer_kill_before_hook", RUN_HOOK_UNTIL_FAILURE);
634 function buffer_before_window_close (window) {
635     var bs = window.buffers;
636     var count = bs.count;
637     for (let i = 0; i < count; ++i) {
638         if (!buffer_kill_before_hook.run(bs.get_buffer(i)))
639             return false;
640     }
641     return true;
643 add_hook("window_before_close_hook", buffer_before_window_close);
645 function buffer_window_close_handler (window) {
646     var bs = window.buffers;
647     var count = bs.count;
648     for (let i = 0; i < count; ++i) {
649         let b = bs.get_buffer(i);
650         b.destroy();
651     }
653 add_hook("window_close_hook", buffer_window_close_handler);
655 /* open/follow targets */
656 const OPEN_CURRENT_BUFFER = 0; // only valid for open if the current
657                                // buffer is a content_buffer.
658 const OPEN_NEW_BUFFER = 1;
659 const OPEN_NEW_BUFFER_BACKGROUND = 2;
660 const OPEN_NEW_WINDOW = 3;
662 const FOLLOW_DEFAULT = 4; // for open, implies OPEN_CURRENT_BUFFER
663 const FOLLOW_CURRENT_FRAME = 5; // for open, implies OPEN_CURRENT_BUFFER
665 var TARGET_PROMPTS = [" in current buffer",
666                       " in new buffer",
667                       " in new buffer (background)",
668                       " in new window",
669                       "",
670                       " in current frame"];
672 var TARGET_NAMES = ["current buffer",
673                     "new buffer",
674                     "new buffer (background)",
675                     "new window",
676                     "default",
677                     "current frame"];
680 function create_buffer (window, creator, target) {
681     switch (target) {
682     case OPEN_NEW_BUFFER:
683         window.buffers.current = creator(window, null);
684         break;
685     case OPEN_NEW_BUFFER_BACKGROUND:
686         creator(window, null);
687         break;
688     case OPEN_NEW_WINDOW:
689         make_window(creator);
690         break;
691     default:
692         throw new Error("invalid target");
693     }
696 let (queued_buffer_creators = null) {
697     function create_buffer_in_current_window (creator, target, focus_existing) {
698         function process_queued_buffer_creators (window) {
699             for (var i = 0; i < queued_buffer_creators.length; ++i) {
700                 var x = queued_buffer_creators[i];
701                 create_buffer(window, x[0], x[1]);
702             }
703             queued_buffer_creators = null;
704         }
706         if (target == OPEN_NEW_WINDOW)
707             throw new Error("invalid target");
708         var window = get_recent_conkeror_window();
709         if (window) {
710             if (focus_existing)
711                 window.focus();
712             create_buffer(window, creator, target);
713         } else if (queued_buffer_creators != null) {
714             queued_buffer_creators.push([creator,target]);
715         } else {
716             queued_buffer_creators = [];
717             window = make_window(creator);
718             add_hook.call(window, "window_initialize_late_hook", process_queued_buffer_creators);
719         }
720     }
725  * Read Buffer
726  */
727 define_variable("read_buffer_show_icons", false,
728     "Boolean which says whether read_buffer should show buffer "+
729     "icons in the completions list.\nNote, setting this variable "+
730     "alone does not cause favicons or other kinds of icons to be "+
731     "fetched.  For that, load the `favicon' (or similar other) "+
732     "library.");
734 minibuffer_auto_complete_preferences["buffer"] = true;
735 define_keywords("$buffers", "$default");
736 minibuffer.prototype.read_buffer = function () {
737     var window = this.window;
738     keywords(arguments, $prompt = "Buffer:",
739              $buffers = function (visitor) window.buffers.for_each(visitor),
740              $default = window.buffers.current,
741              $history = "buffer");
742     var completer = all_word_completer(
743         $completions = arguments.$buffers,
744         $get_string = function (x) x.description,
745         $get_description = function (x) x.title,
746         $get_icon = (read_buffer_show_icons ?
747                      function (x) x.icon : null));
748     var result = yield this.read(
749         $keymap = read_buffer_keymap,
750         $prompt = arguments.$prompt,
751         $history = arguments.$history,
752         $completer = completer,
753         $enable_icons = read_buffer_show_icons,
754         $match_required = true,
755         $auto_complete = "buffer",
756         $auto_complete_initial = true,
757         $auto_complete_delay = 0,
758         $default_completion = arguments.$default);
759     yield co_return(result);
763 function buffer_move_forward (window, count) {
764     var buffers = window.buffers;
765     var index = buffers.selected_index;
766     var buffer = buffers.current
767     var total = buffers.count;
768     if (total == 1)
769         return;
770     var new_index = (index + count) % total;
771     if (new_index == index)
772         return;
773     if (new_index < 0)
774         new_index += total;
775     buffers.buffer_list.splice(index, 1);
776     buffers.buffer_list.splice(new_index, 0, buffer);
777     move_buffer_hook.run(buffer);
779 interactive("buffer-move-forward",
780     "Move the current buffer forward in the buffer order.",
781     function (I) { buffer_move_forward(I.window, I.p); });
783 interactive("buffer-move-backward",
784     "Move the current buffer backward in the buffer order.",
785     function (I) { buffer_move_forward(I.window, -I.p); });
788 function buffer_next (window, count) {
789     var index = window.buffers.selected_index;
790     var total = window.buffers.count;
791     if (total == 1)
792         throw new interactive_error("No other buffer");
793     index = (index + count) % total;
794     if (index < 0)
795         index += total;
796     window.buffers.current = window.buffers.get_buffer(index);
798 interactive("buffer-next",
799     "Switch to the next buffer.",
800     function (I) { buffer_next(I.window, I.p); });
801 interactive("buffer-previous",
802     "Switch to the previous buffer.",
803     function (I) { buffer_next(I.window, -I.p); });
805 function switch_to_buffer (window, buffer) {
806     if (buffer && !buffer.dead)
807         window.buffers.current = buffer;
809 interactive("switch-to-buffer",
810     "Prompt for a buffer and switch to it.",
811     function (I) {
812         switch_to_buffer(
813             I.window,
814             (yield I.minibuffer.read_buffer(
815                 $prompt = "Switch to buffer:",
816                 $default = (I.window.buffers.count > 1 ?
817                             I.window.buffers.buffer_history[1] :
818                             I.buffer))));
819     });
821 define_variable("can_kill_last_buffer", true,
822     "When true, kill-buffer can kill the last  buffer in a window, "+
823     "and close the window.");
825 function kill_other_buffers (buffer) {
826     if (!buffer)
827         return;
828     var bs = buffer.window.buffers;
829     var b;
830     while ((b = bs.get_buffer(0)) != buffer)
831         bs.kill_buffer(b);
832     var count = bs.count;
833     while (--count)
834         bs.kill_buffer(bs.get_buffer(1));
836 interactive("kill-other-buffers",
837     "Kill all buffers except current one.\n",
838     function (I) { kill_other_buffers(I.buffer); });
841 function kill_buffer (buffer, force) {
842     if (!buffer)
843         return;
844     var buffers = buffer.window.buffers;
845     if (buffers.count == 1 && buffer == buffers.current) {
846         if (can_kill_last_buffer || force) {
847             delete_window(buffer.window);
848             return;
849         } else
850             throw interactive_error("Can't kill last buffer.");
851     }
852     buffers.kill_buffer(buffer);
854 interactive("kill-buffer",
855     "Kill a buffer specified in the minibuffer.\n" +
856     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
857     "last remaining buffer in a window will cause the window to be closed.",
858     function (I) {
859         kill_buffer((yield I.minibuffer.read_buffer($prompt = "Kill buffer:")));
860     });
862 interactive("kill-current-buffer",
863     "Kill the current buffer.\n" +
864     "If `can_kill_last_buffer' is set to true, an attempt to kill the "+
865     "last remaining buffer in a window will cause the window to be closed.",
866     function (I) { kill_buffer(I.buffer); });
868 interactive("read-buffer-kill-buffer",
869     "Kill the current selected buffer in the completions list "+
870     "in a read buffer minibuffer interaction.",
871     function (I) {
872         var s = I.window.minibuffer.current_state;
873         var i = s.selected_completion_index;
874         var c = s.completions;
875         if (i == -1)
876             return;
877         kill_buffer(c.get_value(i));
878         s.completer.refresh();
879         s.handle_input(I.window.minibuffer);
880     });
882 interactive("bury-buffer",
883     "Bury the current buffer.\nPut the current buffer at the end of " +
884     "the buffer list, so that it is the least likely buffer to be " +
885     "selected by `switch-to-buffer'.",
886     function (I) { I.window.buffers.bury_buffer(I.buffer); });
888 interactive("unbury-buffer",
889     "Unbury the buffer lowest in the buffer-history list.\n"+
890     "With universal argument, prompt for a buffer.  When "+
891     "`bury_buffer_position` is non-null, move the buffer "+
892     "to the current position in the buffer list.",
893     function (I) {
894         var buffers = I.window.buffers;
895         if (I.prefix_argument)
896             var b = yield I.minibuffer.read_buffer(
897                 $prompt = "Switch to buffer:",
898                 $buffers = function (visitor) {
899                     var count = buffers.count;
900                     for (var i = count - 1; i >= 0; --i)
901                         visitor(buffers.buffer_history[i]);
902                 },
903                 $default = buffers.buffer_history[buffers.count - 1]);
904         else
905             b = buffers.buffer_history[buffers.count - 1];
906         buffers.unbury_buffer(b);
907     });
909 function change_directory (buffer, dir) {
910     if (buffer.page != null)
911         delete buffer.page.local.cwd;
912     buffer.local.cwd = make_file(dir);
914 interactive("change-directory",
915     "Change the current directory of the selected buffer.",
916     function (I) {
917         change_directory(
918             I.buffer,
919             (yield I.minibuffer.read_existing_directory_path(
920                 $prompt = "Change to directory:",
921                 $initial_value = make_file(I.local.cwd).path)));
922     });
924 interactive("shell-command", null,
925     function (I) {
926         var cwd = I.local.cwd;
927         var cmd = (yield I.minibuffer.read_shell_command($cwd = cwd));
928         yield shell_command(cmd, $cwd = cwd);
929     });
933  * selection_is_embed_p is used to test whether the unfocus command can
934  * unfocus an element, even though there is a selection.  This happens
935  * when the focused element is an html:embed.
936  */
937 function selection_is_embed_p (sel, focused_element) {
938     if (sel.rangeCount == 1) {
939         try {
940             var r = sel.getRangeAt(0);
941             var a = r.startContainer.childNodes[r.startOffset];
942             if ((a instanceof Ci.nsIDOMHTMLEmbedElement ||
943                  a instanceof Ci.nsIDOMHTMLObjectElement) &&
944                 a == focused_element)
945             {
946                 return true;
947             }
948         } catch (e) {}
949     }
950     return false;
954  * unfocus is a high-level command for unfocusing hyperlinks, inputs,
955  * frames, iframes, plugins, and also clearing the selection.
956  */
957 define_buffer_local_hook("unfocus_hook");
958 function unfocus (window, buffer) {
959     // 1. if there is a selection, clear it.
960     var selc = buffer.focused_selection_controller;
961     if (selc) {
962         var sel = selc.getSelection(selc.SELECTION_NORMAL);
963         var active = ! sel.isCollapsed;
964         var embed_p = selection_is_embed_p(sel, buffer.focused_element);
965         clear_selection(buffer);
966         if (active && !embed_p) {
967             window.minibuffer.message("cleared selection");
968             return;
969         }
970     }
971     // 2. if there is a focused element, unfocus it.
972     if (buffer.focused_element) {
973         buffer.focused_element.blur();
974         // if an element in a detached fragment has focus, blur() will
975         // not work, and we need to take more drastic measures.  the
976         // action taken was found through experiment, so it is possibly
977         // not the most concise way to unfocus such an element.
978         if (buffer.focused_element) {
979             buffer.element.focus();
980             buffer.top_frame.focus();
981         }
982         window.minibuffer.message("unfocused element");
983         return;
984     }
985     // 3. if an iframe has focus, we must blur it.
986     if (buffer.focused_frame_or_null &&
987         buffer.focused_frame_or_null.frameElement)
988     {
989         buffer.focused_frame_or_null.frameElement.blur();
990     }
991     // 4. return focus to top-frame from subframes and plugins.
992     buffer.top_frame.focus();
993     buffer.top_frame.focus(); // needed to get focus back from plugins
994     window.minibuffer.message("refocused top frame");
995     // give page-modes an opportunity to set focus specially
996     unfocus_hook.run(buffer);
998 interactive("unfocus",
999     "Unfocus is a high-level command for unfocusing hyperlinks, inputs, "+
1000     "frames, iframes, plugins, and also for clearing the selection.\n"+
1001     "The action that it takes is based on precedence.  If there is a "+
1002     "focused hyperlink or input, it will unfocus that.  Otherwise, if "+
1003     "there is a selection, it will clear the selection.  Otherwise, it "+
1004     "will return focus to the top frame from a focused frame, iframe, "+
1005     "or plugin.  In the case of plugins, since they steal keyboard "+
1006     "control away from Conkeror, the normal way to unfocus them is "+
1007     "to use command-line remoting externally: conkeror -batch -f "+
1008     "unfocus.  Page-modes also have an opportunity to alter the default"+
1009     "focus via the hook, `focus_hook'.",
1010     function (I) {
1011         unfocus(I.window, I.buffer);
1012     });
1015 function for_each_buffer (f) {
1016     for_each_window(function (w) { w.buffers.for_each(f); });
1021  * Buffer Modes
1022  */
1024 define_buffer_local_hook("buffer_mode_change_hook");
1025 define_current_buffer_hook("current_buffer_mode_change_hook", "buffer_mode_change_hook");
1027 define_keywords("$display_name", "$doc");
1028 function buffer_mode (name, enable, disable) {
1029     keywords(arguments);
1030     this.name = name.replace("-","_","g");
1031     this.hyphen_name = name.replace("_","-","g");
1032     if (enable)
1033         this._enable = enable;
1034     if (disable)
1035         this._disable = disable;
1036     this.display_name = arguments.$display_name;
1037     this.doc = arguments.$doc;
1038     this.enable_hook = this.name + "_enable_hook";
1039     this.disable_hook = this.name + "_disable_hook";
1041 buffer_mode.prototype = {
1042     constructor: buffer_mode,
1043     name: null,
1044     display_name: null,
1045     doc: null,
1046     enable_hook: null,
1047     disable_hook: null,
1048     _enable: null,
1049     _disable: null,
1050     enable: function (buffer) {
1051         try {
1052             if (this._enable)
1053                 this._enable(buffer);
1054         } finally {
1055             buffer.enabled_modes.push(this.name);
1056             if (conkeror[this.enable_hook])
1057                 conkeror[this.enable_hook].run(buffer);
1058             buffer_mode_change_hook.run(buffer);
1059         }
1060     },
1061     disable: function (buffer) {
1062         try {
1063             if (this._disable)
1064                 this._disable(buffer);
1065         } finally {
1066             var i = buffer.enabled_modes.indexOf(this.name);
1067             if (i > -1)
1068                 buffer.enabled_modes.splice(i, 1);
1069             if (conkeror[this.disable_hook])
1070                 conkeror[this.disable_hook].run(buffer);
1071             buffer_mode_change_hook.run(buffer);
1072         }
1073     }
1075 define_keywords("$constructor");
1076 function define_buffer_mode (name, enable, disable) {
1077     keywords(arguments, $constructor = buffer_mode, $doc = null);
1078     var constructor = arguments.$constructor;
1079     var m = new constructor(name, enable, disable, forward_keywords(arguments));
1080     name = m.name; // normalized
1081     conkeror[name] = m;
1082     define_buffer_local_hook(m.enable_hook);
1083     define_buffer_local_hook(m.disable_hook);
1084     interactive(m.hyphen_name,
1085         arguments.$doc,
1086         function (I) {
1087             var enabledp = (I.buffer.enabled_modes.indexOf(name) > -1);
1088             if (enabledp)
1089                 m.disable(I.buffer);
1090             else
1091                 m.enable(I.buffer);
1092             I.minibuffer.message(m.hyphen_name + (enabledp ? " disabled" : " enabled"));
1093         });
1095 ignore_function_for_get_caller_source_code_reference("define_buffer_mode");
1099  * Mode Display in Minibuffer
1100  */
1102 function minibuffer_mode_indicator (window) {
1103     this.window = window;
1104     var element = create_XUL(window, "label");
1105     element.setAttribute("id", "minibuffer-mode-indicator");
1106     element.setAttribute("class", "mode-text-widget");
1107     window.document.getElementById("minibuffer").appendChild(element);
1108     this.element = element;
1109     this.hook_function = method_caller(this, this.update);
1110     add_hook.call(window, "select_buffer_hook", this.hook_function);
1111     add_hook.call(window, "current_buffer_mode_change_hook", this.hook_function);
1112     this.update();
1114 minibuffer_mode_indicator.prototype = {
1115     constructor: minibuffer_mode_indicator,
1116     window: null,
1117     element: null,
1118     hook_function: null,
1119     update: function () {
1120         var buffer = this.window.buffers.current;
1121         var str = buffer.enabled_modes.map(
1122             function (x) {
1123                 return (conkeror[x].display_name || null);
1124             }).filter(function (x) x != null).join(" ");
1125         this.element.value = str;
1126     },
1127     uninstall: function () {
1128         remove_hook.call(this.window, "select_buffer_hook", this.hook_function);
1129         remove_hook.call(this.window, "current_buffer_mode_change_hook", this.hook_function);
1130         this.element.parentNode.removeChild(this.element);
1131     }
1133 define_global_window_mode("minibuffer_mode_indicator", "window_initialize_hook");
1134 minibuffer_mode_indicator_mode(true);
1138  * minibuffer-keymaps-display
1139  */
1140 function minibuffer_keymaps_display_update (buffer) {
1141     var element = buffer.window.document
1142         .getElementById("keymaps-display");
1143     if (element) {
1144         var str = buffer.keymaps.reduce(
1145             function (acc, kmap) {
1146                 if (kmap.display_name)
1147                     acc.push(kmap.display_name);
1148                 return acc;
1149             }, []).join("/");
1150         if (element.value != str)
1151             element.value = str;
1152     }
1155 function minibuffer_keymaps_display_initialize (window) {
1156     var element = create_XUL(window, "label");
1157     element.setAttribute("id", "keymaps-display");
1158     element.setAttribute("class", "mode-text-widget");
1159     element.setAttribute("value", "");
1160     var mb = window.document.getElementById("minibuffer");
1161     mb.appendChild(element);
1164 define_global_mode("minibuffer_keymaps_display_mode",
1165     function enable () {
1166         add_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1167         add_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1168         for_each_window(minibuffer_keymaps_display_initialize);
1169     },
1170     function disable () {
1171         remove_hook("window_initialize_hook", minibuffer_keymaps_display_initialize);
1172         remove_hook("set_input_mode_hook", minibuffer_keymaps_display_update);
1173         for_each_window(function (w) {
1174             var element = w.document
1175                 .getElementById("keymaps-display");
1176             if (element)
1177                 element.parentNode.removeChild(element);
1178         });
1179     });
1181 minibuffer_keymaps_display_mode(true);
1185  * minibuffer-keymaps-highlight
1186  */
1187 function minibuffer_keymaps_highlight_update (buffer) {
1188     var mb = buffer.window.document.getElementById("minibuffer");
1189     if (buffer.keymaps.some(function (k) k.notify))
1190         dom_add_class(mb, "highlight");
1191     else
1192         dom_remove_class(mb, "highlight");
1195 define_global_mode("minibuffer_keymaps_highlight_mode",
1196     function enable () {
1197         add_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1198     },
1199     function disable () {
1200         remove_hook("set_input_mode_hook", minibuffer_keymaps_highlight_update);
1201         for_each_window(function (w) {
1202             var mb = w.document.getElementById("minibuffer");
1203             if (mb)
1204                 dom_remove_class("highlight");
1205         });
1206     });
1208 minibuffer_keymaps_highlight_mode(true);
1211 provide("buffer");