Sha256: be0271cd936fd8880aa93d0a18aa01a2fef2be6878ec85772e8d46d64d6ea634

Contents?: true

Size: 1.81 KB

Versions: 10

Compression:

Stored size: 1.81 KB

Contents

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

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
facets-0.6.3 lib/facet-dev/string/word_wrap.rb
facets-1.4.1 forge/core/string/word_wrap.rb
facets-1.4.2 forge/core/string/word_wrap.rb
facets-1.4.3 forge/core/string/word_wrap.rb
facets-1.4.5 snip/core/string/word_wrap.rb
facets-1.4.4 forge/core/string/word_wrap.rb
facets-1.8.0 work/core/string/word_wrap.rb
facets-1.8.20 work/core/string/word_wrap.rb
facets-1.8.49 work/core/string/word_wrap.rb
facets-1.8.8 work/core/string/word_wrap.rb