Method: String#wrap

Defined in:
lib/na/string.rb

#wrap(width, indent) ⇒ String

Wrap the string to a given width, indenting each line and preserving tag formatting.

Parameters:

  • width (Integer)

    The maximum line width

  • indent (Integer)

    Number of spaces to indent each line

Returns:



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/na/string.rb', line 191

def wrap(width, indent)
  return to_s if width.nil? || width <= 0

  output = []
  line = []
  # Track visible length of current line (exclude the separating space before first word)
  length = -1
  text = gsub(/(@\S+)\((.*?)\)/) { "#{Regexp.last_match(1)}(#{Regexp.last_match(2).gsub(/ /, '')})" }

  text.split.each do |word|
    uncolored = NA::Color.uncolor(word)
    candidate = length + 1 + uncolored.length
    if candidate <= width
      line << word
      length = candidate
    else
      output << line.join(' ')
      line = [word]
      length = uncolored.length
    end
  end
  output << line.join(' ')
  # Indent all lines after the first
  output.each_with_index.map { |l, i| i.zero? ? l : (' ' * indent) + l }.join("\n").gsub(//, ' ')
end