class String # Word wrap a string, not exceeding max width. # This pads the end of each line with a space, # or a hyphen if there was a word break. The margin # determines how much play to give before forcing a # word break. # # Note that this method reduces paragraphical # whitespace down to a single space. If someone # sees to fix this, then more power to you! def word_wrap(max_width=nil, margin=6) max_width ||= 80 max_width -= 1 min_width = max_width - margin blocks = []; scan(/(.*)(\n\s+\n|\Z)/m){ blocks << $~ } complete = '' blocks.each{ |block| str = ''; line = '' body = block[1].gsub(/\s+/, ' ') padding = block[2].to_s words = body.split(/\s+/) i = 0 words.each { |word| line << word while line.length > max_width clean_break = line.index(/\s\S*?$/) clean_break = 0 unless clean_break if clean_break < min_width remaining = line[max_width..-1] str << line.slice(0,max_width) str << '-' if /^[a-zA-Z0-9]/ =~ remaining str << "\n" line = line[max_width..-1] else str << line.slice(0,clean_break) str << " \n" line = line[(clean_break + 1)..-1] end end line << ' ' } str << line.chomp(' ') complete << str << padding } complete << "\n" end end # --- dev test --- if $0 == __FILE__ s = "PackMule is a rake front-end thisisaverylongwordtoseeifgetsdivededornot" s << " tool that makes it easy to 'pack-out' your Ruby packages. PackMule can run tests, build" s << " .tgz and .zip packages, create gem packages, perform a manual" s << " install, generate rdocs and publish them, and CVS support" s << " might be added soon." puts s.word_wrap(60) end