Class: String
Constant Summary collapse
- ANSI_ESCAPE_SEQUENCE =
/\e\[(\d{1,2}(?:;\d{1,2})*[@-~])/
- ANSI_ESCAPE_MATCH =
'\e\[\d+(?:;\d+)*[@-~]'
- CHAR_SKIP_ANSI =
"(?:(?:#{ANSI_ESCAPE_MATCH})+.?|.(?:#{ANSI_ESCAPE_MATCH})*)"
Instance Method Summary collapse
- #strip_ansi ⇒ Object
- #strip_heredoc ⇒ Object
-
#textwrap_ansi(limit, breakword = true) ⇒ Object
Split the given string at limit, treating ANSI escape sequences as zero characters in length.
-
#wrap(wrap_length = 80, char = "\n") ⇒ Object
Wrap string by the given length, and join it with the given character.
Instance Method Details
#strip_ansi ⇒ Object
132 133 134 |
# File 'lib/rhc/core_ext.rb', line 132 def strip_ansi gsub(ANSI_ESCAPE_SEQUENCE, '') end |
#strip_heredoc ⇒ Object
57 58 59 60 61 62 63 |
# File 'lib/rhc/core_ext.rb', line 57 def strip_heredoc indent = scan(/^[ \t]*(?=\S)/).min.size || 0 gsub(/^[ \t]{#{indent}}/, ''). gsub(/(\b|\S)[^\S\n]*\n(\S)/m, '\1 \2'). gsub(/\n+\Z/, ''). gsub(/\n{3,}/, "\n\n") end |
#textwrap_ansi(limit, breakword = true) ⇒ Object
Split the given string at limit, treating ANSI escape sequences as zero characters in length. Will insert an ANSI reset code (e[0m) at the end of each line containing an ANSI code, assuming that a reset was not in the wrapped segment.
All newlines are preserved.
Lines longer than limit without natural breaks will be forcibly split at the exact limit boundary.
Returns an Array
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
# File 'lib/rhc/core_ext.rb', line 82 def textwrap_ansi(limit, breakword=true) re = breakword ? / ( # Match substrings that end in whitespace shorter than limit #{CHAR_SKIP_ANSI}{1,#{limit}} # up to limit (?:\s+|$) # require the limit to end on whitespace | # Match substrings equal to the limit #{CHAR_SKIP_ANSI}{1,#{limit}} ) /x : / ( # Match substrings that end in whitespace shorter than limit #{CHAR_SKIP_ANSI}{1,#{limit}} (?:\s|$) # require the limit to end on whitespace | # Match all continguous whitespace strings #{CHAR_SKIP_ANSI}+? (?:\s|$) (?:\s+|$)? ) /x escapes = [] split("\n",-1).inject([]) do |a, line| if line.length < limit a << line else line.scan(re) do |segment, other| if escapes.present? a << escapes.map{ |s| "\e[#{s}"}.join a[-1] << segment.rstrip else a << segment.rstrip end segment.scan(ANSI_ESCAPE_SEQUENCE).map{ |e| e.first }.each do |e| case e when '0m' then escapes.clear else escapes << e end end a[-1] << "\e[0m" if escapes.present? end end a end end |
#wrap(wrap_length = 80, char = "\n") ⇒ Object
Wrap string by the given length, and join it with the given character. The method doesn’t distinguish between words, it will only work based on the length.
53 54 55 |
# File 'lib/rhc/core_ext.rb', line 53 def wrap(wrap_length=80, char="\n") scan(/.{#{wrap_length}}|.+/).join(char) end |