Class: String

Inherits:
Object
  • Object
show all
Includes:
Howzit::StringUtils
Defined in:
lib/howzit/colors.rb,
lib/howzit/stringutils.rb

Overview

Template coloring

Instance Method Summary collapse

Methods included from Howzit::StringUtils

#available?, #build_note?, #c, #comp_distance, #contains_count, #distance, #extract_metadata, #format_header, #in_distance?, #in_order, #iterm_marker, #metadata, #normalize_metadata, #note_title, #preserve_escapes, #render_arguments, #render_named_placeholders, #render_numeric_placeholders, #render_template, #render_template!, #should_mark_iterm?, #split_line, #to_config_value, #to_rx, #trunc, #trunc!, #uncolor, #wrap, #wrap!

Instance Method Details

#last_color_codeObject

Get the calculated ANSI color at the end of the string

Returns:

  • ANSI escape sequence to match color



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/howzit/colors.rb', line 140

def last_color_code
  m = scan(ESCAPE_REGEX)

  em = ['0']
  fg = nil
  bg = nil
  rgbf = nil
  rgbb = nil

  m.each do |c|
    case c
    when '0'
      em = ['0']
      fg, bg, rgbf, rgbb = nil
    when /^[34]8/
      case c
      when /^3/
        fg = nil
        rgbf = c
      when /^4/
        bg = nil
        rgbb = c
      end
    else
      c.split(/;/).each do |i|
        x = i.to_i
        if x <= 9
          em << x
        elsif x >= 30 && x <= 39
          rgbf = nil
          fg = x
        elsif x >= 40 && x <= 49
          rgbb = nil
          bg = x
        elsif x >= 90 && x <= 97
          rgbf = nil
          fg = x
        elsif x >= 100 && x <= 107
          rgbb = nil
          bg = x
        end
      end
    end
  end

  escape = "\e[#{em.join(';')}m"
  escape += "\e[#{rgbb}m" if rgbb
  escape += "\e[#{rgbf}m" if rgbf
  escape + "\e[#{[fg, bg].delete_if(&:nil?).join(';')}m"
end

#normalize_colorString

Normalize a color name, removing underscores, replacing "bright" with "bold", and converting bgbold to boldbg

Returns:

  • (String)

    Normalized color name



131
132
133
# File 'lib/howzit/colors.rb', line 131

def normalize_color
  gsub(/_/, '').sub(/bright/i, 'bold').sub(/bgbold/, 'boldbg')
end

#validate_colorString

Extract the longest valid %color name from a string.

Allows %colors to bleed into other text and still be recognized, e.g. %greensomething still finds %green.

Returns:

  • (String)

    a valid color name



111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/howzit/colors.rb', line 111

def validate_color
  valid_color = nil
  compiled = ''
  normalize_color.split('').each do |char|
    compiled += char
    if Color.attributes.include?(compiled.to_sym) || compiled =~ /^([fb]g?)?#([a-f0-9]{6})$/i
      valid_color = compiled
    end
  end

  valid_color
end