# escape text to make it useable in a shell script as one ÒwordÓ (string) def e_sh(str) str.to_s.gsub(/(?=[^a-zA-Z0-9_.\/\-\x7F-\xFF\n])/, '\\').gsub(/\n/, "'\n'").sub(/^$/, "''") end # escape text for use in a TextMate snippet def e_sn(str) str.to_s.gsub(/(?=[$`\\])/, '\\') end # escape text for use in an AppleScript string def e_as(str) str.to_s.gsub(/(?=["\\])/, '\\') end # URL escape a string but preserve slashes (idea being we have a file system path that we want to use with file://) def e_url(str) str.gsub(/([^a-zA-Z0-9\/_.-]+)/n) do '%' + $1.unpack('H2' * $1.size).join('%').upcase end end # Make string suitable for display as HTML, preserve spaces def htmlize(str) str = str.to_s.gsub("&", "&").gsub("<", "<") str = str.gsub(/\t+/, '\0') str = str.reverse.gsub(/ (?= |$)/, ';psbn&').reverse colored_htmlize(str.gsub("\n", "
")) end # Converts 'colored' strings to HTML def colored_htmlize(str) open_tags = [] colored_index = get_next_colored_index(str) while colored_index do match_size = colored_index[1].size match = colored_index[1][1..match_size] # strip escape character start = colored_index[0] finish = colored_index[1].size + start - 1 if match[0..1] == '[3' # colors case match when '[30m' # black html_color = 'black' when '[31m' # red html_color = 'red' when '[32m' # green html_color = 'green' when '[33m' # yellow html_color = 'yellow' when '[34m' # blue html_color = 'blue' when '[35m' # magenta html_color = 'magenta' when '[36m' # cyan html_color = 'cyan' when '[37m' # white html_color = 'white' end str[start..finish] = "" open_tags << "font" else case match when '[0m' # clear if open_tags.size > 0 str[start..finish] = "" open_tags.pop end when '[1m' # bold str[start..finish] = "" open_tags << "strong" when '[4m' # underline str[start..finish] = "" open_tags << "u" when '[7m' # reverse # not implemented end end colored_index = get_next_colored_index(str) end str end # helper method for colored_htmlize def get_next_colored_index(str) start = str.index(/\e\[3[0-7]m|\e\[[0147]m/) if start finish = str.index('m', start) value = str[start..finish] [start,value] else nil end end