Class: WWID

Inherits:
Object
  • Object
show all
Defined in:
lib/doing/wwid.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeWWID

Returns a new instance of WWID.



18
19
20
21
22
23
24
25
# File 'lib/doing/wwid.rb', line 18

def initialize
  @content = {}
  @doingrc_needs_update = false
  @default_config_file = '.doingrc'
  @interval_cache = {}
  @results = []
  @auto_tag = true
end

Instance Attribute Details

#auto_tagObject

Returns the value of attribute auto_tag.



12
13
14
# File 'lib/doing/wwid.rb', line 12

def auto_tag
  @auto_tag
end

#configObject

Returns the value of attribute config.



12
13
14
# File 'lib/doing/wwid.rb', line 12

def config
  @config
end

#config_fileObject

Returns the value of attribute config_file.



12
13
14
# File 'lib/doing/wwid.rb', line 12

def config_file
  @config_file
end

#contentObject

Returns the value of attribute content.



12
13
14
# File 'lib/doing/wwid.rb', line 12

def content
  @content
end

#current_sectionObject

Returns the value of attribute current_section.



12
13
14
# File 'lib/doing/wwid.rb', line 12

def current_section
  @current_section
end

#default_config_fileObject

Returns the value of attribute default_config_file.



12
13
14
# File 'lib/doing/wwid.rb', line 12

def default_config_file
  @default_config_file
end

#doing_fileObject

Returns the value of attribute doing_file.



12
13
14
# File 'lib/doing/wwid.rb', line 12

def doing_file
  @doing_file
end

#resultsObject

Returns the value of attribute results.



12
13
14
# File 'lib/doing/wwid.rb', line 12

def results
  @results
end

#sectionsArray

Returns section titles.

Returns:

  • (Array)

    section titles



408
409
410
# File 'lib/doing/wwid.rb', line 408

def sections
  @sections
end

#user_homeObject

Returns the value of attribute user_home.



12
13
14
# File 'lib/doing/wwid.rb', line 12

def user_home
  @user_home
end

Instance Method Details

#add_item(title, section = nil, opt = {}) ⇒ Object

Parameters:

  • title (String)

    The entry title

  • section (String) (defaults to: nil)

    The section to add to

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

    Additional Options :note, :back, :timed



538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/doing/wwid.rb', line 538

def add_item(title, section = nil, opt = {})
  section ||= @current_section
  add_section(section) unless @content.has_key?(section)
  opt[:date] ||= Time.now
  opt[:note] ||= []
  opt[:back] ||= Time.now
  opt[:timed] ||= false

  opt[:note] = [opt[:note]] if opt[:note].instance_of?(String)

  title = [title.strip.cap_first]
  title = title.join(' ')

  if @auto_tag
    title = autotag(title)
    unless @config['default_tags'].empty?
      default_tags = @config['default_tags'].map do |t|
        next if t.nil?

        dt = t.sub(/^ *@/, '').chomp
        if title =~ /@#{dt}/
          ''
        else
          " @#{dt}"
        end
      end
      default_tags.delete_if { |t| t == '' }
      title += default_tags.join(' ')
    end
  end
  title.gsub!(/ +/, ' ')
  entry = { 'title' => title.strip, 'date' => opt[:back] }
  entry['note'] = opt[:note].map(&:chomp) unless opt[:note].join('').strip == ''
  items = @content[section]['items']
  if opt[:timed]
    items.reverse!
    items.each_with_index do |i, x|
      next if i['title'] =~ / @done/

      items[x]['title'] = "#{i['title']} @done(#{opt[:back].strftime('%F %R')})"
      break
    end
    items.reverse!
  end
  items.push(entry)
  @content[section]['items'] = items
  @results.push(%(Added "#{entry['title']}" to #{section}))
end

#add_section(title) ⇒ Object

Parameters:

  • title (String)

    The new section title



417
418
419
420
# File 'lib/doing/wwid.rb', line 417

def add_section(title)
  @content[title.cap_first] = { 'original' => "#{title}:", 'items' => [] }
  @results.push(%(Added section "#{title.cap_first}"))
end

#archive(section = @current_section, options = {}) ⇒ Object

Parameters:

  • section (String) (defaults to: @current_section)

    The source section

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

    Options



2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
# File 'lib/doing/wwid.rb', line 2047

def archive(section = @current_section, options = {})
  count       = options[:keep] || 0
  destination = options[:destination] || 'Archive'
  tags        = options[:tags] || []
  bool        = options[:bool] || :and

  section = choose_section if section.nil? || section =~ /choose/i
  archive_all = section =~ /^all$/i # && !(tags.nil? || tags.empty?)
  section = guess_section(section) unless archive_all

  add_section('Archive') if destination =~ /^archive$/i && !sections.include?('Archive')

  destination = guess_section(destination)

  if sections.include?(destination) && (sections.include?(section) || archive_all)
    do_archive(section, destination, { count: count, tags: tags, bool: bool, search: options[:search], label: options[:label], before: options[:before] })
    write(doing_file)
  else
    exit_now! 'Either source or destination does not exist'
  end
end

#autotag(text) ⇒ Object

Does not repeat tags in a title, and only converts the first instance of an untagged keyword

Parameters:

  • text (String)

    The text to tag



2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
# File 'lib/doing/wwid.rb', line 2409

def autotag(text)
  return unless text
  return text unless @auto_tag

  current_tags = text.scan(/@\w+/)
  whitelisted = []
  @config['autotag']['whitelist'].each do |tag|
    next if text =~ /@#{tag}\b/i

    text.sub!(/(?<!@)(#{tag.strip})\b/i) do |m|
      m.downcase! if tag =~ /[a-z]/
      whitelisted.push("@#{m}")
      "@#{m}"
    end
  end
  tail_tags = []
  @config['autotag']['synonyms'].each do |tag, v|
    v.each do |word|
      next unless text =~ /\b#{word}\b/i

      tail_tags.push(tag) unless current_tags.include?("@#{tag}") || whitelisted.include?("@#{tag}")
    end
  end
  if @config['autotag'].key? 'transform'
    @config['autotag']['transform'].each do |tag|
      next unless tag =~ /\S+:\S+/

      rx, r = tag.split(/:/)
      r.gsub!(/\$/, '\\')
      rx.sub!(/^@/, '')
      regex = Regexp.new('@' + rx + '\b')

      matches = text.scan(regex)
      next unless matches

      matches.each do |m|
        new_tag = r
        if m.is_a?(Array)
          index = 1
          m.each do |v|
            new_tag = new_tag.gsub('\\' + index.to_s, v)
            index += 1
          end
        end
        tail_tags.push(new_tag)
      end
    end
  end
  @results.push("Whitelisted tags: #{whitelisted.join(', ')}") if whitelisted.length > 0
  if tail_tags.length > 0
    tags = tail_tags.uniq.map { |t| '@' + t }.join(' ')
    @results.push("Synonym tags: #{tags}")
    text + ' ' + tags
  else
    text
  end
end

#choose_from(options, prompt: 'Make a selection: ', multiple: false, fzf_args: []) ⇒ String

Returns The selected option.

Returns:

  • (String)

    The selected option



777
778
779
780
781
782
783
784
785
786
787
788
# File 'lib/doing/wwid.rb', line 777

def choose_from(options, prompt: 'Make a selection: ', multiple: false, fzf_args: [])
  fzf = File.join(File.dirname(__FILE__), '../helpers/fuzzyfilefinder')
  fzf_args << '-1'
  fzf_args << %(--prompt "#{prompt}")
  fzf_args << '--multi' if multiple
  header = "esc: cancel,#{multiple ? ' tab: multi-select, ctrl-a: select all,' : ''} return: confirm"
  fzf_args << %(--header "#{header}")
  res = `echo #{Shellwords.escape(options.join("\n"))}|#{fzf} #{fzf_args.join(' ')}`
  return false if res.strip.size.zero?

  res
end

#choose_sectionString

Returns The selected section name.

Returns:

  • (String)

    The selected section name



1630
1631
1632
1633
# File 'lib/doing/wwid.rb', line 1630

def choose_section
  choice = choose_from(sections.sort, prompt: 'Choose a section > ', fzf_args: ['--height=60%'])
  choice ? choice.strip : choice
end

#choose_viewString

Returns The selected view name.

Returns:

  • (String)

    The selected view name



1649
1650
1651
1652
# File 'lib/doing/wwid.rb', line 1649

def choose_view
  choice = choose_from(views.sort, prompt: 'Choose a view > ', fzf_args: ['--height=60%'])
  choice ? choice.strip : choice
end

#chronify(input) ⇒ DateTime

Returns result.

Parameters:

  • input (String)

    String to chronify

Returns:

  • (DateTime)

    result



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/doing/wwid.rb', line 349

def chronify(input)
  now = Time.now
  exit_now! "Invalid time expression #{input.inspect}" if input.to_s.strip == ''

  secs_ago = if input.match(/^(\d+)$/)
               # plain number, assume minutes
               Regexp.last_match(1).to_i * 60
             elsif (m = input.match(/^(?:(?<day>\d+)d)?(?:(?<hour>\d+)h)?(?:(?<min>\d+)m)?$/i))
               # day/hour/minute format e.g. 1d2h30m
               [[m['day'], 24 * 3600],
                [m['hour'], 3600],
                [m['min'], 60]].map { |qty, secs| qty ? (qty.to_i * secs) : 0 }.reduce(0, :+)
             end

  if secs_ago
    now - secs_ago
  else
    Chronic.parse(input, { context: :past, ambiguous_time_range: 8 })
  end
end

#chronify_qty(qty) ⇒ Integer

Returns seconds.

Parameters:

  • qty (String)

    HH:MM or XX[[XXhm]] (1d2h30m, 45m, 1.5d, 1h20m, etc.)

Returns:

  • (Integer)

    seconds



379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'lib/doing/wwid.rb', line 379

def chronify_qty(qty)
  minutes = 0
  case qty.strip
  when /^(\d+):(\d\d)$/
    minutes += Regexp.last_match(1).to_i * 60
    minutes += Regexp.last_match(2).to_i
  when /^(\d+(?:\.\d+)?)([hmd])?$/
    amt = Regexp.last_match(1)
    type = Regexp.last_match(2).nil? ? 'm' : Regexp.last_match(2)

    minutes = case type.downcase
              when 'm'
                amt.to_i
              when 'h'
                (amt.to_f * 60).round
              when 'd'
                (amt.to_f * 60 * 24).round
              else
                minutes
              end
  end
  minutes * 60
end

#colorsString

Returns ANSI escape sequence.

Returns:

  • (String)

    ANSI escape sequence



2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
# File 'lib/doing/wwid.rb', line 2154

def colors
  color = {}
  color['black'] = "\033[0;0;30m"
  color['red'] = "\033[0;0;31m"
  color['green'] = "\033[0;0;32m"
  color['yellow'] = "\033[0;0;33m"
  color['blue'] = "\033[0;0;34m"
  color['magenta'] = "\033[0;0;35m"
  color['cyan'] = "\033[0;0;36m"
  color['white'] = "\033[0;0;37m"
  color['bgblack'] = "\033[40m"
  color['bgred'] = "\033[41m"
  color['bggreen'] = "\033[42m"
  color['bgyellow'] = "\033[43m"
  color['bgblue'] = "\033[44m"
  color['bgmagenta'] = "\033[45m"
  color['bgcyan'] = "\033[46m"
  color['bgwhite'] = "\033[47m"
  color['boldblack'] = "\033[1;30m"
  color['boldred'] = "\033[1;31m"
  color['boldgreen'] = "\033[0;1;32m"
  color['boldyellow'] = "\033[0;1;33m"
  color['boldblue'] = "\033[0;1;34m"
  color['boldmagenta'] = "\033[0;1;35m"
  color['boldcyan'] = "\033[0;1;36m"
  color['boldwhite'] = "\033[0;1;37m"
  color['boldbgblack'] = "\033[1;40m"
  color['boldbgred'] = "\033[1;41m"
  color['boldbggreen'] = "\033[1;42m"
  color['boldbgyellow'] = "\033[1;43m"
  color['boldbgblue'] = "\033[1;44m"
  color['boldbgmagenta'] = "\033[1;45m"
  color['boldbgcyan'] = "\033[1;46m"
  color['boldbgwhite'] = "\033[1;47m"
  color['softpurple'] = "\033[0;35;40m"
  color['hotpants'] = "\033[7;34;40m"
  color['knightrider'] = "\033[7;30;40m"
  color['flamingo'] = "\033[7;31;47m"
  color['yeller'] = "\033[1;37;43m"
  color['whiteboard'] = "\033[1;30;47m"
  color['default'] = "\033[0;39m"
  color
end

#configure(opt = {}) ⇒ Object

Parameters:

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

    Additional Options



85
86
87
88
89
90
91
92
93
94
95
96
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
# File 'lib/doing/wwid.rb', line 85

def configure(opt = {})
  @timers = {}
  @recorded_items = []
  opt[:ignore_local] ||= false

  @config_file ||= File.join(@user_home, @default_config_file)

  read_config({ ignore_local: opt[:ignore_local] })

  @config = {} if @config.nil?

  @config['autotag'] ||= {}
  @config['autotag']['whitelist'] ||= []
  @config['autotag']['synonyms'] ||= {}
  @config['doing_file'] ||= '~/what_was_i_doing.md'
  @config['current_section'] ||= 'Currently'
  @config['config_editor_app'] ||= nil
  @config['editor_app'] ||= nil

  @config['html_template'] ||= {}
  @config['html_template']['haml'] ||= nil
  @config['html_template']['css'] ||= nil

  @config['templates'] ||= {}
  @config['templates']['default'] ||= {
    'date_format' => '%Y-%m-%d %H:%M',
    'template' => '%date | %title%note',
    'wrap_width' => 0
  }
  @config['templates']['today'] ||= {
    'date_format' => '%_I:%M%P',
    'template' => '%date: %title %interval%note',
    'wrap_width' => 0
  }
  @config['templates']['last'] ||= {
    'date_format' => '%-I:%M%P on %a',
    'template' => '%title (at %date)%odnote',
    'wrap_width' => 88
  }
  @config['templates']['recent'] ||= {
    'date_format' => '%_I:%M%P',
    'template' => '%shortdate: %title (%section)',
    'wrap_width' => 88,
    'count' => 10
  }
  @config['views'] ||= {
    'done' => {
      'date_format' => '%_I:%M%P',
      'template' => '%date | %title%note',
      'wrap_width' => 0,
      'section' => 'All',
      'count' => 0,
      'order' => 'desc',
      'tags' => 'done complete cancelled',
      'tags_bool' => 'OR'
    },
    'color' => {
      'date_format' => '%F %_I:%M%P',
      'template' => '%boldblack%date %boldgreen| %boldwhite%title%default%note',
      'wrap_width' => 0,
      'section' => 'Currently',
      'count' => 10,
      'order' => 'asc'
    }
  }
  @config['marker_tag'] ||= 'flagged'
  @config['marker_color'] ||= 'red'
  @config['default_tags'] ||= []
  @config['tag_sort'] ||= 'time'

  @current_section = config['current_section']
  @default_template = config['templates']['default']['template']
  @default_date_format = config['templates']['default']['date_format']

  @config[:include_notes] ||= true

  # if ENV['DOING_DEBUG'].to_i == 3
  #   if @config['default_tags'].length > 0
  #     exit_now! "DEFAULT CONFIG CHANGED"
  #   end
  # end

  File.open(@config_file, 'w') { |yf| YAML.dump(@config, yf) } unless File.exist?(@config_file)

  @config = @local_config.deep_merge(@config)

  @current_section = @config['current_section']
  @default_template = @config['templates']['default']['template']
  @default_date_format = @config['templates']['default']['date_format']
end

#create(filename = nil) ⇒ Object



257
258
259
260
261
262
263
264
# File 'lib/doing/wwid.rb', line 257

def create(filename = nil)
  filename = @doing_file if filename.nil?
  return if File.exist?(filename) && File.stat(filename).size.positive?

  File.open(filename, 'w+') do |f|
    f.puts "#{@current_section}:"
  end
end

#css_templateString

Returns CSS template.

Returns:



250
251
252
# File 'lib/doing/wwid.rb', line 250

def css_template
  IO.read(File.join(File.dirname(__FILE__), '../templates/doing.css'))
end

#dedup(items, no_overlap = false) ⇒ Object



603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/doing/wwid.rb', line 603

def dedup(items, no_overlap = false)

  combined = []
  @content.each do |_k, v|
    combined += v['items']
  end

  items.delete_if do |item|
    duped = false
    combined.each do |comp|
      duped = no_overlap ? overlapping_time?(item, comp) : same_time?(item, comp)
      break if duped
    end
    # warn "Skipping overlapping entry: #{item['title']}" if duped
    duped
  end
end

#delete_item(old_item) ⇒ Object

Parameters:

  • old_item


1235
1236
1237
1238
1239
1240
1241
1242
# File 'lib/doing/wwid.rb', line 1235

def delete_item(old_item)
  section = old_item['section']

  section_items = @content[section]['items']
  deleted = section_items.delete(old_item)
  @results.push("Entry deleted: #{deleted['title']}")
  @content[section]['items'] = section_items
end

#do_archive(sect, destination, opt = {}) ⇒ Object

Parameters:

  • section (String)

    The source section

  • destination (String)

    The destination section

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

    Additional Options



2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
# File 'lib/doing/wwid.rb', line 2076

def do_archive(sect, destination, opt = {})
  count = opt[:count] || 0
  tags  = opt[:tags] || []
  bool  = opt[:bool] || :and
  label = opt[:label] || true

  if sect =~ /^all$/i
    all_sections = sections.dup
    all_sections.delete(destination)
  else
    all_sections = [sect]
  end

  counter = 0

  all_sections.each do |section|
    items = @content[section]['items'].dup

    moved_items = []
    if !tags.empty? || opt[:search] || opt[:before]
      if opt[:before]
        time_string = opt[:before]
        time_string += ' 12am' if time_string !~ /(\d+:\d+|\d+[ap])/
        cutoff = chronify(time_string)
      end

      items.delete_if do |item|
        if ((!tags.empty? && item.has_tags?(tags, bool)) || (opt[:search] && item.matches_search?(opt[:search].to_s)) || (opt[:before] && item['date'] < cutoff))
          moved_items.push(item)
          counter += 1
          true
        else
          false
        end
      end
      moved_items.each do |item|
        if label && section != @current_section
          item['title'] =
            item['title'].sub(/(?:@from\(.*?\))?(.*)$/, "\\1 @from(#{section})")
        end
      end

      @content[section]['items'] = items
      @content[destination]['items'].concat(moved_items)
      @results.push("Archived #{moved_items.length} items from #{section} to #{destination}")
    else
      count = items.length if items.length < count

      items.map! do |item|
        if label && section != @current_section
          item['title'] =
            item['title'].sub(/(?:@from\(.*?\))?(.*)$/, "\\1 @from(#{section})")
        end
        item
      end

      if items.count > count
        @content[destination]['items'].concat(items[count..-1])
      else
        @content[destination]['items'].concat(items)
      end

      @content[section]['items'] = if count.zero?
                                     []
                                   else
                                     items[0..count - 1]
                                   end

      @results.push("Archived #{items.length - count} items from #{section} to #{destination}")
    end
  end
end

#edit_last(section: 'All', options: {}) ⇒ Object

Parameters:

  • section (String) (defaults to: 'All')

    The section, default “All”



1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
# File 'lib/doing/wwid.rb', line 1326

def edit_last(section: 'All', options: {})
  section = guess_section(section)

  if section =~ /^all$/i
    items = []
    @content.each do |_k, v|
      items.concat(v['items'])
    end
    # section = combined['items'].dup.sort_by { |item| item['date'] }.reverse[0]['section']
  else
    items = @content[section]['items']
  end

  items = items.sort_by { |item| item['date'] }.reverse

  idx = nil

  if options[:tag] && !options[:tag].empty?
    items.each_with_index do |item, i|
      if item.has_tags?(options[:tag], options[:tag_bool])
        idx = i
        break
      end
    end
  elsif options[:search]
    items.each_with_index do |item, i|
      if item.matches_search?(options[:search])
        idx = i
        break
      end
    end
  else
    idx = 0
  end

  if idx.nil?
    @results.push('No entries found')
    return
  end

  section = items[idx]['section']

  section_items = @content[section]['items']
  s_idx = section_items.index(items[idx])

  current_item = section_items[s_idx]['title']
  old_note = section_items[s_idx]['note'] ? section_items[s_idx]['note'].map(&:strip).join("\n") : nil
  current_item += "\n#{old_note}" unless old_note.nil?
  new_item = fork_editor(current_item)
  title, note = format_input(new_item)

  if title.nil? || title.empty?
    @results.push('No content provided')
  elsif title == section_items[s_idx]['title'] && note == old_note
    @results.push('No change in content')
  else
    section_items[s_idx]['title'] = title
    section_items[s_idx]['note'] = note
    @results.push("Entry edited: #{section_items[s_idx]['title']}")
    @content[section]['items'] = section_items
    write(@doing_file)
  end
end

#find_local_configString

Returns A file path.

Returns:



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/doing/wwid.rb', line 32

def find_local_config
  config = {}
  dir = Dir.pwd

  local_config_files = []

  while dir != '/' && (dir =~ %r{[A-Z]:/}).nil?
    local_config_files.push(File.join(dir, @default_config_file)) if File.exist? File.join(dir, @default_config_file)

    dir = File.dirname(dir)
  end

  local_config_files
end

#fork_editor(input = '') ⇒ Object

Parameters:

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

    Text input for editor



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/doing/wwid.rb', line 271

def fork_editor(input = '')
  tmpfile = Tempfile.new(['doing', '.md'])

  File.open(tmpfile.path, 'w+') do |f|
    f.puts input
    f.puts "\n# The first line is the entry title, any lines after that are added as a note"
  end

  pid = Process.fork { system("$EDITOR #{tmpfile.path}") }

  trap('INT') do
    begin
      Process.kill(9, pid)
    rescue StandardError
      Errno::ESRCH
    end
    tmpfile.unlink
    tmpfile.close!
    exit 0
  end

  Process.wait(pid)

  begin
    if $?.exitstatus == 0
      input = IO.read(tmpfile.path)
    else
      exit_now! 'Cancelled'
    end
  ensure
    tmpfile.close
    tmpfile.unlink
  end

  input.split(/\n/).delete_if {|line| line =~ /^#/ }.join("\n")
end

#format_input(input) ⇒ Array

Returns [(String)title, (Array)note].

Parameters:

  • input (String)

    The string to parse

Returns:

  • (Array)
    (String)title, (Array)note


315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/doing/wwid.rb', line 315

def format_input(input)
  exit_now! 'No content in entry' if input.nil? || input.strip.empty?

  input_lines = input.split(/[\n\r]+/).delete_if {|line| line =~ /^#/ || line =~ /^\s*$/ }
  title = input_lines[0]&.strip
  exit_now! 'No content in first line' if title.nil? || title.strip.empty?

  note = input_lines.length > 1 ? input_lines[1..-1] : []
  # If title line ends in a parenthetical, use that as the note
  if note.empty? && title =~ /\s+\(.*?\)$/
    title.sub!(/\s+\((.*?)\)$/) do
      m = Regexp.last_match
      note.push(m[1])
      ''
    end
  end

  note.map!(&:strip)
  note.delete_if { |line| line =~ /^\s*$/ || line =~ /^#/ }

  [title, note]
end

#get_view(title) ⇒ Object

Parameters:

  • title (String)

    The title of the view to retrieve



1659
1660
1661
1662
1663
# File 'lib/doing/wwid.rb', line 1659

def get_view(title)
  return @config['views'][title] if @config['views'].has_key?(title)

  false
end

#guess_section(frag, guessed: false) ⇒ Object

Parameters:

  • frag (String)

    The user-provided string

  • guessed (Boolean) (defaults to: false)

    already guessed and failed



428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'lib/doing/wwid.rb', line 428

def guess_section(frag, guessed: false)
  return 'All' if frag =~ /^all$/i
  frag ||= @current_section
  sections.each { |section| return section.cap_first if frag.downcase == section.downcase }
  section = false
  re = frag.split('').join('.*?')
  sections.each do |sect|
    next unless sect =~ /#{re}/i

    warn "Assuming you meant #{sect}"
    section = sect
    break
  end
  unless section || guessed
    alt = guess_view(frag, true)
    exit_now! "Did you mean `doing view #{alt}`?" if alt

    res = yn("Section #{frag} not found, create it", default_response: false)

    if res
      add_section(frag.cap_first)
      write(@doing_file)
      return frag.cap_first
    end

    exit_now! "Unknown section: #{frag}"
  end
  section ? section.cap_first : guessed
end

#guess_view(frag, guessed = false) ⇒ Object

Parameters:

  • frag (String)

    The user-provided string

  • guessed (Boolean) (defaults to: false)

    already guessed



509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'lib/doing/wwid.rb', line 509

def guess_view(frag, guessed = false)
  views.each { |view| return view if frag.downcase == view.downcase }
  view = false
  re = frag.split('').join('.*?')
  views.each do |v|
    next unless v =~ /#{re}/i

    warn "Assuming you meant #{v}"
    view = v
    break
  end
  unless view || guessed
    alt = guess_section(frag, guessed: true)
    if alt
      exit_now! "Did you mean `doing show #{alt}`?"
    else
      exit_now! "Unknown view: #{frag}"
    end
  end
  view
end

#haml_templateString

Returns HAML template.

Returns:



241
242
243
# File 'lib/doing/wwid.rb', line 241

def haml_template
  IO.read(File.join(File.dirname(__FILE__), '../templates/doing.haml'))
end

#import_timing(path, opt = {}) ⇒ Object

Parameters:

  • path (String)

    Path to JSON report file

  • section (String)

    The section to add to

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

    Additional Options



628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
# File 'lib/doing/wwid.rb', line 628

def import_timing(path, opt = {})
  section = opt[:section] || @current_section
  opt[:no_overlap] ||= false
  opt[:autotag] ||= @auto_tag

  add_section(section) unless @content.has_key?(section)

  add_tags = opt[:tag] ? opt[:tag].split(/[ ,]+/).map { |t| t.sub(/^@?/, '@') }.join(' ') : ''
  prefix = opt[:prefix] ? opt[:prefix] : '[Timing.app]'
  exit_now! "File not found" unless File.exist?(File.expand_path(path))

  data = JSON.parse(IO.read(File.expand_path(path)))
  new_items = []
  data.each do |entry|
    # Only process task entries
    next if entry.key?('activityType') && entry['activityType'] != 'Task'
    # Only process entries with a start and end date
    next unless entry.key?('startDate') && entry.key?('endDate')

    # Round down seconds and convert UTC to local time
    start_time = Time.parse(entry['startDate'].sub(/:\d\dZ$/, ':00Z')).getlocal
    end_time = Time.parse(entry['endDate'].sub(/:\d\dZ$/, ':00Z')).getlocal
    next unless start_time && end_time

    tags = entry['project'].split(/ ▸ /).map {|proj| proj.gsub(/[^a-z0-9]+/i, '').downcase }
    title = "#{prefix} "
    title += entry.key?('activityTitle') && entry['activityTitle'] != '(Untitled Task)' ? entry['activityTitle'] : 'Working on'
    tags.each do |tag|
      if title =~ /\b#{tag}\b/i
        title.sub!(/\b#{tag}\b/i, "@#{tag}")
      else
        title += " @#{tag}"
      end
    end
    title = autotag(title) if opt[:autotag]
    title += " @done(#{end_time.strftime('%Y-%m-%d %H:%M')})"
    title.gsub!(/ +/, ' ')
    title.strip!
    new_entry = { 'title' => title, 'date' => start_time, 'section' => section }
    new_entry['note'] = entry['notes'].split(/\n/).map(&:chomp) if entry.key?('notes')
    new_items.push(new_entry)
  end
  total = new_items.count
  new_items = dedup(new_items, opt[:no_overlap])
  dups = total - new_items.count
  @results.push(%(Skipped #{dups} items with overlapping times)) if dups > 0
  @content[section]['items'].concat(new_items)
  @results.push(%(Imported #{new_items.count} items to #{section}))
end

#init_doing_file(path = nil) ⇒ Object

Parameters:

  • path (String) (defaults to: nil)

    Override path to a doing file, optional



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/doing/wwid.rb', line 181

def init_doing_file(path = nil)
  @doing_file = File.expand_path(@config['doing_file'])

  input = path

  if input.nil?
    create(@doing_file) unless File.exist?(@doing_file)
    input = IO.read(@doing_file)
    input = input.force_encoding('utf-8') if input.respond_to? :force_encoding
  elsif File.exist?(File.expand_path(input)) && File.file?(File.expand_path(input)) && File.stat(File.expand_path(input)).size.positive?
    @doing_file = File.expand_path(input)
    input = IO.read(File.expand_path(input))
    input = input.force_encoding('utf-8') if input.respond_to? :force_encoding
  elsif input.length < 256
    @doing_file = File.expand_path(input)
    create(input)
    input = IO.read(File.expand_path(input))
    input = input.force_encoding('utf-8') if input.respond_to? :force_encoding
  end

  @other_content_top = []
  @other_content_bottom = []

  section = 'Uncategorized'
  lines = input.split(/[\n\r]/)
  current = 0

  lines.each do |line|
    next if line =~ /^\s*$/

    if line =~ /^(\S[\S ]+):\s*(@\S+\s*)*$/
      section = Regexp.last_match(1)
      @content[section] = {}
      @content[section]['original'] = line
      @content[section]['items'] = []
      current = 0
    elsif line =~ /^\s*- (\d{4}-\d\d-\d\d \d\d:\d\d) \| (.*)/
      date = Time.parse(Regexp.last_match(1))
      title = Regexp.last_match(2)
      @content[section]['items'].push({ 'title' => title, 'date' => date, 'section' => section })
      current += 1
    elsif current.zero?
      # if content[section]['items'].length - 1 == current
      @other_content_top.push(line)
    elsif line =~ /^\S/
      @other_content_bottom.push(line)
    else
      @content[section]['items'][current - 1]['note'] = [] unless @content[section]['items'][current - 1].key? 'note'

      @content[section]['items'][current - 1]['note'].push(line.chomp)
      # end
    end
  end
end

#interactive(opt = {}) ⇒ Object

Parameters:

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

    Additional options



795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
# File 'lib/doing/wwid.rb', line 795

def interactive(opt = {})
  fzf = File.join(File.dirname(__FILE__), '../helpers/fuzzyfilefinder')

  section = opt[:section] ? guess_section(opt[:section]) : 'All'


  if section =~ /^all$/i
    combined = { 'items' => [] }
    @content.each do |_k, v|
      combined['items'] += v['items']
    end
    items = combined['items'].dup.sort_by { |item| item['date'] }.reverse
  else
    items = @content[section]['items']
  end


  options = items.map.with_index do |item, i|
    out = [
      i,
      ') ',
      item['date'],
      ' | ',
      item['title']
    ]
    if opt[:section] =~ /^all/i
      out.concat([
        ' (',
        item['section'],
        ') '
      ])
    end
    out.join('')
  end
  fzf_args = [
    %(--header="Arrows: navigate, tab: mark for selection, ctrl-a: select all, enter: commit"),
    %(--prompt="Select entries to act on > "),
    '-1',
    '-m',
    '--bind ctrl-a:select-all',
    %(-q "#{opt[:query]}")
  ]
  res = `echo #{Shellwords.escape(options.join("\n"))}|#{fzf} #{fzf_args.join(' ')}`
  selected = []
  res.split(/\n/).each do |item|
    idx = item.match(/^(\d+)\)/)[1].to_i
    selected.push(items[idx])
  end

  if selected.empty?
    @results.push("No selection")
    return
  end

  actions = i[editor delete tag flag finish cancel tag archive output save_to]
  has_action = false
  actions.each do |a|
    if opt[a]
      has_action = true
      break
    end
  end

  unless has_action
    choice = choose_from([
                           'add tag',
                           'remove tag',
                           'cancel',
                           'delete',
                           'finish',
                           'flag',
                           'archive',
                           'move',
                           'edit',
                           'output formatted'
                         ],
                         prompt: 'What do you want to do with the selected items? > ',
                         multiple: true,
                         fzf_args: ['--height=60%', '--tac', '--no-sort'])
    return unless choice

    to_do = choice.strip.split(/\n/)
    to_do.each do |action|
      case action
      when /(add|remove) tag/
        type = action =~ /^add/ ? 'add' : 'remove'
        if opt[:tag]
          warn "'add tag' and 'remove tag' can not be used together"
          Process.exit 1
        end
        print "#{colors['yellow']}Tag to #{type}: #{colors['reset']}"
        tag = STDIN.gets
        return if tag =~ /^ *$/
        opt[:tag] = tag.strip.sub(/^@/, '')
        opt[:remove] = true if type == 'remove'
      when /output formatted/
        output_format = choose_from(%w[doing taskpaper json timeline html csv].sort, prompt: 'Which output format? > ', fzf_args: ['--height=60%', '--tac', '--no-sort'])
        return if tag =~ /^ *$/
        opt[:output] = output_format.strip
        res = opt[:force] ? false : yn('Save to file?', default_response: 'n')
        if res
          print "#{colors['yellow']}File path/name: #{colors['reset']}"
          filename = STDIN.gets.strip
          return if filename.empty?
          opt[:save_to] = filename
        end
      when /archive/
        opt[:archive] = true
      when /delete/
        opt[:delete] = true
      when /edit/
        opt[:editor] = true
      when /finish/
        opt[:finish] = true
      when /cancel/
        opt[:cancel] = true
      when /move/
        section = choose_section.strip
        opt[:move] = section.strip unless section =~ /^ *$/
      when /flag/
        opt[:flag] = true
      end
    end
  end

  if opt[:delete]
    res = opt[:force] ? true : yn("Delete #{selected.size} items?", default_response: 'y')
    if res
      selected.each { |item| delete_item(item) }
      write(@doing_file)
    end
    return
  end

  if opt[:flag]
    tag = @config['marker_tag'] || 'flagged'
    selected.map! do |item|
      if opt[:remove]
        untag_item(item, tag)
      else
        tag_item(item, tag, date: false)
      end
    end
  end

  if opt[:finish] || opt[:cancel]
    tag = 'done'
    selected.map! do |item|
      if opt[:remove]
        untag_item(item, tag)
      else
        tag_item(item, tag, date: !opt[:cancel])
      end
    end
  end

  if opt[:tag]
    tag = opt[:tag]
    selected.map! do |item|
      if opt[:remove]
        untag_item(item, tag)
      else
        tag_item(item, tag, date: false)
      end
    end
  end

  if opt[:archive] || opt[:move]
    section = opt[:archive] ? 'Archive' : guess_section(opt[:move])
    selected.map! {|item| move_item(item, section) }
  end

  write(@doing_file)

  if opt[:editor]

    editable_items = []

    selected.each do |item|
      editable = "#{item['date']} | #{item['title']}"
      old_note = item['note'] ? item['note'].map(&:strip).join("\n") : nil
      editable += "\n#{old_note}" unless old_note.nil?
      editable_items << editable
    end
    divider = "\n-----------\n"
    input = editable_items.map(&:strip).join(divider) + "\n\n# You may delete entries, but leave all divider lines in place"

    new_items = fork_editor(input).split(/#{divider}/)

    new_items.each_with_index do |new_item, i|

      input_lines = new_item.split(/[\n\r]+/).delete_if {|line| line =~ /^#/ || line =~ /^\s*$/ }
      title = input_lines[0]&.strip

      if title.nil? || title =~ /^#{divider.strip}$/ || title.strip.empty?
        delete_item(selected[i])
      else
        note = input_lines.length > 1 ? input_lines[1..-1] : []

        note.map!(&:strip)
        note.delete_if { |line| line =~ /^\s*$/ || line =~ /^#/ }

        date = title.match(/^([\d\-: ]+) \| /)[1]
        title.sub!(/^([\d\-: ]+) \| /, '')

        item = selected[i].dup
        item['title'] = title
        item['note'] = note
        item['date'] = Time.parse(date) || selected[i]['date']
        update_item(selected[i], item)
      end
    end

    write(@doing_file)
  end

  if opt[:output]
    selected.map! do |item|
      item['title'] = "#{item['title']} @project(#{item['section']})"
      item
    end

    @content = { 'Export' => { 'original' => 'Export:', 'items' => selected } }
    options = { section: 'Export' }

    case opt[:output]
    when /doing/
      options[:template] = '- %date | %title%note'
    when /taskpaper/
      options[:template] = '- %title @date(%date)%note'
    else
      options[:output] = opt[:output]
    end

    output = list_section(options)

    if opt[:save_to]
      file = File.expand_path(opt[:save_to])
      if File.exist?(file)
        # Create a backup copy for the undo command
        FileUtils.cp(file, "#{file}~")
      end

      File.open(file, 'w+') do |f|
        f.puts output
      end

      @results.push("Export saved to #{file}")
    else
      puts output
    end
  end
end

#last(times: true, section: nil, options: {}) ⇒ Object

Parameters:

  • times (Bool) (defaults to: true)

    Show times

  • section (String) (defaults to: nil)

    Section to pull from, default Currently



2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
# File 'lib/doing/wwid.rb', line 2292

def last(times: true, section: nil, options: {})
  section = section.nil? || section =~ /all/i ? 'All' : guess_section(section)
  cfg = @config['templates']['last']

  opts = {
    section: section,
    wrap_width: cfg['wrap_width'],
    count: 1,
    format: cfg['date_format'],
    template: cfg['template'],
    times: times
  }

  if options[:tag]
    opts[:tag_filter] = {
      'tags' => options[:tag],
      'bool' => options[:tag_bool]
    }
  end

  opts[:search] = options[:search] if options[:search]

  list_section(opts)
end

#last_entry(opt = {}) ⇒ Object

Parameters:

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

    Additional Options



737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
# File 'lib/doing/wwid.rb', line 737

def last_entry(opt = {})
  opt[:tag_bool] ||= :and
  opt[:section] ||= @current_section

  sec_arr = []

  if opt[:section].nil?
    sec_arr = [@current_section]
  elsif opt[:section].instance_of?(String)
    if opt[:section] =~ /^all$/i
      combined = { 'items' => [] }
      @content.each do |_k, v|
        combined['items'] += v['items']
      end
      items = combined['items'].dup.sort_by { |item| item['date'] }.reverse
      sec_arr.push(items[0]['section'])
    else
      sec_arr = [guess_section(opt[:section])]
    end
  end

  all_items = []
  sec_arr.each do |section|
    all_items.concat(@content[section]['items'].dup) if @content.key?(section)
  end

  if opt[:tag]&.length
    all_items.select! { |item| item.has_tags?(opt[:tag], opt[:tag_bool]) }
  elsif opt[:search]&.length
    all_items.select! { |item| item.matches_search?(opt[:search]) }
  end

  all_items.max_by { |item| item['date'] }
end

#last_note(section = 'All') ⇒ Object

Parameters:

  • section (String) (defaults to: 'All')

    The section to retrieve from, default All



684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
# File 'lib/doing/wwid.rb', line 684

def last_note(section = 'All')
  section = guess_section(section)
  if section =~ /^all$/i
    combined = { 'items' => [] }
    @content.each do |_k, v|
      combined['items'] += v['items']
    end
    section = combined['items'].dup.sort_by { |item| item['date'] }.reverse[0]['section']
  end

  exit_now! "Section #{section} not found" unless @content.key?(section)

  last_item = @content[section]['items'].dup.sort_by { |item| item['date'] }.reverse[0]
  warn "Editing note for #{last_item['title']}"
  note = ''
  note = last_item['note'].map(&:strip).join("\n") unless last_item['note'].nil?
  "#{last_item['title']}\n# EDIT BELOW THIS LINE ------------\n#{note}"
end

#list_date(dates, section, times = nil, output = nil, opt = {}) ⇒ Object

Parameters:

  • dates (Array)
    start, end
  • section (String)

    The section

  • times (Bool) (defaults to: nil)

    Show times

  • output (String) (defaults to: nil)

    Output format

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

    Additional Options



2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
# File 'lib/doing/wwid.rb', line 2237

def list_date(dates, section, times = nil, output = nil, opt = {})
  opt[:totals] ||= false
  opt[:sort_tags] ||= false
  section = guess_section(section)
  # :date_filter expects an array with start and end date
  dates = [dates, dates] if dates.instance_of?(String)

  list_section({ section: section, count: 0, order: 'asc', date_filter: dates, times: times,
                 output: output, totals: opt[:totals], sort_tags: opt[:sort_tags] })
end

#list_section(opt = {}) ⇒ Object

Parameters:

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

    Additional Options



1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
# File 'lib/doing/wwid.rb', line 1671

def list_section(opt = {})
  opt[:count] ||= 0
  count = opt[:count] - 1
  opt[:age] ||= 'newest'
  opt[:date_filter] ||= []
  opt[:format] ||= @default_date_format
  opt[:only_timed] ||= false
  opt[:order] ||= 'desc'
  opt[:search] ||= false
  opt[:section] ||= nil
  opt[:sort_tags] ||= false
  opt[:tag_filter] ||= false
  opt[:tag_order] ||= 'asc'
  opt[:tags_color] ||= false
  opt[:template] ||= @default_template
  opt[:times] ||= false
  opt[:today] ||= false
  opt[:totals] ||= false

  # opt[:highlight] ||= true
  section = ''
  if opt[:section].nil?
    section = choose_section
    opt[:section] = @content[section]
  elsif opt[:section].instance_of?(String)
    if opt[:section] =~ /^all$/i
      combined = { 'items' => [] }
      @content.each do |_k, v|
        combined['items'] += v['items']
      end
      section = if opt[:tag_filter] && opt[:tag_filter]['bool'].normalize_bool != :not
                  opt[:tag_filter]['tags'].map do |tag|
                    "@#{tag}"
                  end.join(' + ')
                else
                  'doing'
                end
      opt[:section] = combined
    else
      section = guess_section(opt[:section])
      opt[:section] = @content[section]
    end
  end

  exit_now! 'Invalid section object' unless opt[:section].instance_of? Hash

  items = opt[:section]['items'].sort_by { |item| item['date'] }

  if opt[:date_filter].length == 2
    start_date = opt[:date_filter][0]
    end_date = opt[:date_filter][1]
    items.keep_if do |item|
      if end_date
        item['date'] >= start_date && item['date'] <= end_date
      else
        item['date'].strftime('%F') == start_date.strftime('%F')
      end
    end
  end

  if opt[:tag_filter] && !opt[:tag_filter]['tags'].empty?
    items.select! { |item| item.has_tags?(opt[:tag_filter]['tags'], opt[:tag_filter]['bool']) }
  end

  if opt[:search]
    items.keep_if {|item| item.matches_search?(opt[:search]) }
  end

  if opt[:only_timed]
    items.delete_if do |item|
      get_interval(item, record: false) == false
    end
  end

  if opt[:before]
    time_string = opt[:before]
    time_string += ' 12am' if time_string !~ /(\d+:\d+|\d+[ap])/
    cutoff = chronify(time_string)
    if cutoff
      items.delete_if { |item| item['date'] >= cutoff }
    end
  end

  if opt[:after]
    time_string = opt[:after]
    time_string += ' 11:59pm' if time_string !~ /(\d+:\d+|\d+[ap])/
    cutoff = chronify(time_string)
    if cutoff
      items.delete_if { |item| item['date'] <= cutoff }
    end
  end

  if opt[:today]
    items.delete_if do |item|
      item['date'] < Date.today.to_time
    end.reverse!
    section = Time.now.strftime('%A, %B %d')
  elsif opt[:yesterday]
    items.delete_if do |item|
      item['date'] <= Date.today.prev_day.to_time or
        item['date'] >= Date.today.to_time
    end.reverse!
  elsif opt[:age] =~ /oldest/i
    items = items[0..count]
  else
    items = items.reverse[0..count]
  end

  items.reverse! if opt[:order] =~ /^a/i

  out = ''

  exit_now! 'Unknown output format' if opt[:output] && (opt[:output] !~ /^(template|html|csv|json|timeline)$/i)

  case opt[:output]
  when /^csv$/i
    output = [CSV.generate_line(%w[date title note timer section])]
    items.each do |i|
      note = ''
      if i['note']
        arr = i['note'].map { |line| line.strip }.delete_if { |e| e =~ /^\s*$/ }
        note = arr.join("\n") unless arr.nil?
      end
      interval = get_interval(i, formatted: false) if i['title'] =~ /@done\((\d{4}-\d\d-\d\d \d\d:\d\d.*?)\)/ && opt[:times]
      interval ||= 0
      output.push(CSV.generate_line([i['date'], i['title'], note, interval, i['section']]))
    end
    out = output.join('')
  when /^(json|timeline)/i
    items_out = []
    max = items[-1]['date'].strftime('%F')
    min = items[0]['date'].strftime('%F')
    items.each_with_index do |i, index|
      if String.method_defined? :force_encoding
        title = i['title'].force_encoding('utf-8')
        note = i['note'].map { |line| line.force_encoding('utf-8').strip } if i['note']
      else
        title = i['title']
        note = i['note'].map { |line| line.strip } if i['note']
      end
      if i['title'] =~ /@done\((\d{4}-\d\d-\d\d \d\d:\d\d.*?)\)/ && opt[:times]
        end_date = Time.parse(Regexp.last_match(1))
        interval = get_interval(i, formatted: false)
      end
      end_date ||= ''
      interval ||= 0
      note ||= ''

      tags = []
      attributes = {}
      skip_tags = %w[meanwhile done cancelled flagged]
      i['title'].scan(/@([^(\s]+)(?:\((.*?)\))?/).each do |tag|
        tags.push(tag[0]) unless skip_tags.include?(tag[0])
        attributes[tag[0]] = tag[1] if tag[1]
      end

      if opt[:output] == 'json'

        i = {
          date: i['date'],
          end_date: end_date,
          title: title.strip, #+ " #{note}"
          note: note.instance_of?(Array) ? note.map(&:strip).join("\n") : note,
          time: '%02d:%02d:%02d' % fmt_time(interval),
          tags: tags
        }

        attributes.each { |attr, val| i[attr.to_sym] = val }

        items_out << i

      elsif opt[:output] == 'timeline'
        new_item = {
          'id' => index + 1,
          'content' => title.strip, #+ " #{note}"
          'title' => title.strip + " (#{'%02d:%02d:%02d' % fmt_time(interval)})",
          'start' => i['date'].strftime('%F %T'),
          'type' => 'point'
        }

        if interval && interval.to_i > 0
          new_item['end'] = end_date.strftime('%F %T')
          new_item['type'] = 'range' if interval.to_i > 3600 * 3
        end
        items_out.push(new_item)
      end
    end
    if opt[:output] == 'json'
      out = {
        'section' => section,
        'items' => items_out,
        'timers' => tag_times(format: 'json', sort_by_name: opt[:sort_tags], sort_order: opt[:tag_order])
      }.to_json
    elsif opt[:output] == 'timeline'
      template = "                  <!doctype html>\n                  <html>\n                  <head>\n                    <link href=\"https://unpkg.com/[email protected]/dist/vis-timeline-graph2d.min.css\" rel=\"stylesheet\" type=\"text/css\" />\n                    <script src=\"https://unpkg.com/[email protected]/dist/vis-timeline-graph2d.min.js\"></script>\n                  </head>\n                  <body>\n                    <div id=\"mytimeline\"></div>\n        \#{'          '}\n                    <script type=\"text/javascript\">\n                      // DOM element where the Timeline will be attached\n                      var container = document.getElementById('mytimeline');\n        \#{'          '}\n                      // Create a DataSet with data (enables two way data binding)\n                      var data = new vis.DataSet(\#{items_out.to_json});\n        \#{'          '}\n                      // Configuration for the Timeline\n                      var options = {\n                        width: '100%',\n                        height: '800px',\n                        margin: {\n                          item: 20\n                        },\n                        stack: true,\n                        min: '\#{min}',\n                        max: '\#{max}'\n                      };\n        \#{'          '}\n                      // Create a Timeline\n                      var timeline = new vis.Timeline(container, data, options);\n                    </script>\n                  </body>\n                  </html>\n      EOTEMPLATE\n      return template\n    end\n  when /^html$/i\n    page_title = section\n    items_out = []\n    items.each do |i|\n      # if i.has_key?('note')\n      #   note = '<span class=\"note\">' + i['note'].map{|n| n.strip }.join('<br>') + '</span>'\n      # else\n      #   note = ''\n      # end\n      if String.method_defined? :force_encoding\n        title = i['title'].force_encoding('utf-8').link_urls\n        note = i['note'].map { |line| line.force_encoding('utf-8').strip.link_urls } if i['note']\n      else\n        title = i['title'].link_urls\n        note = i['note'].map { |line| line.strip.link_urls } if i['note']\n      end\n\n      interval = get_interval(i) if i['title'] =~ /@done\\((\\d{4}-\\d\\d-\\d\\d \\d\\d:\\d\\d.*?)\\)/ && opt[:times]\n      interval ||= false\n\n      items_out << {\n        date: i['date'].strftime('%a %-I:%M%p'),\n        title: title.gsub(/(@[^ (]+(\\(.*?\\))?)/im, '<span class=\"tag\">\\1</span>').strip, #+ \" \#{note}\"\n        note: note,\n        time: interval,\n        section: i['section']\n      }\n    end\n\n    template = if @config['html_template']['haml'] && File.exist?(File.expand_path(@config['html_template']['haml']))\n                 IO.read(File.expand_path(@config['html_template']['haml']))\n               else\n                 haml_template\n               end\n\n    style = if @config['html_template']['css'] && File.exist?(File.expand_path(@config['html_template']['css']))\n              IO.read(File.expand_path(@config['html_template']['css']))\n            else\n              css_template\n            end\n\n    totals = opt[:totals] ? tag_times(format: 'html', sort_by_name: opt[:sort_tags], sort_order: opt[:tag_order]) : ''\n    engine = Haml::Engine.new(template)\n    out = engine.render(Object.new,\n                       { :@items => items_out, :@page_title => page_title, :@style => style, :@totals => totals })\n  else\n    items.each do |item|\n      if opt[:highlight] && item['title'] =~ /@\#{@config['marker_tag']}\\b/i\n        flag = colors[@config['marker_color']]\n        reset = colors['default']\n      else\n        flag = ''\n        reset = ''\n      end\n\n      if (item.key?('note') && !item['note'].empty?) && @config[:include_notes]\n        note_lines = item['note'].delete_if do |line|\n          line =~ /^\\s*$/\n        end\n        note_lines.map! { |line| \"\\t\\t\#{line.sub(/^\\t*/, '').sub(/^-/, '\u2014')}  \" }\n        if opt[:wrap_width]&.positive?\n          width = opt[:wrap_width]\n          note_lines.map! do |line|\n            line.strip.gsub(/(.{1,\#{width}})(\\s+|\\Z)/, \"\\t\\\\1\\n\")\n          end\n        end\n        note = \"\\n\#{note_lines.join(\"\\n\").chomp}\"\n      else\n        note = ''\n      end\n      output = opt[:template].dup\n\n      output.gsub!(/%[a-z]+/) do |m|\n        if colors.key?(m.sub(/^%/, ''))\n          colors[m.sub(/^%/, '')]\n        else\n          m\n        end\n      end\n\n      output.sub!(/%date/, item['date'].strftime(opt[:format]))\n\n      interval = get_interval(item, record: true) if item['title'] =~ /@done\\((\\d{4}-\\d\\d-\\d\\d \\d\\d:\\d\\d.*?)\\)/ && opt[:times]\n      interval ||= ''\n      output.sub!(/%interval/, interval)\n\n      output.sub!(/%shortdate/) do\n        if item['date'] > Date.today.to_time\n          item['date'].strftime('    %_I:%M%P')\n        elsif item['date'] > (Date.today - 6).to_time\n          item['date'].strftime('%a %_I:%M%P')\n        elsif item['date'].year == Date.today.year\n          item['date'].strftime('%m/%d %_I:%M%P')\n        else\n          item['date'].strftime('%m/%d/%Y %_I:%M%P')\n        end\n      end\n\n      output.sub!(/%title/) do |_m|\n        if opt[:wrap_width] && opt[:wrap_width] > 0\n          flag + item['title'].gsub(/(.{1,\#{opt[:wrap_width]}})(\\s+|\\Z)/, \"\\\\1\\n\\t \").chomp + reset\n        else\n          flag + item['title'].chomp + reset\n        end\n      end\n\n      output.sub!(/%section/, item['section']) if item['section']\n\n      if opt[:tags_color]\n        escapes = output.scan(/(\\e\\[[\\d;]+m)[^\\e]+@/)\n        last_color = if escapes.length > 0\n                       escapes[-1][0]\n                     else\n                       colors['default']\n                     end\n        output.gsub!(/(\\s|m)(@[^ (]+)/, \"\\\\1\#{colors[opt[:tags_color]]}\\\\2\#{last_color}\")\n      end\n      output.sub!(/%note/, note)\n      output.sub!(/%odnote/, note.gsub(/^\\t*/, ''))\n      output.sub!(/%chompnote/, note.gsub(/\\n+/, ' ').gsub(/(^\\s*|\\s*$)/, '').gsub(/\\s+/, ' '))\n      output.gsub!(/%hr(_under)?/) do |_m|\n        o = ''\n        `tput cols`.to_i.times do\n          o += Regexp.last_match(1).nil? ? '-' : '_'\n        end\n        o\n      end\n      output.gsub!(/%n/, \"\\n\")\n      output.gsub!(/%t/, \"\\t\")\n\n      out += \"\#{output}\\n\"\n    end\n\n    out += tag_times(format: 'text', sort_by_name: opt[:sort_tags], sort_order: opt[:tag_order]) if opt[:totals]\n  end\n  out\nend\n"

#move_item(item, section) ⇒ Object



1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
# File 'lib/doing/wwid.rb', line 1194

def move_item(item, section)
  old_section = item['section']
  new_item = item.dup
  new_item['section'] = section

  section_items = @content[old_section]['items']
  section_items.delete(item)
  @content[old_section]['items'] = section_items

  archive_items = @content[section]['items']
  archive_items.push(new_item)
  # archive_items = archive_items.sort_by { |item| item['date'] }
  @content[section]['items'] = archive_items

  @results.push("Entry moved to #{section}: #{new_item['title']}")
  return new_item
end

#next_item(old_item) ⇒ Object

Parameters:

  • old_item


1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
# File 'lib/doing/wwid.rb', line 1217

def next_item(old_item)
  section = old_item['section']

  section_items = @content[section]['items'].sort_by { |entry| entry['date'] }
  idx = section_items.index(old_item)

  if section_items.size > idx
    section_items[idx + 1]
  else
    nil
  end
end

#note_last(section, note, replace: false) ⇒ Object

Parameters:

  • section (String)

    The section, default “All”

  • note (String)

    The note to add

  • replace (Bool) (defaults to: false)

    Should replace existing note



1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
# File 'lib/doing/wwid.rb', line 1397

def note_last(section, note, replace: false)
  section = guess_section(section)

  if section =~ /^all$/i
    combined = { 'items' => [] }
    @content.each do |_k, v|
      combined['items'] += v['items']
    end
    section = combined['items'].dup.sort_by { |item| item['date'] }.reverse[0]['section']
  end

  exit_now! "Section #{section} not found" unless @content.key?(section)

  # sort_section(opt[:section])
  items = @content[section]['items'].dup.sort_by { |item| item['date'] }.reverse

  current_note = items[0]['note']
  current_note = [] if current_note.nil?
  title = items[0]['title']
  if replace
    items[0]['note'] = note
    if note.empty? && !current_note.empty?
      @results.push(%(Removed note from "#{title}"))
    elsif !current_note.empty? && !note.empty?
      @results.push(%(Replaced note from "#{title}"))
    elsif !note.empty?
      @results.push(%(Added note to "#{title}"))
    else
      @results.push(%(Entry "#{title}" has no note))
    end
  elsif current_note.instance_of?(Array)
    items[0]['note'] = current_note.concat(note)
    @results.push(%(Added note to "#{title}")) unless note.empty?
  else
    items[0]['note'] = note
    @results.push(%(Added note to "#{title}")) unless note.empty?
  end

  @content[section]['items'] = items

end

#overlapping_time?(item_a, item_b) ⇒ Boolean

Returns:

  • (Boolean)


591
592
593
594
595
596
597
598
599
600
601
# File 'lib/doing/wwid.rb', line 591

def overlapping_time?(item_a, item_b)
  return true if same_time?(item_a, item_b)

  start_a = item_a['date']
  interval = get_interval(item_a, formatted: false, record: false)
  end_a = interval ? start_a + interval.to_i : start_a
  start_b = item_b['date']
  interval = get_interval(item_b,  formatted: false, record: false)
  end_b = interval ? start_b + interval.to_i : start_b
  (start_a >= start_b && start_a <= end_b) || (end_a >= start_b && end_a <= end_b) || (start_a < start_b && end_a > end_b)
end

#read_config(opt = {}) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/doing/wwid.rb', line 50

def read_config(opt = {})
  @config_file ||= if Dir.respond_to?('home')
                     File.join(Dir.home, @default_config_file)
                   else
                     File.join(File.expand_path('~'), @default_config_file)
                   end

  additional_configs = if opt[:ignore_local]
                         []
                       else
                         find_local_config
                       end

  begin
    @local_config = {}

    @config = YAML.load_file(@config_file) || {} if File.exist?(@config_file)
    additional_configs.each do |cfg|
      new_config = YAML.load_file(cfg) || {} if cfg
      @local_config = @local_config.deep_merge(new_config)
    end

    # @config.deep_merge(@local_config)
  rescue StandardError
    @config = {}
    @local_config = {}
    # exit_now! "error reading config"
  end
end

#recent(count = 10, section = nil, opt = {}) ⇒ Object

Parameters:

  • count (Integer) (defaults to: 10)

    The number to show

  • section (String) (defaults to: nil)

    The section to show from, default Currently

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

    Additional Options



2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
# File 'lib/doing/wwid.rb', line 2271

def recent(count = 10, section = nil, opt = {})
  times = opt[:t] || true
  opt[:totals] ||= false
  opt[:sort_tags] ||= false

  cfg = @config['templates']['recent']
  section ||= @current_section
  section = guess_section(section)

  list_section({ section: section, wrap_width: cfg['wrap_width'], count: count,
                 format: cfg['date_format'], template: cfg['template'],
                 order: 'asc', times: times, totals: opt[:totals],
                 sort_tags: opt[:sort_tags], tags_color: opt[:tags_color] })
end

#restart_last(opt = {}) ⇒ Object

Parameters:

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

    Additional Options



708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
# File 'lib/doing/wwid.rb', line 708

def restart_last(opt = {})
  opt[:section] ||= 'all'
  opt[:note] ||= []
  opt[:tag] ||= []
  opt[:tag_bool] ||= :and

  last = last_entry(opt)
  if last.nil?
    @results.push(%(No previous entry found))
    return
  end
  unless last.has_tags?(['done'], 'ALL')
    new_item = last.dup
    new_item['title'] += " @done(#{Time.now.strftime('%F %R')})"
    update_item(last, new_item)
  end
  # Remove @done tag
  title = last['title'].sub(/\s*@done(\(.*?\))?/, '').chomp
  section = opt[:in].nil? ? last['section'] : guess_section(opt[:in])
  @auto_tag = false
  add_item(title, section, { note: opt[:note], back: opt[:date], timed: true })
  write(@doing_file)
end

#restore_backup(file) ⇒ Object

Parameters:

  • file (String)

    The filepath to restore



1535
1536
1537
1538
1539
1540
1541
# File 'lib/doing/wwid.rb', line 1535

def restore_backup(file)
  if File.exist?(file + '~')
    puts file + '~'
    FileUtils.cp(file + '~', file)
    @results.push("Restored #{file}")
  end
end

#rotate(opt = {}) ⇒ Object



1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
# File 'lib/doing/wwid.rb', line 1546

def rotate(opt = {})
  count = opt[:keep] || 0
  tags = []
  tags.concat(opt[:tag].split(/ *, */).map { |t| t.sub(/^@/, '').strip }) if opt[:tag]
  bool  = opt[:bool] || :and
  sect = opt[:section] !~ /^all$/i ? guess_section(opt[:section]) : 'all'

  if sect =~ /^all$/i
    all_sections = sections.dup
  else
    all_sections = [sect]
  end

  counter = 0
  new_content = {}


  all_sections.each do |section|
    items = @content[section]['items'].dup
    new_content[section] = {}
    new_content[section]['original'] = @content[section]['original']
    new_content[section]['items'] = []

    moved_items = []
    if !tags.empty? || opt[:search] || opt[:before]
      if opt[:before]
        time_string = opt[:before]
        time_string += ' 12am' if time_string !~ /(\d+:\d+|\d+[ap])/
        cutoff = chronify(time_string)
      end

      items.delete_if do |item|
        if ((!tags.empty? && item.has_tags?(tags, bool)) || (opt[:search] && item.matches_search?(opt[:search].to_s)) || (opt[:before] && item['date'] < cutoff))
          moved_items.push(item)
          counter += 1
          true
        else
          false
        end
      end
      @content[section]['items'] = items
      new_content[section]['items'] = moved_items
      @results.push("Rotated #{moved_items.length} items from #{section}")
    else
      new_content[section]['items'] = []
      moved_items = []

      count = items.length if items.length < count

      if items.count > count
        moved_items.concat(items[count..-1])
      else
        moved_items.concat(items)
      end

      @content[section]['items'] = if count.zero?
                                     []
                                   else
                                     items[0..count - 1]
                                   end
      new_content[section]['items'] = moved_items

      @results.push("Rotated #{items.length - count} items from #{section}")
    end
  end

  write(@doing_file)

  file = @doing_file.sub(/(\.\w+)$/, "_#{Time.now.strftime('%Y-%m-%d')}\\1")
  if File.exist?(file)
    init_doing_file(file)
    @content.deep_merge(new_content)
  else
    @content = new_content
  end

  write(file, backup: false)
end

#same_time?(item_a, item_b) ⇒ Boolean

Returns:

  • (Boolean)


587
588
589
# File 'lib/doing/wwid.rb', line 587

def same_time?(item_a, item_b)
  item_a['date'] == item_b['date'] ? get_interval(item_a, formatted: false, record: false) == get_interval(item_b,  formatted: false, record: false) : false
end

#stop_start(target_tag, opt = {}) ⇒ Object

Parameters:

  • tag (String)

    Tag to replace

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

    Additional Options



1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
# File 'lib/doing/wwid.rb', line 1449

def stop_start(target_tag, opt = {})
  tag = target_tag.dup
  opt[:section] ||= @current_section
  opt[:archive] ||= false
  opt[:back] ||= Time.now
  opt[:new_item] ||= false
  opt[:note] ||= false

  opt[:section] = guess_section(opt[:section])

  tag.sub!(/^@/, '')

  found_items = 0
  @content[opt[:section]]['items'].each_with_index do |item, i|
    next unless item['title'] =~ /@#{tag}/

    title = item['title'].gsub(/(^| )@(#{tag}|done)(\([^)]*\))?/, '')
    title += " @done(#{opt[:back].strftime('%F %R')})"

    @content[opt[:section]]['items'][i]['title'] = title
    found_items += 1

    if opt[:archive] && opt[:section] != 'Archive'
      @results.push(%(Completed and archived "#{@content[opt[:section]]['items'][i]['title']}"))
      archive_item = @content[opt[:section]]['items'][i]
      archive_item['title'] = i['title'].sub(/(?:@from\(.*?\))?(.*)$/, "\\1 @from(#{i['section']})")
      @content['Archive']['items'].push(archive_item)
      @content[opt[:section]]['items'].delete_at(i)
    else
      @results.push(%(Completed "#{@content[opt[:section]]['items'][i]['title']}"))
    end
  end

  @results.push("No active @#{tag} tasks found.") if found_items == 0

  if opt[:new_item]
    title, note = format_input(opt[:new_item])
    note.push(opt[:note].map(&:chomp)) if opt[:note]
    title += " @#{tag}"
    add_item(title.cap_first, opt[:section], { note: note.join(' ').rstrip, back: opt[:back] })
  end

  write(@doing_file)
end

#tag_item(old_item, tags, remove: false, date: false) ⇒ Object

Parameters:

  • old_item (Item)

    The item to tag

  • tag (string)

    The tag to apply

  • date (Boolean) (defaults to: false)

    Include timestamp?



1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
# File 'lib/doing/wwid.rb', line 1278

def tag_item(old_item, tags, remove: false, date: false)
  title = old_item['title'].dup
  if tags.is_a? ::String
    tags = tags.split(/ *, */).map(&:strip)
  end

  done_date = Time.now
  tags.each do |tag|
    if title !~ /@#{tag}/
      title.chomp!
      if date
        title += " @#{tag}(#{done_date.strftime('%F %R')})"
      else
        title += " @#{tag}"
      end
      new_item = old_item.dup
      new_item['title'] = title
      update_item(old_item, new_item)
      return new_item
    else
      @results.push(%(Item already @#{tag}: "#{title}" in #{old_item['section']}))
      return old_item
    end
  end
end

#tag_last(opt = {}) ⇒ Object

Parameters:

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

    Additional Options



1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
# File 'lib/doing/wwid.rb', line 1054

def tag_last(opt = {})
  opt[:section] ||= nil
  opt[:count] ||= 1
  opt[:archive] ||= false
  opt[:tags] ||= ['done']
  opt[:sequential] ||= false
  opt[:date] ||= false
  opt[:remove] ||= false
  opt[:autotag] ||= false
  opt[:back] ||= false
  opt[:took] ||= nil
  opt[:unfinished] ||= false

  sec_arr = []

  if opt[:section].nil?
    if opt[:search] || opt[:tag]
      sec_arr = sections
    else
      sec_arr = [@current_section]
    end
  elsif opt[:section].instance_of?(String)
    if opt[:section] =~ /^all$/i
      if opt[:count] == 1
        combined = { 'items' => [] }
        @content.each do |_k, v|
          combined['items'] += v['items']
        end
        items = combined['items'].dup.sort_by { |item| item['date'] }.reverse
        sec_arr.push(items[0]['section'])
      elsif opt[:count] > 1
        if opt[:search] || opt[:tag]
          sec_arr = sections
        else
          exit_now! 'A count greater than one requires a section to be specified'
        end
      else
        sec_arr = sections
      end
    else
      sec_arr = [guess_section(opt[:section])]
    end
  end

  sec_arr.each do |section|
    if @content.key?(section)

      items = @content[section]['items'].dup.sort_by { |item| item['date'] }.reverse
      idx = 0
      done_date = Time.now
      count = (opt[:count]).zero? ? items.length : opt[:count]
      items.map! do |item|
        break if idx == count
        finished = opt[:unfinished] && item.has_tags?('done', :and)
        tag_match = opt[:tag].nil? || opt[:tag].empty? ? true : item.has_tags?(opt[:tag], opt[:tag_bool])
        search_match = opt[:search].nil? || opt[:search].empty? ? true : item.matches_search?(opt[:search])

        if tag_match && search_match && !finished
          if opt[:autotag]
            new_title = autotag(item['title']) if @auto_tag
            if new_title == item['title']
              @results.push(%(Autotag: No changes))
            else
              @results.push("Tags updated: #{new_title}")
              item['title'] = new_title
            end
          else
            if opt[:sequential]
              next_entry = next_item(item)
              done_date = next_entry['date'] - 60 if next_entry
            elsif opt[:took]
              if item['date'] + opt[:took] > Time.now
                item['date'] = Time.now - opt[:took]
                done_date = Time.now
              else
                done_date = item['date'] + opt[:took]
              end
            elsif opt[:back]
              if opt[:back].is_a? Integer
                done_date = item['date'] + opt[:back]
              else
                done_date = item['date'] + (opt[:back] - item['date'])
              end
            else
              done_date = Time.now
            end

            title = item['title']
            opt[:tags].each do |tag|
              tag = tag.strip
              if opt[:remove]
                if title =~ /@#{tag}\b/
                  title.gsub!(/(^| )@#{tag}(\([^)]*\))?/, '')
                  @results.push(%(Removed @#{tag}: "#{title}" in #{section}))
                end
              elsif title !~ /@#{tag}/
                title.chomp!
                title += if opt[:date]
                           " @#{tag}(#{done_date.strftime('%F %R')})"
                         else
                           " @#{tag}"
                         end
                @results.push(%(Added @#{tag}: "#{title}" in #{section}))
              end
            end
            item['title'] = title
          end

          idx += 1
        end

        item
      end

      @content[section]['items'] = items

      if opt[:archive] && section != 'Archive' && (opt[:count]).positive?
        # concat [count] items from [section] and archive section
        archived = @content[section]['items'][0..opt[:count] - 1].map do |i|
          i['title'].sub!(/(?:@from\(.*?\))?(.*)$/, "\\1 @from(#{i['section']})")
          i
        end.concat(@content['Archive']['items'])
        # slice [count] items off of [section] items
        @content[opt[:section]]['items'] = @content[opt[:section]]['items'][opt[:count]..-1]
        # overwrite archive section with concatenated array
        @content['Archive']['items'] = archived
        # log it
        result = opt[:count] == 1 ? '1 entry' : "#{opt[:count]} entries"
        @results.push("Archived #{result} from #{section}")
      elsif opt[:archive] && (opt[:count]).zero?
        @results.push('Archiving is skipped when operating on all entries') if (opt[:count]).zero?
      end
    else
      exit_now! "Section not found: #{section}"
    end
  end

  write(@doing_file)
end

#tag_times(format: 'text', sort_by_name: false, sort_order: 'asc') ⇒ Object

Parameters:

  • format (String) (defaults to: 'text')

    return format (html, json, or text)

  • sort_by_name (Boolean) (defaults to: false)

    Sort by name if true, otherwise by time

  • sort_order (String) (defaults to: 'asc')

    The sort order (asc or desc)



2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
# File 'lib/doing/wwid.rb', line 2326

def tag_times(format: 'text', sort_by_name: false, sort_order: 'asc')
  return '' if @timers.empty?

  max = @timers.keys.sort_by { |k| k.length }.reverse[0].length + 1

  total = @timers.delete('All')

  tags_data = @timers.delete_if { |_k, v| v == 0 }
  sorted_tags_data = if sort_by_name
                       tags_data.sort_by { |k, _v| k }
                     else
                       tags_data.sort_by { |_k, v| v }
                     end

  sorted_tags_data.reverse! if sort_order =~ /^asc/i

  if format == 'html'
    output = "      <table>\n      <caption id=\"tagtotals\">Tag Totals</caption>\n      <colgroup>\n      <col style=\"text-align:left;\"/>\n      <col style=\"text-align:left;\"/>\n      </colgroup>\n      <thead>\n      <tr>\n        <th style=\"text-align:left;\">project</th>\n        <th style=\"text-align:left;\">time</th>\n      </tr>\n      </thead>\n      <tbody>\n"
    sorted_tags_data.reverse.each do |k, v|
      if v > 0
        output += "<tr><td style='text-align:left;'>#{k}</td><td style='text-align:left;'>#{'%02d:%02d:%02d' % fmt_time(v)}</td></tr>\n"
      end
    end
    tail = "    <tr>\n      <td style=\"text-align:left;\" colspan=\"2\"></td>\n    </tr>\n    </tbody>\n    <tfoot>\n    <tr>\n      <td style=\"text-align:left;\"><strong>Total</strong></td>\n      <td style=\"text-align:left;\">\#{'%02d:%02d:%02d' % fmt_time(total)}</td>\n    </tr>\n    </tfoot>\n    </table>\n"
    output + tail
  elsif format == 'json'
    output = []
    sorted_tags_data.reverse.each do |k, v|
      output << {
        'tag' => k,
        'seconds' => v,
        'formatted' => '%02d:%02d:%02d' % fmt_time(v)
      }
    end
    output
  else
    output = []
    sorted_tags_data.reverse.each do |k, v|
      spacer = ''
      (max - k.length).times do
        spacer += ' '
      end
      output.push("#{k}:#{spacer}#{'%02d:%02d:%02d' % fmt_time(v)}")
    end

    output = output.empty? ? '' : "\n--- Tag Totals ---\n" + output.join("\n")
    output += "\n\nTotal tracked: #{'%02d:%02d:%02d' % fmt_time(total)}\n"
    output
  end
end

#today(times = true, output = nil, opt = {}) ⇒ Object

Parameters:

  • times (Boolean) (defaults to: true)

    show times

  • output (String) (defaults to: nil)

    output format

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

    Options



2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
# File 'lib/doing/wwid.rb', line 2205

def today(times = true, output = nil, opt = {})
  opt[:totals] ||= false
  opt[:sort_tags] ||= false

  cfg = @config['templates']['today']
  options = {
    after: opt[:after],
    before: opt[:before],
    count: 0,
    format: cfg['date_format'],
    order: 'asc',
    output: output,
    section: opt[:section],
    sort_tags: opt[:sort_tags],
    template: cfg['template'],
    times: times,
    today: true,
    totals: opt[:totals],
    wrap_width: cfg['wrap_width']
  }
  list_section(options)
end

#untag_item(old_item, tags) ⇒ Object

Parameters:

  • old_item (Item)

    The item to tag

  • tag (string)

    The tag to remove



1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
# File 'lib/doing/wwid.rb', line 1250

def untag_item(old_item, tags)
  title = old_item['title'].dup
  if tags.is_a? ::String
    tags = tags.split(/ *, */).map {|t| t.strip.gsub(/\*/,'[^ (]*') }
  end

  tags.each do |tag|
    if title =~ /@#{tag}/
      title.chomp!
      title.gsub!(/ +@#{tag}(\(.*?\))?/, '')
      new_item = old_item.dup
      new_item['title'] = title
      update_item(old_item, new_item)
      return new_item
    else
      @results.push(%(Item isn't tagged @#{tag}: "#{title}" in #{old_item['section']}))
      return old_item
    end
  end
end

#update_item(old_item, new_item) ⇒ Object

Parameters:

  • old_item

    The old item

  • new_item

    The new item



1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
# File 'lib/doing/wwid.rb', line 1310

def update_item(old_item, new_item)
  section = old_item['section']

  section_items = @content[section]['items']
  s_idx = section_items.index(old_item)

  section_items[s_idx] = new_item
  @results.push("Entry updated: #{section_items[s_idx]['title']}")
  @content[section]['items'] = section_items
end

#viewsArray

Returns View names.

Returns:

  • (Array)

    View names



1640
1641
1642
# File 'lib/doing/wwid.rb', line 1640

def views
  @config.has_key?('views') ? @config['views'].keys : []
end

#write(file = nil, backup: true) ⇒ Object

Parameters:

  • file (String) (defaults to: nil)

    The filepath to write to



1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
# File 'lib/doing/wwid.rb', line 1499

def write(file = nil, backup: true)
  output = @other_content_top ? "#{@other_content_top.join("\n")}\n" : ''

  @content.each do |title, section|
    output += "#{section['original']}\n"
    output += list_section({ section: title, template: "\t- %date | %title%note", highlight: false })
  end
  output += @other_content_bottom.join("\n") unless @other_content_bottom.nil?
  if file.nil?
    $stdout.puts output
  else
    file = File.expand_path(file)
    if File.exist?(file) && backup
      # Create a backup copy for the undo command
      FileUtils.cp(file, "#{file}~")
    end

    File.open(file, 'w+') do |f|
      f.puts output
    end

    if @config.key?('run_after')
      stdout, stderr, status = Open3.capture3(@config['run_after'])
      if status.exitstatus.positive?
        warn "Error running #{@config['run_after']}"
        warn stderr
      end
    end
  end
end

#yesterday(section, times = nil, output = nil, opt = {}) ⇒ Object

Parameters:

  • section (String)

    The section

  • times (Bool) (defaults to: nil)

    Show times

  • output (String) (defaults to: nil)

    Output format

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

    Additional Options



2256
2257
2258
2259
2260
2261
2262
# File 'lib/doing/wwid.rb', line 2256

def yesterday(section, times = nil, output = nil, opt = {})
  opt[:totals] ||= false
  opt[:sort_tags] ||= false
  section = guess_section(section)
  list_section({ section: section, count: 0, order: 'asc', yesterday: true, times: times,
                 output: output, totals: opt[:totals], sort_tags: opt[:sort_tags] })
end

#yn(question, default_response: false) ⇒ Bool

Returns yes or no.

Parameters:

  • question (String)

    The question to ask

  • default (Bool)

    default response if no input

Returns:

  • (Bool)

    yes or no



466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# File 'lib/doing/wwid.rb', line 466

def yn(question, default_response: false)
  default = default_response ? default_response : 'n'

  # if this isn't an interactive shell, answer default
  return default.downcase == 'y' unless $stdout.isatty

  # clear the buffer
  if ARGV&.length
    ARGV.length.times do
      ARGV.shift
    end
  end
  system 'stty cbreak'

  cw = colors['white']
  cbw = colors['boldwhite']
  cbg = colors['boldgreen']
  cd = colors['default']

  options = if default
              default =~ /y/i ? "#{cw}[#{cbg}Y#{cw}/#{cbw}n#{cw}]#{cd}" : "#{cw}[#{cbw}y#{cw}/#{cbg}N#{cw}]#{cd}"
            else
              "#{cw}[#{cbw}y#{cw}/#{cbw}n#{cw}]#{cd}"
            end
  $stdout.syswrite "#{cbw}#{question.sub(/\?$/, '')} #{options}#{cbw}?#{cd} "
  res = $stdin.sysread 1
  puts
  system 'stty cooked'

  res.chomp!
  res.downcase!

  res = default.downcase if res == ''

  res =~ /y/i
end