Module: HighLine::Wrapper
- Defined in:
- lib/highline/wrapper.rb
Overview
A simple Wrapper module that is aware of ANSI escape codes. It compensates for the ANSI escape codes so it works on the actual (visual) line length.
Class Method Summary collapse
-
.actual_length(string_with_escapes) ⇒ Integer
Returns the length of the passed
string_with_escapes
, minus and color sequence escapes. -
.wrap(text, wrap_at) ⇒ Object
Wrap a sequence of lines at wrap_at characters per line.
Class Method Details
.actual_length(string_with_escapes) ⇒ Integer
Returns the length of the passed string_with_escapes
, minus and color sequence escapes.
49 50 51 |
# File 'lib/highline/wrapper.rb', line 49 def self.actual_length(string_with_escapes) string_with_escapes.to_s.gsub(/\e\[\d{1,2}m/, "").length end |
.wrap(text, wrap_at) ⇒ Object
Wrap a sequence of lines at wrap_at characters per line. Existing newlines will not be affected by this process, but additional newlines may be added.
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/highline/wrapper.rb', line 17 def self.wrap(text, wrap_at) return text unless wrap_at wrap_at = Integer(wrap_at) wrapped = [] text.each_line do |line| # take into account color escape sequences when wrapping wrap_at += (line.length - actual_length(line)) while line =~ /([^\n]{#{wrap_at + 1},})/ search = Regexp.last_match(1).dup replace = Regexp.last_match(1).dup index = replace.rindex(" ", wrap_at) if index replace[index, 1] = "\n" replace.sub!(/\n[ \t]+/, "\n") line.sub!(search, replace) else line[$LAST_MATCH_INFO.begin(1) + wrap_at, 0] = "\n" end end wrapped << line end wrapped.join end |