Sha256: 4235e363c64bec5700ceb2baa0d37acb9e166f96d9c740d09d56a93b0b261e6d

Contents?: true

Size: 985 Bytes

Versions: 7

Compression:

Stored size: 985 Bytes

Contents

class String

  # Word-wraps and indents the string.
  #
  # +width+:: The maximal width of each line. This also includes indentation,
  #           i.e. the actual maximal width of the text is width-indentation.
  #
  # +indentation+:: The number of spaces to indent each wrapped line.
  def wrap_and_indent(width, indentation)
    # Split into paragraphs
    paragraphs = self.split("\n").map { |p| p.strip }.reject { |p| p == '' }

    # Wrap and indent each paragraph
    paragraphs.map do |paragraph|
      # Initialize
      lines = []
      line = ''

      # Split into words
      paragraph.split(/\s/).each do |word|
        # Begin new line if it's too long
        if (line + ' ' + word).length >= width
          lines << line
          line = ''
        end

        # Add word to line
        line += (line == '' ? '' : ' ' ) + word
      end
      lines << line

      # Join lines
      lines.map { |l| ' '*indentation + l }.join("\n")
    end.join("\n\n")
  end

end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
nanoc-2.1.4 lib/nanoc/cli/ext.rb
nanoc-2.1 lib/nanoc/cli/ext.rb
nanoc-2.1.1 lib/nanoc/cli/ext.rb
nanoc-2.1.2 lib/nanoc/cli/ext.rb
nanoc-2.1.3 lib/nanoc/cli/ext.rb
nanoc-2.1.5 lib/nanoc/cli/ext.rb
nanoc-2.1.6 lib/nanoc/cli/ext.rb