Class: Doing::TemplateString

Inherits:
String show all
Includes:
Color
Defined in:
lib/doing/template_string.rb

Overview

Template string formatting

Constant Summary

Constants included from Color

Color::ATTRIBUTES, Color::ATTRIBUTE_NAMES, Color::COLORED_REGEXP, Color::ESCAPE_REGEX

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Color

#attributes, coloring?, #rgb, #support?, template, #uncolor

Methods inherited from String

#good?, #last_color_code, #normalize_color, #sanitize, #utf8, #valid_id?, #validate_color

Methods included from Completion::StringUtils

#ltrunc, #ltrunc!, #short_desc

Methods included from ChronifyString

#chronify, #chronify_qty, #expand_date_tags, #is_range?, #split_date_range, #time_string, #to_seconds

Methods included from StringURL

#clean_unlinked_urls, #link_urls, #link_urls!, #remove_self_links, #replace_qualified_urls

Methods included from StringTruncate

#trunc, #trunc!, #truncend, #truncend!, #truncmiddle, #truncmiddle!

Methods included from StringTransform

#cap_first, #compress, #compress!, #set_type, #simple_wrap, #titlecase, #to_p, #wrap

Methods included from StringTags

#add_at, #add_tags, #add_tags!, #dedup_tags, #dedup_tags!, #remove_at, #split_tags, #tag, #tag!, #to_tags

Methods included from StringQuery

#ignore?, #ignore_case, #rx?, #to_bool, #to_phrase_query, #to_query, #to_rx, #truthy?, #wildcard_to_rx

Methods included from StringHighlight

#highlight_search, #highlight_search!, #highlight_tags, #highlight_tags!, #last_color, #uncolor, #uncolor!

Methods included from StringNormalize

#normalize_age, #normalize_age!, #normalize_bool, #normalize_bool!, #normalize_case, #normalize_case!, #normalize_change_type, #normalize_matching, #normalize_matching!, #normalize_order, #normalize_order!, #normalize_tag_sort, #normalize_tag_sort!, #normalize_trigger, #normalize_trigger!

Constructor Details

#initialize(string, placeholders: {}, force_color: false, wrap_width: 0, color: '', tags_color: '', reset: '') ⇒ TemplateString

Returns a new instance of TemplateString.



11
12
13
14
15
16
17
18
# File 'lib/doing/template_string.rb', line 11

def initialize(string, placeholders: {}, force_color: false, wrap_width: 0, color: '', tags_color: '', reset: '')
  Color.coloring = true if force_color
  @colors = nil
  @original = string
  super(Color.reset + string)

  placeholders.each { |k, v| fill(k, v, wrap_width: wrap_width, color: color, tags_color: tags_color) }
end

Instance Attribute Details

#originalObject (readonly)

Returns the value of attribute original.



8
9
10
# File 'lib/doing/template_string.rb', line 8

def original
  @original
end

Instance Method Details

#apply_colors(color_array) ⇒ Object

Apply a color array to a string

Parameters:

  • color_array (Array)

    Array of hashes containing :name, :color, :index



88
89
90
91
92
93
94
95
# File 'lib/doing/template_string.rb', line 88

def apply_colors(color_array)
  str = dup
  color_array.reverse.each do |color|
    c = color[:color].empty? ? Color.send(color[:name]) : color[:color]
    str.insert(color[:index], c)
  end
  str
end

#coloredString

Return string with %colors replaced with escape codes

Returns:

  • (String)

    colorized string



41
42
43
44
# File 'lib/doing/template_string.rb', line 41

def colored
  reparse
  parsed_colors[:string].apply_colors(parsed_colors[:colors])
end

#colors?Boolean

Test if string contains any valid %colors

Returns:

  • (Boolean)

    True if colors, False otherwise.



25
26
27
28
29
30
# File 'lib/doing/template_string.rb', line 25

def colors?
  scan(/%([a-z]+)/).each do
    return true if Regexp.last_match(1).validate_color
  end
  false
end

#fill(placeholder, value, wrap_width: 0, color: '', tags_color: '', reset: '') ⇒ Object



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
131
132
133
134
135
136
137
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
# File 'lib/doing/template_string.rb', line 97

def fill(placeholder, value, wrap_width: 0, color: '', tags_color: '', reset: '')
  reparse
  rx = /(?mi)(?<!\\)%(?<width>-?\d+)?(?:\^(?<mchar>.))?(?:(?<ichar>[ _t]|[^a-z0-9])(?<icount>\d+))?(?<prefix>.[ _t]?)?#{placeholder.sub(/^%/, '')}(?<after>.*?)$/
  ph = raw.match(rx)

  return unless ph
  placeholder_offset = ph.begin(0)
  last_colors = parsed_colors[:colors].select { |v| v[:index] <= placeholder_offset + 4 }

  last_color = last_colors.map { |v| v[:color] }.pop(3).join('')

  sub!(rx) do
    m = Regexp.last_match

    after = m['after']

    if !value.good?
      after
    else
      pad = m['width'].to_i
      mark = m['mchar'] || ''
      if placeholder == 'shortdate' && m['width'].nil?
        pad = 13
      end
      indent = nil
      if m['ichar']
        char = m['ichar'] =~ /t/ ? "\t" : ' '
        indent = char * m['icount'].to_i
      end
      indent ||= placeholder =~ /^title/ ? '' : "\t"
      prefix = m['prefix']

      if placeholder =~ /^tags/
        prefix ||= ''
        value = value.map { |t| "#{prefix}#{t.sub(/^#{prefix}?/, '')}" }.join(' ')
        prefix = ''
      end

      if placeholder =~ /^title/
        color = last_color + color

        if wrap_width.positive? || pad.positive?
          width = pad.positive? ? pad : wrap_width

          out = value.gsub(/%/, '\%').strip.wrap(width,
                                                 pad: pad,
                                                 indent: indent,
                                                 offset: placeholder_offset,
                                                 prefix: prefix,
                                                 color: color,
                                                 after: after,
                                                 reset: reset,
                                                 pad_first: false)
          out.highlight_tags!(tags_color, last_color: color) if tags_color && !tags_color.empty?
          out
        else
          out = format("%s%s%#{pad}s%s", prefix, color, value.gsub(/%/, '\%').sub(/\s*$/, ''), after)
          out.highlight_tags!(tags_color, last_color: color) if tags_color && !tags_color.empty?
          out
        end
      elsif placeholder =~ /^note/
        if wrap_width.positive? || pad.positive?
          width = pad.positive? ? pad : wrap_width
          outstring = value.map do |l|
            if l.empty?
              '  '
            else
              line = l.gsub(/%/, '\%').strip.wrap(width, pad: pad, indent: indent, offset: 0, prefix: prefix, color: last_color, after: after, reset: reset, pad_first: true)
              line.highlight_tags!(tags_color, last_color: last_color) unless !tags_color || !tags_color.good?
              "#{line}  "
            end
          end.join("\n")
          "\n#{last_color}#{mark}#{outstring}  "
        else
          out = format("\n%s%s%s%#{pad}s%s", indent, prefix, last_color, value.join("\n#{indent}#{prefix}").gsub(/%/, '\%').sub(/\s*$/, ''), after)
          out.highlight_tags!(tags_color, last_color: last_color) if tags_color && !tags_color.empty?
          out
        end
      else
        format("%s%#{pad}s%s", prefix, value.gsub(/%/, '\%').sub(/\s*$/, ''), after)
      end
    end
  end
  @parsed_colors = parse_colors
end

#parse_colorsHash

Parse a template string for %colors and return a hash of colors and string locations

Returns:

  • (Hash)

    Uncolored string and array of colors and locations



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/doing/template_string.rb', line 64

def parse_colors
  working = dup
  color_array = []

  scan(/(?<!\\)(%((?:[fb]g?)?#[a-fA-F0-9]{6}|[a-z]+))/).each do |color|
    valid_color = color[1].validate_color
    next unless valid_color

    idx = working.match(/(?<!\\)%#{valid_color}/).begin(0)
    color = Color.attributes.include?(valid_color.to_sym) ? Color.send(valid_color) : Color.rgb(valid_color)
    color_array.push({ name: valid_color, color: color, index: idx })
    working.sub!(/(?<!\\)%#{valid_color}/, '')
  end

  { string: working, colors: color_array }
end

#parsed_colorsObject



55
56
57
# File 'lib/doing/template_string.rb', line 55

def parsed_colors
  @parsed_colors ||= parse_colors
end

#rawString

Remove all valid %colors from string

Returns:



51
52
53
# File 'lib/doing/template_string.rb', line 51

def raw
  parsed_colors[:string].uncolor
end

#reparseObject



32
33
34
# File 'lib/doing/template_string.rb', line 32

def reparse
  @parsed_colors = nil
end