2 * (C) Copyright 2004-2007 Shawn Betts
3 * (C) Copyright 2007-2009 John J. Foerch
4 * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
6 * Use, modification, and distribution are subject to the terms specified in the
13 * trim_whitespace removes whitespace from the beginning and end of the
16 function trim_whitespace (str) {
17 var tmp = new String(str);
18 return tmp.replace(/^\s+/, "").replace(/\s+$/, "");
22 function shell_quote (str) {
23 var s = str.replace("\"", "\\\"", "g");
24 s = s.replace("$", "\$", "g");
28 /* Like perl's quotemeta. Backslash all non-alphanumerics. */
29 function quotemeta (str) {
30 return str.replace(/([^a-zA-Z0-9])/g, "\\$1");
33 /* Given a list of choices (strings), return a regex which matches any
35 function choice_regex (choices) {
36 var regex = "(?:" + choices.map(quotemeta).join("|") + ")";
42 * get_shortdoc_string, given a docstring, returns the portion of the
43 * docstring up to the first newline, or the whole docstring.
45 function get_shortdoc_string (doc) {
48 var idx = doc.indexOf("\n");
50 shortdoc = doc.substring(0,idx);
59 * string_format takes a format-string containing %X style format codes,
60 * and an object mapping the code-letters to replacement text. It
61 * returns a string with the formatting codes replaced by the replacement
64 function string_format (spec, substitutions) {
65 return spec.replace(/%(.)/g, function (a, b) substitutions[b]);
70 * html_escape replaces characters which are special in html with character
71 * entities, safe for inserting as text into an html document.
73 function html_escape (str) {
74 return str.replace(/&/g, '&')
75 .replace(/</g, '<')
76 .replace(/>/g, '>')
77 .replace(/"/g, '"');
82 * get_spaces returns a string of n spaces.
84 function get_spaces (n) {
86 while (x.length < n) x += " ";
92 * word_wrap wraps str to line_length.
94 function word_wrap (str, line_length, line_prefix_first, line_prefix) {
95 if (line_prefix === undefined)
96 line_prefix = line_prefix_first;
97 else if (line_prefix.length < line_prefix_first.length) {
98 line_prefix += get_spaces(line_prefix_first.length - line_prefix.length);
101 line_length -= line_prefix_first.length;
106 let cur_prefix = line_prefix_first;
109 while (line_length < str.length) {
110 let i = str.lastIndexOf(" ", line_length);
112 i = str.indexOf(" ", line_length);
114 out += cur_prefix + str + "\n";
118 out += cur_prefix + str.substr(0, i) + "\n";
119 while (i < str.length && str.charAt(i) == " ")
123 cur_prefix = line_prefix;
126 out += cur_prefix + str + "\n";
132 * or_string joins an array of strings on commas, except for the last
133 * pair, which it joins with the word "or".
135 function or_string (options) {
136 return options.slice(0,options.length-1)
137 .join(", ") + " or " + options[options.length - 1];