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 return (new String(str)).replace(/^\s+|\s+$/g, "");
21 function shell_quote (str) {
22 var s = str.replace("\"", "\\\"", "g");
23 s = s.replace("$", "\$", "g");
27 /* Like perl's quotemeta. Backslash all non-alphanumerics. */
28 function quotemeta (str) {
29 return str.replace(/([^a-zA-Z0-9])/g, "\\$1");
32 /* Given a list of choices (strings), return a regex which matches any
34 function choice_regex (choices) {
35 var regex = "(?:" + choices.map(quotemeta).join("|") + ")";
41 * get_shortdoc_string, given a docstring, returns the portion of the
42 * docstring up to the first newline, or the whole docstring.
44 function get_shortdoc_string (doc) {
47 var idx = doc.indexOf("\n");
49 shortdoc = doc.substring(0,idx);
58 * string_format takes a format-string containing %X style format codes,
59 * and an object mapping the code-letters to replacement text. It
60 * returns a string with the formatting codes replaced by the replacement
63 function string_format (spec, substitutions) {
64 return spec.replace(/%(.)/g, function (a, b) substitutions[b]);
69 * html_escape replaces characters which are special in html with character
70 * entities, safe for inserting as text into an html document.
72 function html_escape (str) {
73 return str.replace(/&/g, '&')
74 .replace(/</g, '<')
75 .replace(/>/g, '>')
76 .replace(/"/g, '"');
81 * get_spaces returns a string of n spaces.
83 function get_spaces (n) {
85 while (x.length < n) x += " ";
91 * word_wrap wraps str to line_length.
93 function word_wrap (str, line_length, line_prefix_first, line_prefix) {
94 if (line_prefix === undefined)
95 line_prefix = line_prefix_first;
96 else if (line_prefix.length < line_prefix_first.length) {
97 line_prefix += get_spaces(line_prefix_first.length - line_prefix.length);
100 line_length -= line_prefix_first.length;
105 let cur_prefix = line_prefix_first;
108 while (line_length < str.length) {
109 let i = str.lastIndexOf(" ", line_length);
111 i = str.indexOf(" ", line_length);
113 out += cur_prefix + str + "\n";
117 out += cur_prefix + str.substr(0, i) + "\n";
118 while (i < str.length && str.charAt(i) == " ")
122 cur_prefix = line_prefix;
125 out += cur_prefix + str + "\n";
131 * or_string joins an array of strings on commas, except for the last
132 * pair, which it joins with the word "or".
134 function or_string (options) {
135 return options.slice(0,options.length-1)
136 .join(", ") + " or " + options[options.length - 1];