Method: String#reformat

Defined in:
lib/whisper/common.rb

#reformat(width) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/whisper/common.rb', line 108

def reformat width
  lines = []
  body = self.clone

  if body =~ /\A(\n+)/ # preserve any leading newlines
    newlines = $1
    lines << newlines
    body = body[newlines.size .. -1]
  end

  while body
    newline_point = body.index(/\n([\n\*\#])/) || width

    split_point, appendage = if newline_point < width
      [newline_point + 1, "\n#{$1}"]
    elsif body.length < width
      [body.length, "\n"]
    else # regular: find a split point
      split_point = body.rindex(/\s/, width) # look backwards
      split_point ||= body.index(/\s/, width) # nope, look forward 
      split_point ||= body.length # nope, use everything (don't think this will ever occur)
      [split_point, "\n"]
    end

    start_split = split_point - 1
    start_split -= 1 while start_split > 0 && [?\ , ?\n].include?(body[start_split])

    lines << body[0 .. start_split].chomp.gsub(/\n/, " ") + appendage
    body = body[(split_point + 1) .. -1]
  end

  lines << body if body
  lines.pop if lines.last == "\n"
  lines.join("")
end