Module: Howzit::StringUtils

Included in:
String
Defined in:
lib/howzit/stringutils.rb

Overview

String Extensions

Instance Method Summary collapse

Instance Method Details

#available?Boolean

Test if an executable is available on the system



210
211
212
# File 'lib/howzit/stringutils.rb', line 210

def available?
  Util.valid_command?(self)
end

#build_note?Boolean

Test if the filename matches the conditions to be a build note



11
12
13
14
15
16
17
# File 'lib/howzit/stringutils.rb', line 11

def build_note?
  return false if downcase !~ /^(howzit[^.]*|build[^.]+)/

  return false if Howzit.config.should_ignore(self)

  true
end

#cString

Shortcut for calling Color.template



82
83
84
# File 'lib/howzit/stringutils.rb', line 82

def c
  Color.template(self)
end

#extract_metadataHash

Split the content at the first top-level header and assume everything before it is metadata. Passes to

get_metadata for processing



261
262
263
264
265
266
267
268
# File 'lib/howzit/stringutils.rb', line 261

def 
  if File.exist?(self)
    leader = Util.read_file(self).split(/^#/)[0].strip
    leader.length > 0 ? leader. : {}
  else
    {}
  end
end

#format_header(opts = {}) ⇒ String

Make a fancy title line for the topic



332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/howzit/stringutils.rb', line 332

def format_header(opts = {})
  title = dup
  options = {
    hr: "\u{254C}",
    color: '{bg}',
    border: '{x}',
    mark: should_mark_iterm?
  }

  options.merge!(opts)

  case Howzit.options[:header_format]
  when :block
    Color.template("#{options[:color]}\u{258C}#{title}#{should_mark_iterm? && options[:mark] ? iterm_marker : ''}{x}")
  else
    cols = TTY::Screen.columns

    cols = Howzit.options[:wrap] if (Howzit.options[:wrap]).positive? && cols > Howzit.options[:wrap]
    title = Color.template("#{options[:border]}#{options[:hr] * 2}( #{options[:color]}#{title}#{options[:border]} )")

    tail = if should_mark_iterm?
             "#{options[:hr] * (cols - title.uncolor.length - 15)}#{options[:mark] ? iterm_marker : ''}"
           else
             options[:hr] * (cols - title.uncolor.length)
           end
    Color.template("#{title}#{tail}{x}")
  end
end

#get_metadataHash

Examine text for multimarkdown-style metadata and return key/value pairs



275
276
277
278
279
280
281
# File 'lib/howzit/stringutils.rb', line 275

def 
  data = {}
  scan(/(?mi)^(\S[\s\S]+?): ([\s\S]*?)(?=\n\S[\s\S]*?:|\Z)/).each do |m|
    data[m[0].strip.downcase] = m[1]
  end
  (data)
end

#iterm_markerString

Output an iTerm marker



322
323
324
# File 'lib/howzit/stringutils.rb', line 322

def iterm_marker
  "\e]1337;SetMark\a" if should_mark_iterm?
end

#normalize_metadata(meta) ⇒ Hash

Autocorrect some keys



290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/howzit/stringutils.rb', line 290

def (meta)
  data = {}
  meta.each do |k, v|
    case k
    when /^te?m?pl(ate)?s?$/
      data['template'] = v
    when /^req\w*$/
      data['required'] = v
    else
      data[k] = v
    end
  end
  data
end

#note_title(file, truncate = 0) ⇒ Object

Get the title of the build note (top level header)



24
25
26
27
28
29
30
31
32
33
# File 'lib/howzit/stringutils.rb', line 24

def note_title(file, truncate = 0)
  title = match(/(?:^(\S.*?)(?=\n==)|^# ?(.*?)$)/)
  title = if title
            title[1].nil? ? title[2] : title[1]
          else
            file.sub(/(\.\w+)?$/, '')
          end

  title && truncate.positive? ? title.trunc(truncate) : title
end

#preserve_escapesString

Replace slash escaped characters in a string with a zero-width space that will prevent a shell from interpreting them when output to console



42
43
44
# File 'lib/howzit/stringutils.rb', line 42

def preserve_escapes
  gsub(/\\([a-z])/, '\​\1')
end

#render_argumentsString

Render $X placeholders based on positional arguments



244
245
246
247
248
249
250
251
252
# File 'lib/howzit/stringutils.rb', line 244

def render_arguments
  return self if Howzit.arguments.nil? || Howzit.arguments.empty?

  gsub!(/\$(\d+)/) do |m|
    idx = m[1].to_i - 1
    Howzit.arguments.length > idx ? Howzit.arguments[idx] : m
  end
  gsub(/\$[@*]/, Shellwords.join(Howzit.arguments))
end

#render_template(vars) ⇒ String

Render [%variable] placeholders in a templated string



222
223
224
225
226
227
228
# File 'lib/howzit/stringutils.rb', line 222

def render_template(vars)
  vars.each do |k, v|
    gsub!(/\[%#{k}(:.*?)?\]/, v)
  end

  gsub(/\[%(.*?):(.*?)\]/, '\2')
end

#render_template!(vars) ⇒ Object

Render [%variable] placeholders in place



235
236
237
# File 'lib/howzit/stringutils.rb', line 235

def render_template!(vars)
  replace render_template(vars)
end

#should_mark_iterm?Boolean

Test if iTerm markers should be output. Requires that the $TERM_PROGRAM be iTerm and howzit is not running directives or paginating output



312
313
314
# File 'lib/howzit/stringutils.rb', line 312

def should_mark_iterm?
  ENV['TERM_PROGRAM'] =~ /^iTerm/ && !Howzit.options[:run] && !Howzit.options[:paginate]
end

#split_line(width, indent = '') ⇒ Object

Splits a line at nearest word break



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/howzit/stringutils.rb', line 188

def split_line(width, indent = '')
  line = dup
  at = line.index(/\s/)
  last_at = at

  while !at.nil? && at < width
    last_at = at
    at = line.index(/\s/, last_at + 1)
  end

  if last_at.nil?
    [indent + line[0, width], line[width, line.length]]
  else
    [indent + line[0, last_at], line[last_at + 1, line.length]]
  end
end

#to_config_value(orig_value = nil) ⇒ Object

Convert a string to a valid YAML value



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/howzit/stringutils.rb', line 53

def to_config_value(orig_value = nil)
  if orig_value
    case orig_value.class.to_s
    when /Integer/
      to_i
    when /(True|False)Class/
      self =~ /^(t(rue)?|y(es)?|1)$/i ? true : false
    else
      self
    end
  else
    case self
    when /^[0-9]+$/
      to_i
    when /^(t(rue)?|y(es)?)$/i
      true
    when /^(f(alse)?|n(o)?)$/i
      false
    else
      self
    end
  end
end

#to_rxRegexp

Convert a string to a regex object based on matching settings



92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/howzit/stringutils.rb', line 92

def to_rx
  case Howzit.options[:matching]
  when 'exact'
    /^#{self}$/i
  when 'beginswith'
    /^#{self}/i
  when 'fuzzy'
    /#{split(//).join('.*?')}/i
  else
    /#{self}/i
  end
end

#trunc(len) ⇒ Object

Truncate string to nearest word



165
166
167
168
169
170
171
# File 'lib/howzit/stringutils.rb', line 165

def trunc(len)
  split(/ /).each_with_object([]) do |x, ob|
    break ob unless ob.join(' ').length + ' '.length + x.length <= len

    ob.push(x)
  end.join(' ').strip
end

#trunc!(len) ⇒ Object

Truncate string in place (destructive)



178
179
180
# File 'lib/howzit/stringutils.rb', line 178

def trunc!(len)
  replace trunc(len)
end

#uncolorObject

Just strip out color codes when requested



106
107
108
# File 'lib/howzit/stringutils.rb', line 106

def uncolor
  gsub(/\e\[[\d;]+m/, '').gsub(/\e\]1337;SetMark/,'')
end

#wrap(width) ⇒ String

Wrap text at a specified width.

Adapted from https://github.com/pazdera/word_wrap/, copyright (c) 2014, 2015 Radek Pazdera Distributed under the MIT License



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/howzit/stringutils.rb', line 121

def wrap(width)
  width ||= 80
  output = []
  indent = ''

  text = gsub(/\t/, '  ')

  text.lines do |line|
    line.chomp! "\n"
    if line.length > width
      indent = if line.uncolor =~ /^(\s*(?:[+\-*]|\d+\.) )/
                 ' ' * Regexp.last_match[1].length
               else
                 ''
               end
      new_lines = line.split_line(width)

      while new_lines.length > 1 && new_lines[1].length + indent.length > width
        output.push new_lines[0]

        new_lines = new_lines[1].split_line(width, indent)
      end
      output += [new_lines[0], indent + new_lines[1]]
    else
      output.push line
    end
  end
  output.map!(&:rstrip)
  output.join("\n")
end

#wrap!(width) ⇒ Object

Wrap string in place (destructive)



157
158
159
# File 'lib/howzit/stringutils.rb', line 157

def wrap!(width)
  replace(wrap(width))
end