module Wraptools # unwrap format=flowed text def self.unwrap(s) s.gsub(/ \n/, " ") end # unwrap a format=flowed text; preserves quoting information def self.unwrap_quoted(s) level = nil # the quoting level ff = nil # does the line end with " "? text = '' s.split(/\r*\n/).each do |t| old_level = level old_ff = ff # detect the quoting level of the line if t =~ /^(>+)/ level = $1.size else level = 0 end # trailing space? ff = (t[-1,1] == " ") if old_ff and level == old_level result = t.sub(/^>{#{level}}\s/, "") else result = t end if old_ff == false or (old_ff == true and level != old_level) text += "\n" end text += result end text.gsub(/ \n/, "\n") end # wrap a text with format=flowed def self.wrap_ff(s, n) wrap(s, n, " \n") end # wrap a text def self.wrap(s, n, break_string="\n") s.split("\n").map do |t| if t =~ /^[>|]/ t + "\n" elsif t.strip == "" t = "\n" else t.gsub(/(.{0,#{n-1}}\S)(\s+|\Z)/,"\\1" + break_string).gsub(/\s+\n$/,"\n") end end.join('').chop end # split words that are longer than n characters def self.break_long_words(s, n) s.gsub(/(\S{#{n}})(?=\S)/, "\\1 \\2") end # add one level of indentation to a text def self.quote(s) s.split(/\r*\n/).each do |line| if line =~ /^>/ line.replace '>' + line else line.replace '> ' + line end end.join("\n") end end