Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/na/colors.rb,
lib/na/string.rb

Overview

String helpers

Instance Method Summary collapse

Instance Method Details

#cap_firstString

Capitalize first character, leaving other capitalization in place

Returns:

  • (String)

    capitalized string



130
131
132
133
134
135
# File 'lib/na/string.rb', line 130

def cap_first
  sub(/^([a-z])(.*)$/) do
    m = Regexp.last_match
    m[1].upcase << m[2]
  end
end

#cap_first!Object



120
121
122
# File 'lib/na/string.rb', line 120

def cap_first!
  replace cap_first
end

#dir_matches(any: [], all: []) ⇒ Object



103
104
105
# File 'lib/na/string.rb', line 103

def dir_matches(any: [], all: [])
  matches_any(any.map(&:dir_to_rx)) && matches_all(all.map(&:dir_to_rx))
end

#dir_to_rx(distance: 2) ⇒ Object

Note:

Splits at / or :, adds variable distance between characters, joins segments with slashes and requires that last segment match last segment of target path

Convert a directory path to a regular expression

Parameters:

  • distance (defaults to: 2)

    The distance



99
100
101
# File 'lib/na/string.rb', line 99

def dir_to_rx(distance: 2)
  "#{split(%r{[/:]}).map { |comp| comp.split('').join(".{0,#{distance}}").gsub(/\*/, '[^ ]*?') }.join('.*?/.*?')}[^/]*?$"
end

#highlight_search(regexes, color: '{y}', last_color: '{xg}') ⇒ Object

Highlight search results

Parameters:

  • regexes (Array)

    The regexes for the search

  • color (String) (defaults to: '{y}')

    The highlight color template

  • last_color (String) (defaults to: '{xg}')

    Color to restore after highlight



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/na/string.rb', line 56

def highlight_search(regexes, color: '{y}', last_color: '{xg}')
  string = dup
  color = NA::Color.template(color)
  regexes.each do |rx|
    next if rx.nil?

    rx = Regexp.new(rx.wildcard_to_rx, Regexp::IGNORECASE) if rx.is_a?(String)

    string.gsub!(rx) do
      m = Regexp.last_match
      last = m.pre_match.last_color
      "#{color}#{m[0]}#{NA::Color.template(last)}"
    end
  end
  string
end

#highlight_tags(color: '{m}', value: '{y}', parens: '{m}', last_color: '{xg}') ⇒ String

Colorize @tags with ANSI escapes

Parameters:

  • color (String) (defaults to: '{m}')

    color (see #Color)

  • value (String) (defaults to: '{y}')

    The value color template

  • parens (String) (defaults to: '{m}')

    The parens color template

  • last_color (String) (defaults to: '{xg}')

    Color to restore after tag highlight

Returns:

  • (String)

    string with @tags highlighted



38
39
40
41
42
43
44
# File 'lib/na/string.rb', line 38

def highlight_tags(color: '{m}', value: '{y}', parens: '{m}', last_color: '{xg}')
  tag_color = NA::Color.template(color)
  paren_color = NA::Color.template(parens)
  value_color = NA::Color.template(value)
  gsub(/(\s|m)(@[^ ("']+)(?:(\()(.*?)(\)))?/,
       "\\1#{tag_color}\\2#{paren_color}\\3#{value_color}\\4#{paren_color}\\5#{last_color}")
end

#indent_levelNumber

Determine indentation level of line

Returns:

  • (Number)

    number of indents detected



18
19
20
21
22
23
# File 'lib/na/string.rb', line 18

def indent_level
  prefix = match(/(^[ \t]+)/)
  return 0 if prefix.nil?

  prefix[1].gsub(/  /, "\t").scan(/\t/).count
end

#last_colorString

Note:

Actually returns all escape codes, with the assumption that the result of inserting them will generate the same color as was set at the end of the string. Because you can send modifiers like dark and bold separate from color codes, only using the last code may not render the same style.

Returns the last escape sequence from a string.

Returns:

  • (String)

    All escape codes in string



85
86
87
# File 'lib/na/string.rb', line 85

def last_color
  scan(/\e\[[\d;]+m/).join('').gsub(/\e\[0m/, '')
end

#last_color_codeObject

Get the calculated ANSI color at the end of the string

Returns:

  • ANSI escape sequence to match color



138
139
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
# File 'lib/na/colors.rb', line 138

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

#matches(any: [], all: [], none: []) ⇒ Object



107
108
109
# File 'lib/na/string.rb', line 107

def matches(any: [], all: [], none: [])
  matches_any(any) && matches_all(all) && matches_none(none)
end

#normalize_colorString

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

Returns:

  • (String)

    Normalized color name



129
130
131
# File 'lib/na/colors.rb', line 129

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

#read_fileObject



5
6
7
8
9
10
11
# File 'lib/na/string.rb', line 5

def read_file
  file = File.expand_path(self)
  raise "Missing file #{file}" unless File.exist?(file)

  # IO.read(file).force_encoding('ASCII-8BIT').encode('UTF-8', invalid: :replace, undef: :replace, replace: '?')
  IO.read(file).force_encoding('utf-8')
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
# File 'lib/na/colors.rb', line 111

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

  valid_color
end

#wildcard_to_rxString

Convert wildcard characters to regular expressions

Returns:



116
117
118
# File 'lib/na/string.rb', line 116

def wildcard_to_rx
  gsub(/\./, '\\.').gsub(/\?/, '.').gsub(/\*/, '[^ ]*?')
end