debian/conkeror.bin: Use wildcards instead of a list of xulrunner-stub versions
[conkeror.git] / modules / utils.js
blob78fe91eae872e019d9e64c4f8efa9b82f26bb2d9
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007-2008 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 function string_hashset () {}
12 string_hashset.prototype = {
13     constructor : string_hashset,
15     add : function (s) {
16         this["-" + s] = true;
17     },
19     contains : function (s) {
20         return (("-" + s) in this);
21     },
23     remove : function (s) {
24         delete this["-" + s];
25     },
27     for_each : function (f) {
28         for (var i in this) {
29             if (i[0] == "-")
30                 f(i.slice(1));
31         }
32     },
34     iterator : function () {
35         for (let k in this) {
36             if (i[0] == "-")
37                 yield i.slice(1);
38         }
39     }
42 function string_hashmap () {}
44 string_hashmap.prototype = {
45     constructor : string_hashmap,
47     put : function (s,value) {
48         this["-" + s] = value;
49     },
51     contains : function (s) {
52         return (("-" + s) in this);
53     },
55     get : function (s, default_value) {
56         if (this.contains(s))
57             return this["-" + s];
58         return default_value;
59     },
61     get_put_default : function (s, default_value) {
62         if (this.contains(s))
63             return this["-" + s];
64         return (this["-" + s] = default_value);
65     },
67     remove : function (s) {
68         delete this["-" + s];
69     },
71     for_each : function (f) {
72         for (var i in this) {
73             if (i[0] == "-")
74                 f(i.slice(1), this[i]);
75         }
76     },
78     for_each_value : function (f) {
79         for (var i in this) {
80             if (i[0] == "-")
81                 f(this[i]);
82         }
83     },
85     iterator: function (only_keys) {
86         if (only_keys) {
87             for (let k in Iterator(this, true)) {
88                 if (k[0] == "-")
89                     yield k.slice(1);
90             }
91         } else {
92             for (let [k,v] in Iterator(this, false)) {
93                 if (k[0] == "-")
94                     yield [k.slice(1),v];
95             }
96         }
97     }
101 // Put the string on the clipboard
102 function writeToClipboard (str) {
103     var gClipboardHelper = Cc["@mozilla.org/widget/clipboardhelper;1"]
104         .getService(Ci.nsIClipboardHelper);
105     gClipboardHelper.copyString(str);
109 function makeURLAbsolute (base, url) {
110     // Construct nsIURL.
111     var ioService = Cc["@mozilla.org/network/io-service;1"]
112         .getService(Ci.nsIIOService);
113     var baseURI  = ioService.newURI(base, null, null);
114     return ioService.newURI(baseURI.resolve(url), null, null).spec;
118 function get_link_location (element) {
119     if (element && element.getAttribute("href")) {
120         var loc = element.getAttribute("href");
121         return makeURLAbsolute(element.baseURI, loc);
122     }
123     return null;
127 function make_file (path) {
128     if (path instanceof Ci.nsILocalFile)
129         return path;
130     var f = Cc["@mozilla.org/file/local;1"]
131         .createInstance(Ci.nsILocalFile);
132     f.initWithPath(path);
133     return f;
136 var io_service = Cc["@mozilla.org/network/io-service;1"]
137     .getService(Ci.nsIIOService2);
139 function make_uri (uri, charset, base_uri) {
140     if (uri instanceof Ci.nsIURI)
141         return uri;
142     if (uri instanceof Ci.nsIFile)
143         return io_service.newFileURI(uri);
144     return io_service.newURI(uri, charset, base_uri);
148 function get_document_content_disposition (document_o) {
149     var content_disposition = null;
150     try {
151         content_disposition = document_o.defaultView
152             .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
153             .getInterface(Components.interfaces.nsIDOMWindowUtils)
154             .getDocumentMetadata("content-disposition");
155     } catch (e) { }
156     return content_disposition;
160 function set_focus_no_scroll (window, element) {
161     window.document.commandDispatcher.suppressFocusScroll = true;
162     element.focus();
163     window.document.commandDispatcher.suppressFocusScroll = false;
166 function do_repeatedly_positive (func, n) {
167     var args = Array.prototype.slice.call(arguments, 2);
168     while (n-- > 0)
169         func.apply(null, args);
172 function do_repeatedly (func, n, positive_args, negative_args) {
173     if (n < 0)
174         do func.apply(null, negative_args); while (++n < 0);
175     else
176         while (n-- > 0) func.apply(null, positive_args);
179 // remove whitespace from the beginning and end
180 function trim_whitespace (str) {
181     var tmp = new String(str);
182     return tmp.replace(/^\s+/, "").replace(/\s+$/, "");
186  * Given a node, returns its position relative to the document.
188  * @param node The node to get the position of.
189  * @return An object with properties "x" and "y" representing its offset from
190  *         the left and top of the document, respectively.
191  */
192 function abs_point (node) {
193     var orig = node;
194     var pt = {};
195     try {
196         pt.x = node.offsetLeft;
197         pt.y = node.offsetTop;
198         // find imagemap's coordinates
199         if (node.tagName == "AREA") {
200             var coords = node.getAttribute("coords").split(",");
201             pt.x += Number(coords[0]);
202             pt.y += Number(coords[1]);
203         }
205         node = node.offsetParent;
206         // Sometimes this fails, so just return what we got.
208         while (node.tagName != "BODY") {
209             pt.x += node.offsetLeft;
210             pt.y += node.offsetTop;
211             node = node.offsetParent;
212         }
213     } catch(e) {
214 //      node = orig;
215 //      while (node.tagName != "BODY") {
216 //          alert("okay: " + node + " " + node.tagName + " " + pt.x + " " + pt.y);
217 //          node = node.offsetParent;
218 //      }
219     }
220     return pt;
225  * get_os returns a string identifying the current OS.
226  * possible values include 'Darwin', 'Linux' and 'WINNT'.
227  */
228 let (xul_runtime = Cc['@mozilla.org/xre/app-info;1']
229          .getService(Ci.nsIXULRuntime)) {
230     function get_os () {
231         return xul_runtime.OS;
232     }
237  * getenv returns the value of a named environment variable or null if
238  * the environment variable does not exist.
239  */
240 let (env = Cc['@mozilla.org/process/environment;1']
241          .getService(Ci.nsIEnvironment)) {
242     function getenv (variable) {
243         if (env.exists(variable))
244             return env.get(variable);
245         return null;
246     }
251  * get_home_directory returns an nsILocalFile object of the user's
252  * home directory.
253  */
254 function get_home_directory () {
255     var dir = Cc["@mozilla.org/file/local;1"]
256         .createInstance(Ci.nsILocalFile);
257     if (get_os() == "WINNT")
258         dir.initWithPath(getenv('USERPROFILE') ||
259                          getenv('HOMEDRIVE') + getenv('HOMEPATH'));
260     else
261         dir.initWithPath(getenv('HOME'));
262     return dir;
266 const XHTML_NS = "http://www.w3.org/1999/xhtml";
267 const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
268 const MATHML_NS = "http://www.w3.org/1998/Math/MathML";
269 const XLINK_NS = "http://www.w3.org/1999/xlink";
271 function create_XUL (window, tag_name) {
272     return window.document.createElementNS(XUL_NS, tag_name);
276 /* Used in calls to XPath evaluate */
277 function xpath_lookup_namespace (prefix) {
278     if (prefix == "xhtml")
279         return XHTML_NS;
280     if (prefix == "m")
281         return MATHML_NS;
282     if (prefix == "xul")
283         return XUL_NS;
284     return null;
287 function method_caller (obj, func) {
288     return function () {
289         func.apply(obj, arguments);
290     };
293 function shell_quote (str) {
294     var s = str.replace("\"", "\\\"", "g");
295     s = s.replace("$", "\$", "g");
296     return s;
299 /* Like perl's quotemeta. Backslash all non-alphanumerics. */
300 function quotemeta (str) {
301     return str.replace(/([^a-zA-Z0-9])/g, "\\$1");
304 /* Given a list of choices (strings), return a regex which matches any
305    of them*/
306 function choice_regex (choices) {
307     var regex = "(?:" + choices.map(quotemeta).join("|") + ")";
308     return regex;
311 function get_window_from_frame (frame) {
312     try {
313         var window = frame.QueryInterface(Ci.nsIInterfaceRequestor)
314             .getInterface(Ci.nsIWebNavigation)
315             .QueryInterface(Ci.nsIDocShellTreeItem)
316             .rootTreeItem
317             .QueryInterface(Ci.nsIInterfaceRequestor)
318             .getInterface(Ci.nsIDOMWindow).wrappedJSObject;
319         /* window is now an XPCSafeJSObjectWrapper */
320         window.escape_wrapper(function (w) { window = w; });
321         /* window is now completely unwrapped */
322         return window;
323     } catch (e) {
324         return null;
325     }
328 function get_buffer_from_frame (window, frame) {
329     var count = window.buffers.count;
330     for (var i = 0; i < count; ++i) {
331         var b = window.buffers.get_buffer(i);
332         if (b.top_frame == frame)
333             return b;
334     }
335     return null;
338 var file_locator = Cc["@mozilla.org/file/directory_service;1"]
339     .getService(Ci.nsIProperties);
341 function get_shortdoc_string (doc) {
342     var shortdoc = null;
343     if (doc != null) {
344         var idx = doc.indexOf("\n");
345         if (idx >= 0)
346             shortdoc = doc.substring(0,idx);
347         else
348             shortdoc = doc;
349     }
350     return shortdoc;
353 var conkeror_source_code_path = null;
355 function source_code_reference (uri, line_number) {
356     this.uri = uri;
357     this.line_number = line_number;
359 source_code_reference.prototype = {
360     get module_name () {
361         if (this.uri.indexOf(module_uri_prefix) == 0)
362             return this.uri.substring(module_uri_prefix.length);
363         return null;
364     },
366     get file_name () {
367         var file_uri_prefix = "file://";
368         if (this.uri.indexOf(file_uri_prefix) == 0)
369             return this.uri.substring(file_uri_prefix.length);
370         return null;
371     },
373     get best_uri () {
374         if (conkeror_source_code_path != null) {
375             var module_name = this.module_name;
376             if (module_name != null)
377                 return "file://" + conkeror_source_code_path + "/modules/" + module_name;
378         }
379         return this.uri;
380     },
382     open_in_editor : function() {
383         yield open_with_external_editor(this.best_uri, $line = this.line_number);
384     }
387 var get_caller_source_code_reference_ignored_functions = {};
389 function get_caller_source_code_reference (extra_frames_back) {
390     /* Skip at least this function itself and whoever called it (and
391      * more if the caller wants to be skipped). */
392     var frames_to_skip = 2;
393     if (extra_frames_back != null)
394         frames_to_skip += extra_frames_back;
396     for (let f = Components.stack; f != null; f = f.caller) {
397         if (frames_to_skip > 0) {
398             --frames_to_skip;
399             continue;
400         }
401         if (get_caller_source_code_reference_ignored_functions[f.name])
402             continue;
403         return new source_code_reference(f.filename, f.lineNumber);
404     }
406     return null;
409 function ignore_function_for_get_caller_source_code_reference (func_name) {
410     get_caller_source_code_reference_ignored_functions[func_name] = 1;
413 require_later("external-editor.js");
415 function dom_generator (document, ns) {
416     this.document = document;
417     this.ns = ns;
419 dom_generator.prototype = {
420     element : function (tag, parent) {
421         var node = this.document.createElementNS(this.ns, tag);
422         var i = 1;
423         if (parent != null && (parent instanceof Ci.nsIDOMNode)) {
424             parent.appendChild(node);
425             i = 2;
426         }
427         for (; i < arguments.length; i += 2)
428             node.setAttribute(arguments[i], arguments[i+1]);
429         return node;
430     },
432     text : function (str, parent) {
433         var node = this.document.createTextNode(str);
434         if (parent)
435             parent.appendChild(node);
436         return node;
437     },
440     stylesheet_link : function (href, parent) {
441         var node = this.element("link");
442         node.setAttribute("rel", "stylesheet");
443         node.setAttribute("type", "text/css");
444         node.setAttribute("href", href);
445         if (parent)
446             parent.appendChild(node);
447         return node;
448     },
451     add_stylesheet : function (url) {
452         var head = this.document.documentElement.firstChild;
453         this.stylesheet_link(url, head);
454     }
458  * Generates a QueryInterface function suitable for an implemenation
459  * of an XPCOM interface.  Unlike XPCOMUtils, this uses the Function
460  * constructor to generate a slightly more efficient version.  The
461  * arguments can be either Strings or elements of
462  * Components.interfaces.
463  */
464 function generate_QI () {
465     var args = Array.prototype.slice.call(arguments).map(String).concat(["nsISupports"]);
466     var fstr = "if(" +
467         Array.prototype.map.call(args, function (x) {
468             return "iid.equals(Components.interfaces." + x + ")";
469         })
470         .join("||") +
471         ") return this; throw Components.results.NS_ERROR_NO_INTERFACE;";
472     return new Function("iid", fstr);
475 function set_branch_pref (branch, name, value) {
476     if (typeof(value) == "string") {
477         branch.setCharPref(name, value);
478     } else if (typeof(value) == "number") {
479         branch.setIntPref(name, value);
480     } else if (typeof(value) == "boolean") {
481         branch.setBoolPref(name, value);
482     }
485 function default_pref (name, value) {
486     var branch = preferences.getDefaultBranch(null);
487     set_branch_pref(branch, name, value);
490 function user_pref (name, value) {
491     var branch = preferences.getBranch(null);
492     set_branch_pref(branch, name, value);
495 function get_branch_pref (branch, name) {
496     switch (branch.getPrefType(name)) {
497     case branch.PREF_STRING:
498         return branch.getCharPref(name);
499     case branch.PREF_INT:
500         return branch.getIntPref(name);
501     case branch.PREF_BOOL:
502         return branch.getBoolPref(name);
503     default:
504         return null;
505     }
508 function get_localized_pref (name) {
509     try {
510         return preferences.getBranch(null).getComplexValue(name, Ci.nsIPrefLocalizedString).data;
511     } catch (e) {
512         return null;
513     }
516 function get_pref (name) {
517     var branch = preferences.getBranch(null);
518     return get_branch_pref(branch, name);
521 function get_default_pref (name) {
522     var branch = preferences.getDefaultBranch(null);
523     return get_branch_pref(branch, name);
526 function clear_pref (name) {
527     var branch = preferences.getBranch(null);
528     return branch.clearUserPref(name);
531 function pref_has_user_value (name) {
532     var branch = preferences.getBranch(null);
533     return branch.prefHasUserValue(name);
536 function pref_has_default_value (name) {
537     var branch = preferences.getDefaultBranch(null);
538     return branch.prefHasUserValue(name);
541 function session_pref (name, value) {
542     try {
543         clear_pref (name);
544     } catch (e) {}
545     return default_pref(name, value);
548 function watch_pref (pref, hook) {
549     /* Extract pref into branch.pref */
550     let match = pref.match(/^(.*[.])?([^.]*)$/);
551     let br = match[1];
552     let key = match[2];
553     let branch = preferences.getBranch(br).QueryInterface(Ci.nsIPrefBranch2);
554     let observer = {
555         observe: function (subject, topic, data) {
556             if (topic == "nsPref:changed" && data == key) {
557                 hook();
558             }
559         }
560     };
561     branch.addObserver("", observer, false);
564 const LOCALE_PREF = "general.useragent.locale";
566 function get_locale () {
567     return get_localized_pref(LOCALE_PREF) || get_pref(LOCALE_PREF);
570 const USER_AGENT_OVERRIDE_PREF = "general.useragent.override";
572 function set_user_agent (str) {
573     session_pref(USER_AGENT_OVERRIDE_PREF, str);
576 function define_builtin_commands (prefix, do_command_function, toggle_mark, mark_active_predicate, mode) {
578     // Specify a docstring
579     function D (cmd, docstring) {
580         var o = new String(cmd);
581         o.doc = docstring;
582         return o;
583     }
585     // Specify a forward/reverse pair
586     function R (a, b) {
587         var o = [a,b];
588         o.is_reverse_pair = true;
589         return o;
590     }
592     // Specify a movement/select/scroll/move-caret command group.
593     function S (command, movement, select, scroll, caret) {
594         var o = [movement, select, scroll, caret];
595         o.command = command;
596         o.is_move_select_pair = true;
597         return o;
598     }
600     var builtin_commands = [
602         /*
603          * cmd_scrollBeginLine and cmd_scrollEndLine don't do what I
604          * want, either in or out of caret mode...
605          */
606         S(D("beginning-of-line", "Move or extend the selection to the beginning of the current line."),
607           D("cmd_beginLine", "Move point to the beginning of the current line."),
608           D("cmd_selectBeginLine", "Extend selection to the beginning of the current line."),
609           D("cmd_beginLine", "Scroll to the beginning of the line"),
610           D("cmd_beginLine", "Scroll to the beginning of the line")),
611         S(D("end-of-line", "Move or extend the selection to the end of the current line."),
612           D("cmd_endLine", "Move point to the end of the current line."),
613           D("cmd_selectEndLine", "Extend selection to the end of the current line."),
614           D("cmd_endLine", "Scroll to the end of the current line."),
615           D("cmd_endLine", "Scroll to the end of the current line.")),
616         S(D("beginning-of-first-line", "Move or extend the selection to the beginning of the first line."),
617           D("cmd_moveTop", "Move point to the beginning of the first line."),
618           D("cmd_selectTop", "Extend selection to the beginning of the first line."),
619           D("cmd_scrollTop", "Scroll to the top of the buffer"),
620           D("cmd_scrollTop", "Move point to the beginning of the first line.")),
621         S(D("end-of-last-line", "Move or extend the selection to the end of the last line."),
622           D("cmd_moveBottom", "Move point to the end of the last line."),
623           D("cmd_selectBottom", "Extend selection to the end of the last line."),
624           D("cmd_scrollBottom", "Scroll to the bottom of the buffer"),
625           D("cmd_scrollBottom", "Move point to the end of the last line.")),
626         "cmd_copyOrDelete",
627         "cmd_scrollBeginLine",
628         "cmd_scrollEndLine",
629         "cmd_cutOrDelete",
630         D("cmd_copy", "Copy the selection into the clipboard."),
631         D("cmd_cut", "Cut the selection into the clipboard."),
632         D("cmd_deleteToBeginningOfLine", "Delete to the beginning of the current line."),
633         D("cmd_deleteToEndOfLine", "Delete to the end of the current line."),
634         D("cmd_selectAll", "Select all."),
635         D("cmd_scrollTop", "Scroll to the top of the buffer."),
636         D("cmd_scrollBottom", "Scroll to the bottom of the buffer.")];
638     var builtin_commands_with_count = [
639         R(S(D("forward-char", "Move or extend the selection forward one character."),
640             D("cmd_charNext", "Move point forward one character."),
641             D("cmd_selectCharNext", "Extend selection forward one character."),
642             D("cmd_scrollRight", "Scroll to the right"),
643             D("cmd_scrollRight", "Scroll to the right")),
644           S(D("backward-char", "Move or extend the selection backward one character."),
645             D("cmd_charPrevious", "Move point backward one character."),
646             D("cmd_selectCharPrevious", "Extend selection backward one character."),
647             D("cmd_scrollLeft", "Scroll to the left."),
648             D("cmd_scrollLeft", "Scroll to the left."))),
649         R(D("cmd_deleteCharForward", "Delete the following character."),
650           D("cmd_deleteCharBackward", "Delete the previous character.")),
651         R(D("cmd_deleteWordForward", "Delete the following word."),
652           D("cmd_deleteWordBackward", "Delete the previous word.")),
653         R(S(D("forward-line", "Move or extend the selection forward one line."),
654             D("cmd_lineNext", "Move point forward one line."),
655             D("cmd_selectLineNext", "Extend selection forward one line."),
656             D("cmd_scrollLineDown", "Scroll down one line."),
657             D("cmd_scrollLineDown", "Scroll down one line.")),
658           S(D("backward-line", "Move or extend the selection backward one line."),
659             D("cmd_linePrevious", "Move point backward one line."),
660             D("cmd_selectLinePrevious", "Extend selection backward one line."),
661             D("cmd_scrollLineUp", "Scroll up one line."),
662             D("cmd_scrollLineUp", "Scroll up one line."))),
663         R(S(D("forward-page", "Move or extend the selection forward one page."),
664             D("cmd_movePageDown", "Move point forward one page."),
665             D("cmd_selectPageDown", "Extend selection forward one page."),
666             D("cmd_scrollPageDown", "Scroll forward one page."),
667             D("cmd_movePageDown", "Move point forward one page.")),
668           S(D("backward-page", "Move or extend the selection backward one page."),
669             D("cmd_movePageUp", "Move point backward one page."),
670             D("cmd_selectPageUp", "Extend selection backward one page."),
671             D("cmd_scrollPageUp", "Scroll backward one page."),
672             D("cmd_movePageUp", "Move point backward one page."))),
673         R(D("cmd_undo", "Undo last editing action."),
674           D("cmd_redo", "Redo last editing action.")),
675         R(S(D("forward-word", "Move or extend the selection forward one word."),
676             D("cmd_wordNext", "Move point forward one word."),
677             D("cmd_selectWordNext", "Extend selection forward one word."),
678             D("cmd_scrollRight", "Scroll to the right."),
679             D("cmd_wordNext", "Move point forward one word.")),
680           S(D("backward-word", "Move or extend the selection backward one word."),
681             D("cmd_wordPrevious", "Move point backward one word."),
682             D("cmd_selectWordPrevious", "Extend selection backward one word."),
683             D("cmd_scrollLeft", "Scroll to the left."),
684             D("cmd_wordPrevious", "Move point backward one word."))),
685         R(D("cmd_scrollPageUp", "Scroll up one page."),
686           D("cmd_scrollPageDown", "Scroll down one page.")),
687         R(D("cmd_scrollLineUp", "Scroll up one line."),
688           D("cmd_scrollLineDown", "Scroll down one line.")),
689         R(D("cmd_scrollLeft", "Scroll left."),
690           D("cmd_scrollRight", "Scroll right.")),
691         D("cmd_paste", "Insert the contents of the clipboard.")];
693     interactive(prefix + "set-mark",
694                 "Toggle whether the mark is active.\n" +
695                 "When the mark is active, movement commands affect the selection.",
696                 toggle_mark);
698     function get_mode_idx () {
699         if (mode == 'scroll') return 2;
700         else if (mode == 'caret') return 3;
701         else return 0;
702     }
704     function get_move_select_idx (I) {
705         return mark_active_predicate(I) ? 1 : get_mode_idx();
706     }
708     function doc_for_builtin (c) {
709         var s = "";
710         if (c.doc != null)
711             s += c.doc + "\n";
712         return s + "Run the built-in command " + c + ".";
713     }
715     function define_simple_command (c) {
716         interactive(prefix + c, doc_for_builtin(c), function (I) { do_command_function(I, c); });
717     }
719     function get_move_select_doc_string (c) {
720         return c.command.doc +
721             "\nSpecifically, if the mark is active, runs `" + prefix + c[1] + "'.  " +
722             "Otherwise, runs `" + prefix + c[get_mode_idx()] + "'\n" +
723             "To toggle whether the mark is active, use `" + prefix + "set-mark'.";
724     }
726     for each (let c_temp in builtin_commands) {
727         let c = c_temp;
728         if (c.is_move_select_pair) {
729             interactive(prefix + c.command, get_move_select_doc_string(c), function (I) {
730                 var idx = get_move_select_idx(I);
731                 do_command_function(I, c[idx]);
732             });
733             define_simple_command(c[0]);
734             define_simple_command(c[1]);
735         }
736         else
737             define_simple_command(c);
738     }
740     function get_reverse_pair_doc_string (main_doc, alt_command) {
741         return main_doc + "\n" +
742             "The prefix argument specifies a repeat count for this command.  " +
743             "If the count is negative, `" + prefix + alt_command + "' is performed instead with " +
744             "a corresponding positive repeat count.";
745     }
747     function define_simple_reverse_pair (a, b) {
748         interactive(prefix + a, get_reverse_pair_doc_string(doc_for_builtin(a), b),
749                     function (I) {
750                         do_repeatedly(do_command_function, I.p, [I, a], [I, b]);
751                     });
752         interactive(prefix + b, get_reverse_pair_doc_string(doc_for_builtin(b), a),
753                     function (I) {
754                         do_repeatedly(do_command_function, I.p, [I, b], [I, a]);
755                     });
756     }
758     for each (let c_temp in builtin_commands_with_count) {
759         let c = c_temp;
760         if (c.is_reverse_pair) {
761             if (c[0].is_move_select_pair) {
762                 interactive(prefix + c[0].command, get_reverse_pair_doc_string(get_move_select_doc_string(c[0]),
763                                                                                c[1].command),
764                             function (I) {
765                                 var idx = get_move_select_idx(I);
766                                 do_repeatedly(do_command_function, I.p, [I, c[0][idx]], [I, c[1][idx]]);
767                             });
768                 interactive(prefix + c[1].command, get_reverse_pair_doc_string(get_move_select_doc_string(c[1]),
769                                                                                c[0].command),
770                             function (I) {
771                                 var idx = get_move_select_idx(I);
772                                 do_repeatedly(do_command_function, I.p, [I, c[1][idx]], [I, c[0][idx]]);
773                             });
774                 define_simple_reverse_pair(c[0][0], c[1][0]);
775                 define_simple_reverse_pair(c[0][1], c[1][1]);
776             } else
777                 define_simple_reverse_pair(c[0], c[1]);
778         } else {
779             let doc = doc_for_builtin(c) +
780                 "\nThe prefix argument specifies a positive repeat count for this command.";
781             interactive(prefix + c, doc, function (I) {
782                 do_repeatedly_positive(do_command_function, I.p, I, c);
783             });
784         }
785     }
788 var observer_service = Cc["@mozilla.org/observer-service;1"]
789     .getService(Ci.nsIObserverService);
791 function abort (str) {
792     var e = new Error(str);
793     e.__proto__ = abort.prototype;
794     return e;
796 abort.prototype.__proto__ = Error.prototype;
799 function get_temporary_file (name) {
800     if (name == null)
801         name = "temp.txt";
802     var file = file_locator.get("TmpD", Ci.nsIFile);
803     file.append(name);
804     // Create the file now to ensure that no exploits are possible
805     file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0600);
806     return file;
810 /* FIXME: This should be moved somewhere else, perhaps. */
811 function create_info_panel (window, panel_class, row_arr) {
812     /* Show information panel above minibuffer */
814     var g = new dom_generator(window.document, XUL_NS);
816     var p = g.element("vbox", "class", "panel " + panel_class, "flex", "0");
817     var grid = g.element("grid", p);
818     var cols = g.element("columns", grid);
819     g.element("column", cols, "flex", "0");
820     g.element("column", cols, "flex", "1");
822     var rows = g.element("rows", grid);
823     var row;
825     for each (let [row_class, row_label, row_value] in row_arr) {
826         row = g.element("row", rows, "class", row_class);
827         g.element("label", row,
828                   "value", row_label,
829                   "class", "panel-row-label");
830         g.element("label", row,
831                   "value", row_value,
832                   "class", "panel-row-value",
833                   "crop", "end");
834     }
835     window.minibuffer.insert_before(p);
837     p.destroy = function () {
838         this.parentNode.removeChild(this);
839     };
841     return p;
846  * Paste from the X primary selection, unless the system doesn't support a
847  * primary selection, in which case fall back to the clipboard.
848  */
849 function read_from_x_primary_selection () {
850     // Get clipboard.
851     let clipboard = Components.classes["@mozilla.org/widget/clipboard;1"]
852         .getService(Components.interfaces.nsIClipboard);
854     // Fall back to global clipboard if the system doesn't support a selection
855     let which_clipboard = clipboard.supportsSelectionClipboard() ?
856         clipboard.kSelectionClipboard : clipboard.kGlobalClipboard;
858     let flavors = ["text/unicode"];
860     // Don't barf if there's nothing on the clipboard
861     if (!clipboard.hasDataMatchingFlavors(flavors, flavors.length, which_clipboard))
862         return "";
864     // Create transferable that will transfer the text.
865     let trans = Components.classes["@mozilla.org/widget/transferable;1"]
866         .createInstance(Components.interfaces.nsITransferable);
868     for each (let flavor in flavors) {
869         trans.addDataFlavor(flavor);
870     }
871     clipboard.getData(trans, which_clipboard);
873     var data_flavor = {};
874     var data = {};
875     var dataLen = {};
876     trans.getAnyTransferData(data_flavor, data, dataLen);
878     if (data) {
879         data = data.value.QueryInterface(Components.interfaces.nsISupportsString);
880         let data_length = dataLen.value;
881         if (data_flavor.value == "text/unicode")
882             data_length = dataLen.value / 2;
883         return data.data.substring(0, data_length);
884     } else {
885         return "";
886     }
889 var user_variables = {};
891 function define_variable (name, default_value, doc) {
892     conkeror[name] = default_value;
893     user_variables[name] = {
894         default_value: default_value,
895         doc: doc,
896         shortdoc: get_shortdoc_string(doc),
897         source_code_reference: get_caller_source_code_reference()
898     };
901 function define_special_variable (name, getter, setter, doc) {
902     conkeror.__defineGetter__(name, getter);
903     conkeror.__defineSetter__(name, setter);
904     user_variables[name] = {
905         default_value: undefined,
906         doc: doc,
907         shortdoc: get_shortdoc_string(doc),
908         source_code_reference: get_caller_source_code_reference()
909     };
912 /* Re-define load_paths as a user variable. */
913 define_variable("load_paths", load_paths,
914                 "Array of URL prefixes searched in order when loading a module.\n" +
915                 "Each entry must end in a slash, and should begin with file:// or chrome://.");
918  * Stylesheets
919  */
920 function register_user_stylesheet (url) {
921     var uri = make_uri(url);
922     var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
923         .getService(Ci.nsIStyleSheetService);
924     sss.loadAndRegisterSheet(uri, sss.USER_SHEET);
927 function unregister_user_stylesheet (url) {
928     var uri = make_uri(url);
929     var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
930         .getService(Ci.nsIStyleSheetService);
931     if (sss.sheetRegistered(uri, sss.USER_SHEET))
932         sss.unregisterSheet(uri, sss.USER_SHEET);
935 function register_agent_stylesheet (url) {
936     var uri = make_uri(url);
937     var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
938         .getService(Ci.nsIStyleSheetService);
939     sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET);
942 function unregister_agent_stylesheet (url) {
943     var uri = make_uri(url);
944     var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
945         .getService(Ci.nsIStyleSheetService);
946     if (sss.sheetRegistered(uri, sss.AGENT_SHEET))
947         sss.unregisterSheet(uri, sss.AGENT_SHEET);
950 function agent_stylesheet_registered_p (url) {
951     var uri = make_uri(url);
952     var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
953         .getService(Ci.nsIStyleSheetService);
954     return sss.sheetRegistered(uri, sss.AGENT_SHEET);
957 function user_stylesheet_registered_p (url) {
958     var uri = make_uri(url);
959     var sss = Cc["@mozilla.org/content/style-sheet-service;1"]
960         .getService(Ci.nsIStyleSheetService);
961     return sss.sheetRegistered(uri, sss.USER_SHEET);
966 function predicate_alist_match (alist, key) {
967     for each (let i in alist) {
968         if (i[0](key))
969             return i[1];
970     }
971     return undefined;
975 function get_meta_title (doc) {
976     var title = doc.evaluate("//meta[@name='title']/@content", doc, xpath_lookup_namespace,
977                              Ci.nsIDOMXPathResult.STRING_TYPE , null);
978     if (title && title.stringValue)
979         return title.stringValue;
980     return null;
983 var rdf_service = Cc["@mozilla.org/rdf/rdf-service;1"]
984     .getService(Ci.nsIRDFService);
986 const PREFIX_ITEM_URI = "urn:mozilla:item:";
987 const PREFIX_NS_EM = "http://www.mozilla.org/2004/em-rdf#";
989 var extension_manager = Cc["@mozilla.org/extensions/manager;1"]
990     .getService(Ci.nsIExtensionManager);
992 function get_extension_rdf_property (id, name, type) {
993     var value = extension_manager.datasource.GetTarget(
994         rdf_service.GetResource(PREFIX_ITEM_URI + id),
995         rdf_service.GetResource(PREFIX_NS_EM + name),
996         true);
997     if (value == null)
998         return null;
999     return value.QueryInterface(type || Ci.nsIRDFLiteral).Value;
1002 function get_extension_update_item (id) {
1003     return extension_manager.getItemForID(id);
1006 function extension_info (id) {
1007     this.id = id;
1009 extension_info.prototype = {
1010     // Returns the nsIUpdateItem object associated with this extension
1011     get update_item () { return get_extension_update_item(this.id); },
1013     get_rdf_property : function (name, type) {
1014         return get_extension_rdf_property(this.id, name, type);
1015     },
1017     // RDF properties
1018     get isDisabled () { return this.get_rdf_property("isDisabled"); },
1019     get aboutURL () { return this.get_rdf_property("aboutURL"); },
1020     get addonID () { return this.get_rdf_property("addonID"); },
1021     get availableUpdateURL () { return this.get_rdf_property("availableUpdateURL"); },
1022     get availableUpdateVersion () { return this.get_rdf_property("availableUpdateVersion"); },
1023     get blocklisted () { return this.get_rdf_property("blocklisted"); },
1024     get compatible () { return this.get_rdf_property("compatible"); },
1025     get description () { return this.get_rdf_property("description"); },
1026     get downloadURL () { return this.get_rdf_property("downloadURL"); },
1027     get isDisabled () { return this.get_rdf_property("isDisabled"); },
1028     get hidden () { return this.get_rdf_property("hidden"); },
1029     get homepageURL () { return this.get_rdf_property("homepageURL"); },
1030     get iconURL () { return this.get_rdf_property("iconURL"); },
1031     get internalName () { return this.get_rdf_property("internalName"); },
1032     get locked () { return this.get_rdf_property("locked"); },
1033     get name () { return this.get_rdf_property("name"); },
1034     get optionsURL () { return this.get_rdf_property("optionsURL"); },
1035     get opType () { return this.get_rdf_property("opType"); },
1036     get plugin () { return this.get_rdf_property("plugin"); },
1037     get previewImage () { return this.get_rdf_property("previewImage"); },
1038     get satisfiesDependencies () { return this.get_rdf_property("satisfiesDependencies"); },
1039     get providesUpdatesSecurely () { return this.get_rdf_property("providesUpdatesSecurely"); },
1040     get type () { return this.get_rdf_property("type", Ci.nsIRDFInt); },
1041     get updateable () { return this.get_rdf_property("updateable"); },
1042     get updateURL () { return this.get_rdf_property("updateURL"); },
1043     get version () { return this.get_rdf_property("version"); }
1046 function extension_is_enabled (id) {
1047     var info = new extension_info(id);
1048     return info.update_item && (info.isDisabled == "false");
1051 function queue () {
1052     this.input = [];
1053     this.output = [];
1055 queue.prototype = {
1056     get length () {
1057         return this.input.length + this.output.length;
1058     },
1059     push: function (x) {
1060         this.input[this.input.length] = x;
1061     },
1062     pop: function (x) {
1063         let l = this.output.length;
1064         if (!l) {
1065             l = this.input.length;
1066             if (!l)
1067                 return undefined;
1068             this.output = this.input.reverse();
1069             this.input = [];
1070             let x = this.output[l];
1071             this.output.length--;
1072             return x;
1073         }
1074     }
1077 function frame_iterator (root_frame, start_with) {
1078     var q = new queue, x;
1079     if (start_with) {
1080         x = start_with;
1081         do {
1082             yield x;
1083             for (let i = 0; i < x.frames.length; ++i)
1084                 q.push(x.frames[i]);
1085         } while ((x = q.pop()));
1086     }
1087     x = root_frame;
1088     do {
1089         if (x == start_with)
1090             continue;
1091         yield x;
1092         for (let i = 0; i < x.frames.length; ++i)
1093             q.push(x.frames[i]);
1094     } while ((x = q.pop()));
1097 function xml_http_request () {
1098     return Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
1099         .createInstance(Ci.nsIXMLHttpRequest)
1100         .QueryInterface(Ci.nsIJSXMLHttpRequest)
1101         .QueryInterface(Ci.nsIDOMEventTarget);
1104 var xml_http_request_load_listener = {
1105   // nsIBadCertListener2
1106   notifyCertProblem: function SSLL_certProblem (socketInfo, status, targetSite) {
1107     return true;
1108   },
1110   // nsISSLErrorListener
1111   notifySSLError: function SSLL_SSLError (socketInfo, error, targetSite) {
1112     return true;
1113   },
1115   // nsIInterfaceRequestor
1116   getInterface: function SSLL_getInterface (iid) {
1117     return this.QueryInterface(iid);
1118   },
1120   // nsISupports
1121   //
1122   // FIXME: array comprehension used here to hack around the lack of
1123   // Ci.nsISSLErrorListener in 2007 versions of xulrunner 1.9pre.
1124   // make it a simple generateQI when xulrunner is more stable.
1125   QueryInterface: XPCOMUtils.generateQI (
1126       [i for each (i in [Ci.nsIBadCertListener2,
1127                          Ci.nsISSLErrorListener,
1128                          Ci.nsIInterfaceRequestor])
1129        if (i)])
1134  * Coroutine interface for sending an HTTP request and waiting for the
1135  * response. (This includes so-called "AJAX" requests.)
1137  * @param lspec (required) a load_spec object or URI string (see load-spec.js)
1139  * The request URI is obtained from this argument. In addition, if the
1140  * load spec specifies post data, a POST request is made instead of a
1141  * GET request, and the post data included in the load spec is
1142  * sent. Specifically, the request_mime_type and raw_post_data
1143  * properties of the load spec are used.
1145  * @param $user (optional) HTTP user name to include in the request headers
1146  * @param $password (optional) HTTP password to include in the request headers
1148  * @param $override_mime_type (optional) Force the response to be interpreted
1149  *                            as having the specified MIME type.  This is only
1150  *                            really useful for forcing the MIME type to be
1151  *                            text/xml or something similar, such that it is
1152  *                            automatically parsed into a DOM document.
1153  * @param $headers (optional) an array of [name,value] pairs (each specified as
1154  *                 a two-element array) specifying additional headers to add to
1155  *                 the request.
1157  * @returns After the request completes (either successfully or with an error),
1158  *          the nsIXMLHttpRequest object is returned.  Its responseText (for any
1159  *          arbitrary document) or responseXML (if the response type is an XML
1160  *          content type) properties can be accessed to examine the response
1161  *          document.
1163  * If an exception is thrown to the continutation (which can be obtained by the
1164  * caller by calling yield CONTINUATION prior to calling this function) while the
1165  * request is in progress (i.e. before this coroutine returns), the request will
1166  * be aborted, and the exception will be propagated to the caller.
1168  **/
1169 define_keywords("$user", "$password", "$override_mime_type", "$headers");
1170 function send_http_request (lspec) {
1171     // why do we get warnings in jsconsole unless we initialize the
1172     // following keywords?
1173     keywords(arguments, $user = undefined, $password = undefined,
1174              $override_mime_type = undefined, $headers = undefined);
1175     if (! (lspec instanceof load_spec))
1176         lspec = load_spec(lspec);
1177     var req = xml_http_request();
1178     var cc = yield CONTINUATION;
1179     var aborting = false;
1180     req.onreadystatechange = function send_http_request__onreadysatechange () {
1181         if (req.readyState != 4)
1182             return;
1183         if (aborting)
1184             return;
1185         cc();
1186     };
1188     if (arguments.$override_mime_type)
1189         req.overrideMimeType(arguments.$override_mime_type);
1191     var post_data = load_spec_raw_post_data(lspec);
1193     var method = post_data ? "POST" : "GET";
1195     req.open(method, load_spec_uri_string(lspec), true, arguments.$user, arguments.$password);
1196     req.channel.notificationCallbacks = xml_http_request_load_listener;
1198     for each (let [name,value] in arguments.$headers) {
1199         req.setRequestHeader(name, value);
1200     }
1202     if (post_data) {
1203         req.setRequestHeader("Content-Type", load_spec_request_mime_type(lspec));
1204         req.send(post_data);
1205     } else
1206         req.send(null);
1208     try {
1209         yield SUSPEND;
1210     } catch (e) {
1211         aborting = true;
1212         req.abort();
1213         throw e;
1214     }
1216     // Let the caller access the status and reponse data
1217     yield co_return(req);
1221 var JSON = ("@mozilla.org/dom/json;1" in Cc) &&
1222     Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON);
1225 var console_service = Cc["@mozilla.org/consoleservice;1"]
1226     .getService(Ci.nsIConsoleService);
1228 console_service.registerListener(
1229     {observe: function (msg) {
1230          if (msg instanceof Ci.nsIScriptError) {
1231              switch (msg.category) {
1232              case "CSS Parser":
1233              case "content javascript":
1234                  return;
1235              }
1236              msg.QueryInterface(Ci.nsIScriptError);
1237              dumpln("Console error: " + msg.message);
1238              dumpln("  Category: " + msg.category);
1239          }
1240      }});
1243 // ensure_index_is_visible ensures that the given index in the given
1244 // field (an html input field for example) is visible.
1245 function ensure_index_is_visible (window, field, index) {
1246     var start = field.selectionStart;
1247     var end = field.selectionEnd;
1248     field.setSelectionRange(index, index);
1249     send_key_as_event(window, field, "left");
1250     if (field.selectionStart < index) {
1251         send_key_as_event(window, field, "right");
1252     }
1253     field.setSelectionRange(start, end);
1256 function regex_to_string (obj) {
1257     if(obj instanceof RegExp) {
1258         obj = obj.source;
1259     } else {
1260         obj = quotemeta(obj);
1261     }
1262     return obj;
1266  * Build a regular expression to match URLs for a given web site.
1268  * Both the $domain and $path arguments can be either regexes, in
1269  * which case they will be matched as is, or strings, in which case
1270  * they will be matched literally.
1272  * $tlds specifies a list of valid top-level-domains to match, and
1273  * defaults to .com. Useful for when e.g. foo.org and foo.com are the
1274  * same.
1276  * If $allow_www is true, www.domain.tld will also be allowed.
1278  */
1279 define_keywords("$domain", "$path", "$tlds", "$allow_www");
1280 function build_url_regex () {
1281     keywords(arguments, $path = "", $tlds = ["com"], $allow_www = false);
1282     var domain = regex_to_string(arguments.$domain);
1283     if(arguments.$allow_www) {
1284         domain = "(?:www\.)?" + domain;
1285     }
1286     var path   = regex_to_string(arguments.$path);
1287     var tlds   = arguments.$tlds;
1288     var regex = "^https?://" + domain + "\\." + choice_regex(tlds) + "/" + path;
1289     return new RegExp(regex);
1294  * Given an ordered array of non-overlapping ranges, represented as
1295  * elements of [start, end], insert a new range into the array,
1296  * extending, replacing, or merging existing ranges as needed. Mutates
1297  * `arr' in place.
1299  * Examples:
1301  * splice_range([[1,3],[4,6], 5, 8)
1302  *  => [[1,3],[4,8]]
1304  * splice_range([[1,3],[4,6],[7,10]], 2, 8)
1305  *  => [[1,10]]
1306  */
1307 function splice_range (arr, start, end) {
1308     for (var i = 0; i < arr.length; ++i) {
1309         let [n,m] = arr[i];
1310         if (start > m)
1311             continue;
1312         if (end < n) {
1313             arr.splice(i, 0, [start, end]);
1314             break;
1315         }
1316         if (start < n)
1317             arr[i][0] = start;
1319         if (end >= n) {
1320             /*
1321              * The range we are inserting overlaps the current
1322              * range. We need to scan right to see if it also contains any other
1323              * ranges entirely, and remove them if necessary.
1324              */
1325             var j = i;
1326             while (j < arr.length && end >= arr[j][0])
1327                 j++;
1328             j--;
1329             arr[i][1] = Math.max(end, arr[j][1]);
1330             arr.splice(i + 1, j - i);
1331             break;
1332         }
1333     }
1334     if (start > arr[arr.length - 1][1])
1335         arr.push([start, end]);
1339 function compute_url_up_path (url) {
1340     var new_url = Cc["@mozilla.org/network/standard-url;1"]
1341         .createInstance (Ci.nsIURL);
1342     new_url.spec = url;
1343     var up;
1344     if (new_url.param != "" || new_url.query != "")
1345         up = new_url.filePath;
1346     else if (new_url.fileName != "")
1347         up = ".";
1348     else
1349         up = "..";
1350     return up;
1354 function url_path_trim (url) {
1355     var uri = make_uri(url);
1356     uri.spec = url;
1357     uri.path = "";
1358     return uri.spec;
1361 /* possibly_valid_url returns true if the string might be a valid
1362  * thing to pass to nsIWebNavigation.loadURI.  Currently just checks
1363  * that there's no whitespace in the middle and that it's not entirely
1364  * whitespace.
1365  */
1366 function possibly_valid_url (url) {
1367     return !(/\S\s+\S/.test(url)) && !(/^\s*$/.test(url));
1371 /* remove_duplicates_filter returns a function that can be
1372  * used in Array.filter.  It removes duplicates.
1373  */
1374 function remove_duplicates_filter () {
1375     var acc = {};
1376     return function (x) {
1377         if (acc[x]) return false;
1378         acc[x] = 1;
1379         return true;
1380     };
1384 /* get_current_profile returns the name of the current profile, or
1385  * null if that information cannot be found.  The result is cached for
1386  * quick repeat lookup.  This is safe because xulrunner does not
1387  * support switching profiles on the fly.
1389  * Profiles don't necessarily have a name--as such this information should
1390  * not be depended on for anything important.  It is mainly intended for
1391  * decoration of the window title and mode-line.
1392  */
1393 let (profile_name = null) {
1394     function get_current_profile () {
1395         if (profile_name)
1396             return profile_name;
1397         if ("@mozilla.org/profile/manager;1" in Cc) {
1398             profile_name = Cc["@mozilla.org/profile/manager;1"]
1399                 .getService(Ci.nsIProfile)
1400                 .currentProfile;
1401             return profile_name;
1402         }
1403         var current_profile_path = Cc["@mozilla.org/file/directory_service;1"]
1404             .getService(Ci.nsIProperties)
1405             .get("ProfD", Ci.nsIFile).path;
1406         var profile_service = Cc["@mozilla.org/toolkit/profile-service;1"]
1407             .getService(Components.interfaces.nsIToolkitProfileService);
1408         var profiles = profile_service.profiles;
1409         while (profiles.hasMoreElements()) {
1410             var p = profiles.getNext().QueryInterface(Ci.nsIToolkitProfile);
1411             if (current_profile_path == p.localDir.path ||
1412                 current_profile_path == p.rootDir.path)
1413             {
1414                 profile_name = p.name;
1415                 return p.name;
1416             }
1417         }
1418         return null;
1419     }
1424  * Given an array, switches places on the subarrays at index i1 to i2 and j1 to
1425  * j2. Leaves the rest of the array unchanged.
1426  */
1427 function switch_subarrays (arr, i1, i2, j1, j2) {
1428     return arr.slice(0, i1) +
1429         arr.slice(j1, j2) +
1430         arr.slice(i2, j1) +
1431         arr.slice(i1, i2) +
1432         arr.slice(j2, arr.length);
1437  * Convenience function for making simple XPath lookups in a document.
1439  * @param doc The document to look in.
1440  * @param exp The XPath expression to search for.
1441  * @return The XPathResult object representing the set of found nodes.
1442  */
1443 function xpath_lookup (doc, exp) {
1444     return doc.evaluate(exp, doc, null, Ci.nsIDOMXPathResult.ANY_TYPE, null);
1448 /* get_contents_synchronously returns the contents of the given
1449  * url (string or nsIURI) as a string on success, or null on failure.
1450  */
1451 function get_contents_synchronously (url) {
1452     var ioService=Cc["@mozilla.org/network/io-service;1"]
1453         .getService(Ci.nsIIOService);
1454     var scriptableStream=Cc["@mozilla.org/scriptableinputstream;1"]
1455         .getService(Ci.nsIScriptableInputStream);
1456     var channel;
1457     var input;
1458     try {
1459         if (url instanceof Ci.nsIURI)
1460             channel = ioService.newChannelFromURI(url);
1461         else
1462             channel = ioService.newChannel(url, null, null);
1463         input=channel.open();
1464     } catch (e) {
1465         return null;
1466     }
1467     scriptableStream.init(input);
1468     var str=scriptableStream.read(input.available());
1469     scriptableStream.close();
1470     input.close();
1471     return str;
1476  * string_format takes a format-string containing %X style format codes,
1477  * and an object mapping the code-letters to replacement text.  It
1478  * returns a string with the formatting codes replaced by the replacement
1479  * text.
1480  */
1481 function string_format (spec, substitutions) {
1482     return spec.replace(/%(.)/g, function (a,b) { return substitutions[b]; });
1487  * dom_add_class adds a css class to the given dom node.
1488  */
1489 function dom_add_class (node, cssclass) {
1490     if (node.className)
1491         node.className += " "+cssclass;
1492     else
1493         node.className = cssclass;
1497  * dom_remove_class removes the given css class from the given dom node.
1498  */
1499 function dom_remove_class (node, cssclass) {
1500     if (! node.className)
1501         return;
1502     var classes = node.className.split(" ");
1503     classes = classes.filter(function (x) { return x != cssclass; });
1504     node.className = classes.join(" ");
1509  * dom_node_flash adds the given cssclass to the node for a brief interval.
1510  * this class can be styled, to create a flashing effect.
1511  */
1512 function dom_node_flash (node, cssclass) {
1513     dom_add_class(node, cssclass);
1514     call_after_timeout(
1515         function () {
1516             dom_remove_class(node, cssclass);
1517         },
1518         400);
1523  * data is an an alist (array of 2 element arrays) where each pair is a key
1524  * and a value.
1526  * The return type is a mime input stream that can be passed as postData to
1527  * nsIWebNavigation.loadURI.  In terms of Conkeror's API, the return value
1528  * of this function is of the correct type for the `post_data' field of a
1529  * load_spec.
1530  */
1531 function make_post_data (data) {
1532     data = [(encodeURIComponent(pair[0])+'='+encodeURIComponent(pair[1]))
1533             for each (pair in data)].join('&');
1534     data = string_input_stream(data);
1535     return mime_input_stream(
1536         data, [["Content-Type", "application/x-www-form-urlencoded"]]);
1541  * Centers the viewport around a given element.
1543  * @param win  The window to scroll.
1544  * @param elem The element arund which we put the viewport.
1545  */
1546 function center_in_viewport (win, elem) {
1547     let point = abs_point(elem);
1549     point.x -= win.innerWidth / 2;
1550     point.y -= win.innerHeight / 2;
1552     win.scrollTo(point.x, point.y);
1557  * Takes an interactive context and a function to call with the word
1558  * at point as its sole argument, and which returns a modified word.
1559  */
1560 function modify_word_at_point (I, func) {
1561     var focused = I.buffer.focused_element;
1563     // Skip any whitespaces at point and move point to the right place.
1564     var point = focused.selectionStart;
1565     var rest = focused.value.substring(point);
1567     // Skip any whitespaces.
1568     for (var i = 0; i < rest.length; i++) {
1569         if (" \n".indexOf(rest.charAt(i)) == -1) {
1570             point += i;
1571             break;
1572         }
1573     }
1575     // Find the next whitespace, as it is the end of the word.  If no next
1576     // whitespace is found, we're at the end of input.  TODO: Add "\n" support.
1577     goal = focused.value.indexOf(" ", point);
1578     if (goal == -1)
1579         goal = focused.value.length;
1581     // Change the value of the text field.
1582     var input = focused.value;
1583     focused.value =
1584         input.substring(0, point) +
1585         func(input.substring(point, goal)) +
1586         input.substring(goal);
1588     // Move point.
1589     focused.selectionStart = goal;
1590     focused.selectionEnd = goal;
1595  * Simple predicate returns true if elem is an nsIDOMNode or
1596  * nsIDOMWindow.
1597  */
1598 function element_dom_node_or_window_p (elem) {
1599     if (elem instanceof Ci.nsIDOMNode)
1600         return true;
1601     if (elem instanceof Ci.nsIDOMWindow)
1602         return true;
1603     return false;