Class: String

Inherits:
Object
  • Object
show all
Includes:
Doing::Color
Defined in:
lib/doing/string.rb

Overview

String helpers

Constant Summary

Constants included from Doing::Color

Doing::Color::ATTRIBUTES, Doing::Color::ATTRIBUTE_NAMES, Doing::Color::COLORED_REGEXP

Instance Method Summary collapse

Methods included from Doing::Color

attributes, coloring=, coloring?, #support?

Instance Method Details

#add_tags(tags, remove: false) ⇒ Object



285
286
287
288
289
290
# File 'lib/doing/string.rb', line 285

def add_tags(tags, remove: false)
  title = self.dup
  tags = tags.to_tags
  tags.each { |tag| title.tag!(tag, remove: remove) }
  title
end

#add_tags!(tags, remove: false) ⇒ Object



281
282
283
# File 'lib/doing/string.rb', line 281

def add_tags!(tags, remove: false)
  replace add_tags(tags, remove: remove)
end

#cap_firstObject

Capitalize on the first character on string

Returns:

  • Capitalized string



199
200
201
202
203
# File 'lib/doing/string.rb', line 199

def cap_first
  sub(/^\w/) do |m|
    m.upcase
  end
end

#dedup_tagsObject



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/doing/string.rb', line 359

def dedup_tags
  title = dup
  tags = title.scan(/(?<=\A| )(@(\S+?)(\([^)]+\))?)(?= |\Z)/).uniq
  tags.each do |tag|
    found = false
    title.gsub!(/( |^)#{tag[1]}(\([^)]+\))?(?= |$)/) do |m|
      if found
        ''
      else
        found = true
        m
      end
    end
  end
  title
end

#dedup_tags!Object

Remove duplicate tags, leaving only first occurrence

Returns:

  • Deduplicated string



355
356
357
# File 'lib/doing/string.rb', line 355

def dedup_tags!
  replace dedup_tags
end

#highlight_tags(color = 'yellow') ⇒ String

Colorize @tags with ANSI escapes

Parameters:

  • color (String) (defaults to: 'yellow')

    color (see #Color)

Returns:

  • (String)

    string with @tags highlighted



78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/doing/string.rb', line 78

def highlight_tags(color = 'yellow')
  escapes = scan(/(\e\[[\d;]+m)[^\e]+@/)
  color = color.split(' ') unless color.is_a?(Array)
  tag_color = ''
  color.each { |c| tag_color += Doing::Color.send(c) }
  last_color = if !escapes.empty?
                 escapes[-1][0]
               else
                 Doing::Color.default
               end
  gsub(/(\s|m)(@[^ ("']+)/, "\\1#{tag_color}\\2#{Doing::Color.reset}#{last_color}")
end

#highlight_tags!(color = 'yellow') ⇒ Object

Parameters:

  • color (String) (defaults to: 'yellow')

    color (see #Color)



67
68
69
# File 'lib/doing/string.rb', line 67

def highlight_tags!(color = 'yellow')
  replace highlight_tags(color)
end

#ignore?Boolean

Test if line should be ignored

Returns:

  • (Boolean)

    line is empty or comment



96
97
98
99
# File 'lib/doing/string.rb', line 96

def ignore?
  line = self
  line =~ /^#/ || line =~ /^\s*$/
end

#is_rx?Boolean

Determines if receiver is surrounded by slashes or starts with single quote

Returns:

  • (Boolean)

    True if regex, False otherwise.



14
15
16
# File 'lib/doing/string.rb', line 14

def is_rx?
  self =~ %r{(^/.*?/$|^')}
end

#last_colorObject

Returns the last escape sequence from a string

Parameters:

  • string

    The string to examine



380
381
382
# File 'lib/doing/string.rb', line 380

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


393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/doing/string.rb', line 393

def link_urls(opt = {})
  opt[:format] ||= :html
  str = self.dup

  if :format == :markdown
    # Remove <self-linked> formatting
    str.gsub!(/<(.*?)>/) do |match|
      m = Regexp.last_match
      if m[1] =~ /^https?:/
        m[1]
      else
        match
      end
    end
  end

  # Replace qualified urls
  str.gsub!(%r{(?mi)(?<!["'\[(\\])((http|https)://)([\w\-_]+(\.[\w\-_]+)+)([\w\-.,@?^=%&amp;:/~+#]*[\w\-@^=%&amp;/~+#])?}) do |_match|
    m = Regexp.last_match
    proto = m[1].nil? ? 'http://' : ''
    case opt[:format]
    when :html
      %(<a href="#{proto}#{m[0]}" title="Link to #{m[0].sub(/^https?:\/\//, '')}">[#{m[3]}]</a>)
    when :markdown
      "[#{m[0]}](#{proto}#{m[0]})"
    else
      m[0]
    end
  end

  # Clean up unlinked <urls>
  str.gsub!(/<(\w+:.*?)>/) do |match|
    m = Regexp.last_match
    if m[1] =~ /<a href/
      match
    else
      %(<a href="#{m[1]}" title="Link to #{m[1]}">[link]</a>)
    end
  end

  str
end

Turn raw urls into HTML links

Parameters:

  • opt (Hash) (defaults to: {})

    Additional Options



389
390
391
# File 'lib/doing/string.rb', line 389

def link_urls!(opt = {})
  replace link_urls(opt)
end

#normalize_bool(default = :and) ⇒ Object



256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/doing/string.rb', line 256

def normalize_bool(default = :and)
  case self
  when /(and|all)/i
    :and
  when /(any|or)/i
    :or
  when /(not|none)/i
    :not
  else
    default.is_a?(Symbol) ? default : default.normalize_bool
  end
end

#normalize_bool!(default = :and) ⇒ Object

Convert a boolean string to a symbol

Returns:

  • Symbol :and, :or, or :not



252
253
254
# File 'lib/doing/string.rb', line 252

def normalize_bool!(default = :and)
  replace normalize_bool(default)
end

#normalize_case(default = :smart) ⇒ Object



234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/doing/string.rb', line 234

def normalize_case(default = :smart)
  case self
  when /^c/i
    :sensitive
  when /^i/i
    :ignore
  when /^s/i
    :smart
  else
    default.is_a?(Symbol) ? default : default.normalize_case
  end
end

#normalize_case!Object

Convert a case sensitivity string to a symbol

Returns:

  • Symbol :smart, :sensitive, :ignore



230
231
232
# File 'lib/doing/string.rb', line 230

def normalize_case!
  replace normalize_case
end

#normalize_order(default = 'asc') ⇒ Object



214
215
216
217
218
219
220
221
222
223
# File 'lib/doing/string.rb', line 214

def normalize_order(default = 'asc')
  case self
  when /^a/i
    'asc'
  when /^d/i
    'desc'
  else
    default
  end
end

#normalize_order!(default = 'asc') ⇒ String

Convert a sort order string to a qualified type

Returns:

  • (String)

    'asc' or 'desc'



210
211
212
# File 'lib/doing/string.rb', line 210

def normalize_order!(default = 'asc')
  replace normalize_order(default)
end

#normalize_triggerObject



273
274
275
# File 'lib/doing/string.rb', line 273

def normalize_trigger
  gsub(/\((?!\?:)/, '(?:').downcase
end

#normalize_trigger!Object



269
270
271
# File 'lib/doing/string.rb', line 269

def normalize_trigger!
  replace normalize_trigger
end

#tag(tag, value: nil, remove: false, rename_to: nil, regex: false, single: false) ⇒ Object



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/doing/string.rb', line 296

def tag(tag, value: nil, remove: false, rename_to: nil, regex: false, single: false)
  log_level = single ? :info : :debug
  title = dup
  title.chomp!
  tag = tag.sub(/^@?/, '')
  case_sensitive = tag !~ /[A-Z]/

  rx_tag = if regex
             tag.gsub(/\./, '\S')
           else
             tag.gsub(/\?/, '.').gsub(/\*/, '\S*?')
           end

  if remove || rename_to
    return title unless title =~ /#{rx_tag}(?=[ (]|$)/

    rx = Regexp.new("(^| )@#{rx_tag}(\\([^)]*\\))?(?= |$)", case_sensitive)
    if title =~ rx
      title.gsub!(rx) do
        m = Regexp.last_match
        rename_to ? "#{m[1]}@#{rename_to}#{m[2]}" : m[1]
      end

      title.dedup_tags!
      title.chomp!

      if rename_to
        f = "@#{tag}".cyan
        t = "@#{rename_to}".cyan
        Doing.logger.write(log_level, 'Tag:', %(renamed #{f} to #{t} in "#{title}"))
      else
        f = "@#{tag}".cyan
        Doing.logger.write(log_level, 'Tag:', %(removed #{f} from "#{title}"))
      end
    else
      Doing.logger.debug('Skipped:', "not tagged #{"@#{tag}".cyan}")
    end
  elsif title =~ /@#{tag}(?=[ (]|$)/
    Doing.logger.debug('Skipped:', "already tagged #{"@#{tag}".cyan}")
    return title
  else
    add = tag
    add += "(#{value})" unless value.nil?
    title.chomp!
    title += " @#{add}"

    title.dedup_tags!
    title.chomp!
    Doing.logger.write(log_level, 'Tag:', %(added #{('@' + tag).cyan} to "#{title}"))
  end

  title.gsub(/ +/, ' ')
end

#tag!(tag, value: nil, remove: false, rename_to: nil, regex: false, single: false) ⇒ Object



292
293
294
# File 'lib/doing/string.rb', line 292

def tag!(tag, value: nil, remove: false, rename_to: nil, regex: false, single: false)
  replace tag(tag, value: value, remove: remove, rename_to: rename_to, regex: regex, single: single)
end

#to_rx(distance: 3, case_type: :smart) ⇒ Regexp

Convert string to fuzzy regex. Characters in words can be separated by up to distance characters in haystack, spaces indicate unlimited distance.

/t.0,3h.0,3i.0,3s.0,3.*?w.0,3o.0,3r.0,3d/

Examples:

"this word".to_rx(2) =>

Parameters:

  • distance (Integer) (defaults to: 3)

    Allowed distance between characters

  • case_type (defaults to: :smart)

    The case type

Returns:

  • (Regexp)

    Regex pattern



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/doing/string.rb', line 32

def to_rx(distance: 3, case_type: :smart)
  case_sensitive = case case_type
                   when :smart
                     self =~ /[A-Z]/ ? true : false
                   when :sensitive
                     true
                   else
                     false
                   end

  pattern = case dup.strip
            when %r{^/.*?/$}
              sub(%r{/(.*?)/}, '\1')
            when /^'/
              sub(/^'(.*?)'?$/, '\1')
            else
              split(/ +/).map { |w| w.split('').join(".{0,#{distance}}") }.join('.*?')
            end
  Regexp.new(pattern, !case_sensitive)
end

#to_tagsObject



277
278
279
# File 'lib/doing/string.rb', line 277

def to_tags
  gsub(/ *, */, ' ').gsub(/ +/, ' ').split(/ /).sort.uniq.map { |t| t.strip.sub(/^@/, '') }
end

#truncate(len, ellipsis: '...') ⇒ Object

Truncate to nearest word

Parameters:

  • len

    The length



106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/doing/string.rb', line 106

def truncate(len, ellipsis: '...')
  return self if length <= len

  total = 0
  res = []

  split(/ /).each do |word|
    break if total + 1 + word.length > len

    total += 1 + word.length
    res.push(word)
  end
  res.join(' ') + ellipsis
end

#truncate!(len, ellipsis: '...') ⇒ Object



121
122
123
# File 'lib/doing/string.rb', line 121

def truncate!(len, ellipsis: '...')
  replace truncate(len, ellipsis: ellipsis)
end

#truncmiddle(len, ellipsis: '...') ⇒ Object

Truncate string in the middle

Parameters:

  • len

    The length

  • ellipsis (defaults to: '...')

    The ellipsis



131
132
133
134
135
136
137
138
# File 'lib/doing/string.rb', line 131

def truncmiddle(len, ellipsis: '...')
  return self if length <= len
  len -= (ellipsis.length / 2).to_i
  total = length
  half = total / 2
  cut = (total - len) / 2
  sub(/(.{#{half - cut}}).*?(.{#{half - cut}})$/, "\\1#{ellipsis}\\2")
end

#truncmiddle!(len, ellipsis: '...') ⇒ Object



140
141
142
# File 'lib/doing/string.rb', line 140

def truncmiddle!(len, ellipsis: '...')
  replace truncmiddle(len, ellipsis: ellipsis)
end

#truthy?Boolean

Test string for truthiness (0, "f", "false", "n", "no" all return false, case insensitive, otherwise true)

Returns:

  • (Boolean)

    String is truthy



58
59
60
61
62
63
64
# File 'lib/doing/string.rb', line 58

def truthy?
  if self =~ /^(0|f(alse)?|n(o)?)$/i
    false
  else
    true
  end
end

#uncolorObject

Remove color escape codes

Returns:

  • clean string



149
150
151
# File 'lib/doing/string.rb', line 149

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

#uncolor!Object



153
154
155
# File 'lib/doing/string.rb', line 153

def uncolor!
  replace uncolor
end

#wrap(len, pad: 0, indent: ' ', offset: 0, prefix: '', color: '', after: '', reset: '') ⇒ Object

Wrap string at word breaks, respecting tags

Parameters:

  • len (Integer)

    The length

  • offset (Integer) (defaults to: 0)

    (Optional) The width to pad each subsequent line

  • prefix (String) (defaults to: '')

    (Optional) A prefix to add to each line



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
190
191
192
# File 'lib/doing/string.rb', line 164

def wrap(len, pad: 0, indent: '  ', offset: 0, prefix: '', color: '', after: '', reset: '')
  last_color = color.empty? ? '' : after.last_color
  note_rx = /(?i-m)(%(?:[io]d|(?:\^[\s\S])?(?:(?:[ _t]|[^a-z0-9])?\d+)?(?:[\s\S][ _t]?)?)?note)/
  # Don't break inside of tag values
  str = gsub(/@\S+\(.*?\)/) { |tag| tag.gsub(/\s/, '%%%%') }
  words = str.split(/ /).map { |word| word.gsub(/%%%%/, ' ') }
  out = []
  line = []
  words.each do |word|
    if line.join(' ').uncolor.length + word.uncolor.length + 1 > len
      out.push(line.join(' '))
      line.clear
    end

    line << word.uncolor
  end
  out.push(line.join(' '))
  note = ''
  after.sub!(note_rx) do
    note = Regexp.last_match(0)
    ''
  end

  out[0] = format("%-#{pad}s%s%s", out[0], last_color, after)

  left_pad = ' ' * offset
  left_pad += indent
  out.map { |l| "#{left_pad}#{color}#{l}#{last_color}" }.join("\n").strip + last_color + " #{note}".chomp
end